You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "rekbun (via GitHub)" <gi...@apache.org> on 2026/10/15 19:13:37 UTC
[PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
rekbun opened a new pull request, #59522:
URL: https://github.com/apache/spark/pull/59522
### What changes were proposed in this pull request?
Add `spark.sql.sources.v2.bucketing.groupScanPartitions.enabled`, default `false`, to group scan splits sharing a reported partition key even when a downstream shuffle makes grouping unnecessary for correctness.
- Insert `GroupPartitionsExec` above eligible V2 scans when the setting is enabled.
- Mark grouping requested for scan task sizing and preserve it when `EnsureRequirements` removes grouping used for join alignment.
- Preserve the marker through copying, canonicalization, and join-key projection.
- Document the configuration and add plan and execution regressions.
### Why are the changes needed?
[SPARK-60265](https://issues.apache.org/jira/browse/SPARK-60265).
The SPJ refactor in [PR #54330](https://github.com/apache/spark/pull/54330) deliberately leaves scans ungrouped when a downstream shuffle makes grouping unnecessary (SPARK-55092).
For V2 sources exposing many small physical splits per bucket, this can leave one scan task per split. A large number of scan tasks can consume significant scan-stage time through repeated task launch, setup, execution, and cleanup, increasing overall query latency. This patch provides explicit control over scan task sizing for these sources.
The reproducer has two buckets with 24 physical splits each. An aggregation by a non-partition column requires a shuffle and executes 48 scan tasks by default. With the setting enabled, it executes two scan tasks, with identical query results.
### Does this PR introduce _any_ user-facing change?
Yes: a new configuration, default `false`. It requires `spark.sql.sources.v2.bucketing.enabled` and usable reported partition keys surviving column pruning. Unique-key and unpartitioned scans are unaffected.
```sql
SET spark.sql.sources.v2.bucketing.enabled=true;
SET spark.sql.sources.v2.bucketing.groupScanPartitions.enabled=true;
```
Grouping can reduce scan-stage time by amortizing per-task costs across many small splits. Large or skewed keys can lose parallelism and produce longer tasks, so the behavior remains opt-in. Existing default scan behavior and the SPARK-55092 regression test are preserved.
### How was this patch tested?
46 focused tests passed:
- Five `KeyGroupedPartitioningSuite` cases, including SPARK-55092, the bucketed aggregation and shuffled join, unique and unpartitioned scans, and V2 bucketing disabled.
- One runtime-pruning case against each of the connector and Catalyst filter interfaces, including partially and fully pruned buckets.
- Four `EnsureRequirementsSuite` cases covering grouping preservation, peeling, join-key projection, copying, and canonicalization.
- All 35 `GroupPartitionsExecSuite` cases, including sorted-merge ordering coverage.
The aggregation runs with AQE on and off. The join runs with AQE and the one-side-shuffle optimization independently on and off. The tests execute the scan-stage RDD and return one row count per task: 48 one-row tasks with grouping disabled, and two 24-row tasks with it enabled. Runtime pruning verifies task row counts `[0, 24]` and `[0, 0]` with correct query results.
```bash
build/sbt \
'sql/testOnly *KeyGroupedPartitioningSuite *KeyGroupedPartitioningRuntimeFilterSuite *KeyGroupedPartitioningCatalystRuntimeFilterSuite -- -z "Scans should not group partitions" -z "opt-in scan grouping"' \
'sql/testOnly *EnsureRequirementsSuite -- -z "scan grouping" -z "peel" -z "withJoinKeyPositions"' \
'sql/testOnly *GroupPartitionsExecSuite'
build/sbt 'catalyst/scalastyle' 'sql/scalastyle' 'sql/Test/scalastyle'
```
Catalyst main, SQL main, and SQL test scalastyle checks passed. The task-count reduction was verified; wall-clock latency improvements have not been benchmarked.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4498499223
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
Review Comment:
Done in dc626a7c49a: `FileScan`s are excluded, with your 8-file Parquet case as a test.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2644,6 +2644,61 @@ object SQLConf {
.booleanConf
.createWithDefault(true)
+ val V2_SCAN_PARTITION_PACKING_ENABLED =
Review Comment:
Done in dc626a7c49a: the configs follow `FILES_MAX_PARTITION_NUM`.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "spark-test (via GitHub) via reviews" <re...@spark.apache.org>.
spark-test commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4697838485
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,112 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
+
+When every input of a scan reports a non-negative `HasPartitionStatistics.sizeInBytes()`, Spark
+packs consecutive inputs into tasks as it packs files: a file joins the current task unless its size
+would take the task past the target, and an input joins only if all of the files it reports would.
+Each input adds its size plus an opening cost for each file it reports through
+`HasPartitionStatistics.filesCount()`, and at least one. Unlike files, which Spark sorts by size
+before packing, the inputs keep the order the scan reads them in. The suggested minimum count helps
+retain parallelism for small scans. Packing never divides a connector input, however large.
+Reported sizes are estimates, so this is not a bound on runtime memory or CPU. As with
+`spark.sql.files.maxPartitionNum`, when packing by size gives more tasks than
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum`, Spark packs the inputs again with a
+target of the scan's total size divided by that cap, ignoring
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes`. If any input of a scan reports no
+valid size, Spark leaves the scan's inputs as they are, unless
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum` is set. Then it groups all of the scan's
+inputs by count into at most that many tasks, which balances input counts, not bytes. This applies
+to any eligible V2 scan with such an input, such as a scan of a Python data source or of a connector
+whose inputs do not implement `HasPartitionStatistics`, but not to file-based V2 sources.
+
+Spark decides the tasks when the shuffle's map stage runs, from the inputs that runtime filtering,
+such as dynamic partition pruning, leaves. An input that runtime filtering emptied joins the task of
+the input before it, or the first task when no input precedes it, even when Spark leaves the other
+inputs as they are. EXPLAIN shows a `PackScanPartitions` node between the scan and the shuffle, and
+its SQL metrics show the number of input partitions, the number of partitions it packed them into,
+and the largest number of input partitions in one partition. The operators above the node run once
+per packed task, so a partial aggregation there emits its rows per task, and built-in expressions
+there that take the partition index, such as `spark_partition_id()`, see the packed task's index.
+The operators below the node, if any, run as they do without packing, once per input, and
+`spark_partition_id()` there sees the input's index. Code that reads `TaskContext.partitionId()`,
+such as a UDF, sees the packed task's index wherever it runs, and so does the shuffle, so a
+round-robin repartition can place rows differently. Packing can reduce useful parallelism, and fewer
Review Comment:
**Non-blocking (P2):** This list of what enabling packing costs leaves out locality. For a task that packs several inputs, `GroupedPartitionCoalescer` names only the host that more of those inputs prefer than any other host; when no host is ahead it names none, and the scheduler offers the locations of the task's first input that names any. Inputs of the task whose hosts are not the ones it is offered are then read away from the hosts their `preferredLocations()` name, while on the base branch each input is its own task, offered its own hosts. In the review's model of the head code, 4,000 inputs of 8 MB placed round-robin over 20 hosts pack about eleven to a task at the defaults, no host is ahead in any task, and about 91% of the bytes are read away from their preferred host. For a connector that reads host-local data, this adds network I/O that the documentation does not warn users about when they turn the option on; whether the saved scheduling outweighs it depends on input size
s and placement.
Stating it in this list, in the paragraph of `docs/sql-v2-data-sources.md` that follows the `preferredLocations()` sentence, and in the doc of `spark.sql.sources.v2.scanPartitionPacking.enabled` would make it a disclosed trade-off of the opt-in path, for example: "A task that packs several inputs prefers the host that more of them prefer than any other host or, when no host is ahead, the locations of the first of them that names any, so inputs that prefer other hosts can be read remotely." A shorter "prefers the host most of its inputs prefer" would misstate the tie case, where the first input's hosts need not be among the tied hosts. Grouping inputs by host is a separate design choice that this does not ask for.
**Verification:**
- **Inspection:** The DataSource V2 Scan Partition Packing section of the tuning guide, the DataSource V2 guide's paragraph on preferredLocations() and packing, and the doc of spark.sql.sources.v2.scanPartitionPacking.enabled each state that the inputs of a packed task can be read away from the hosts they prefer, and wherever they say which hosts a task of several inputs prefers, they match GroupedPartitionCoalescer.preferredLocation and the scheduler's fallback: the host that more of the task's inputs prefer than any other host or, when no host is ahead, the locations of the first input that names any.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446983971
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -1461,5 +1461,6 @@ case class EnsureRequirements(
} else {
newPlan
}
+ PackV2ScanPartitions(finalPlan, requiredDistribution)
Review Comment:
Done. `PackV2ScanPartitions` now runs as its own rule right after `StampUnionDecisions`, and `EnsureRequirements` is unchanged from 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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4720517805
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{FilterExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.BroadcastHashJoinExec
+
+/**
+ * Packs the partitions of a V2 batch scan that a shuffle reads, with `PackScanPartitionsExec`,
+ * when the shuffle's child reads one scan through operators that compute each of their partitions
+ * from one scan partition: projects, filters, sorts, partial aggregates and the streamed side of a
+ * broadcast hash join. The list starts from the operators that `DisableUnnecessaryBucketedScan`
+ * allows; others that also map partitions one to one, such as expand and generate, are not packed
+ * yet. Scans of file-based V2 sources are left to `spark.sql.files.*`, as V1 file scans are.
+ *
+ * The node reports no partitioning and no ordering, so it goes at the lowest point on that path
+ * where the plan still meets every operator's requirements, checked with `ValidateRequirements`.
+ * That is directly above the scan unless an operator on the path relies on the scan's ordering,
+ * such as a partial sort aggregate with no sort between it and the scan. The node then goes above
+ * that operator. Directly below the shuffle is the last candidate, and is kept even if the check
+ * fails there, since a shuffle requires nothing of its child. The operators above the node run
+ * once per packed partition, and those below it once per input.
+ *
+ * Above the shuffle, only an AQE local read with one mapper per task reports the layout from
+ * before the shuffle. Over a packed shuffle that read reports none, and AQE keeps the full shuffle
+ * read where an operator needs the scan's layout.
+ *
+ * The rule runs after `ReplaceHashWithSortAgg` and `RemoveRedundantSorts`, so the check sees which
+ * operators rely on the scan's ordering once those rules have decided.
+ */
+object PackV2ScanPartitions extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val packing = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum,
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+ plan.transformUp {
+ case shuffle: ShuffleExchangeExec if readsOneScan(shuffle.child) =>
+ shuffle.withNewChildren(Seq(packAtLowestSafePoint(shuffle.child, packing)))
+ }
+ }
+
+ // The node itself is not listed, so a child that is already packed is not packed again.
+ private def readsOneScan(plan: SparkPlan): Boolean = plan match {
+ case scan: BatchScanExec => !scan.scan.isInstanceOf[FileScan]
+ case _: ProjectExec | _: FilterExec | _: SortExec => readsOneScan(plan.children.head)
+ case agg: BaseAggregateExec if agg.requiredChildDistributionExpressions.isEmpty =>
+ readsOneScan(agg.child)
+ case join: BroadcastHashJoinExec => readsOneScan(streamedSide(join))
+ case _ => false
+ }
+
+ private def streamedSide(join: BroadcastHashJoinExec): SparkPlan = join.buildSide match {
+ case BuildLeft => join.right
+ case BuildRight => join.left
+ }
+
+ /**
+ * Tries the node above each operator below `top`, the shuffle's child, on its path from the scan
+ * up, and keeps the first plan that passes `ValidateRequirements`. Otherwise the node goes
+ * directly above `top`.
+ */
+ private def packAtLowestSafePoint(top: SparkPlan, packing: V2ScanPartitionPacking): SparkPlan = {
+ pathToScan(top).tail.reverseIterator
+ .map(packAbove(top, _, packing))
Review Comment:
**Finding 22.** The tuning guide says that above the node "built-in expressions there that take the partition index, such as `spark_partition_id()`, see the packed task's index". With the node directly above the scan, that also holds for `monotonically_increasing_id()` and a seeded `rand()` in a project or filter. A plan of the same scan that no shuffle reads, such as a broadcast build side or a `collect()`, still gives them the input's index. So two plans of one DataFrame now compute different values, while without packing they agree.
I ran two shapes on this head, with AQE off and on:
- A self-join on `monotonically_increasing_id()`, over the read suite's six one-row inputs:
```scala
val x = spark.table("testcat.ns.items").withColumn("rid", monotonically_increasing_id())
x.select("rid", "name").join(broadcast(x.select("rid", "price")), "rid").groupBy("name").count()
// packing off: (aa,2), (bb,2), (cc,2) packing on: (aa,2)
```
The streamed side reads `Project [name, monotonically_increasing_id() AS rid] <- PackScanPartitions <- BatchScan`, and the build side reads `Project [monotonically_increasing_id() AS rid] <- BatchScan`.
- A seeded filter over 48 one-row inputs, with `maxPartitionBytes=2400`: `spark.table(...).where(rand(42) < 0.5)` counts 15 rows with packing on, and its `collect()` returns 19. With packing off, both give 19.
Keeping every operator with a non-deterministic expression below the node fixes both. The operators above it still run once per packed task:
```suggestion
val path = pathToScan(top)
// An operator with a non-deterministic expression, such as monotonically_increasing_id() or
// a seeded rand(), stays below the node. It then sees each input's partition index, as in a
// plan of the same scan that no shuffle reads.
val highest = path.indexWhere(_.expressions.exists(!_.deterministic))
val candidates = if (highest < 0) path.tail else path.slice(1, highest + 1)
candidates.reverseIterator
.map(packAbove(top, _, packing))
```
With it, both shapes give the packing-off answers, with AQE off and on, and the shuffle's input is still packed. In the packing suites, only "partition-dependent expressions above the node see the packed task" fails, since it expects `spark_partition_id()` above the node. That test, the class doc (`:35-41`) and the tuning guide would then say that built-in expressions see the input's partition wherever they run. Only code that reads `TaskContext.partitionId()` would see the packed task's.
This gives up one point of [the placement thread](https://github.com/apache/spark/pull/59522#issuecomment-7092854374): `spark_partition_id()` and `TaskContext.partitionId()` no longer agree directly above the scan. I think agreeing with the other plans of the same DataFrame matters more, because that is where results change.
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,114 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
+
+When every input of a scan reports a non-negative `HasPartitionStatistics.sizeInBytes()`, Spark
+packs consecutive inputs into tasks as it packs files: a file joins the current task unless its size
+would take the task past the target, and an input joins only if all of the files it reports would.
+Each input adds its size plus an opening cost for each file it reports through
+`HasPartitionStatistics.filesCount()`, and at least one. Unlike files, which Spark sorts by size
+before packing, the inputs keep the order the scan reads them in. The suggested minimum count helps
+retain parallelism for small scans. Packing never divides a connector input, however large.
+Reported sizes are estimates, so this is not a bound on runtime memory or CPU. As with
+`spark.sql.files.maxPartitionNum`, when packing by size gives more tasks than
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum`, Spark packs the inputs again with a
+target of the scan's total size divided by that cap, ignoring
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes`. Unlike for files, that target is
+never smaller than the first one, which could only give more tasks. If any input of a scan reports
+no valid size, Spark leaves the scan's inputs as they are, unless
Review Comment:
**Finding 26.** "Spark leaves the scan's inputs as they are" holds for the inputs, but the plan still changes. The rule plans the node for every eligible scan, before any input reports a size (`PackV2ScanPartitions.scala:62-63`). The node reports `UnknownPartitioning(0)` whatever it packs (`PackScanPartitionsExec.scala:49`). So such a scan still shows a `PackScanPartitions` node in EXPLAIN. A local shuffle read over its shuffle also reports no keyed layout, which [you accepted](https://github.com/apache/spark/pull/59522#issuecomment-7115850460) for packed shuffles. The description says this for the pipelined shuffle ("This holds even if the node then packs nothing"). One sentence here would cover the rest, for example: "Spark plans the node for every eligible scan, before any input reports a size, so EXPLAIN shows it, and a local shuffle read over its shuffle reports no keyed layout, even when no input gets packed."
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,114 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
+
+When every input of a scan reports a non-negative `HasPartitionStatistics.sizeInBytes()`, Spark
+packs consecutive inputs into tasks as it packs files: a file joins the current task unless its size
+would take the task past the target, and an input joins only if all of the files it reports would.
+Each input adds its size plus an opening cost for each file it reports through
+`HasPartitionStatistics.filesCount()`, and at least one. Unlike files, which Spark sorts by size
+before packing, the inputs keep the order the scan reads them in. The suggested minimum count helps
+retain parallelism for small scans. Packing never divides a connector input, however large.
+Reported sizes are estimates, so this is not a bound on runtime memory or CPU. As with
+`spark.sql.files.maxPartitionNum`, when packing by size gives more tasks than
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum`, Spark packs the inputs again with a
+target of the scan's total size divided by that cap, ignoring
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes`. Unlike for files, that target is
+never smaller than the first one, which could only give more tasks. If any input of a scan reports
+no valid size, Spark leaves the scan's inputs as they are, unless
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum` is set. Then it groups all of the scan's
+inputs by count into at most that many tasks, which balances input counts, not bytes. This applies
+to any eligible V2 scan with such an input, such as a scan of a Python data source or of a connector
+whose inputs do not implement `HasPartitionStatistics`, but not to file-based V2 sources.
+
+Spark decides the tasks when the shuffle's map stage runs, from the inputs that runtime filtering,
+such as dynamic partition pruning, leaves. An input that runtime filtering emptied joins the task of
+the input before it, or the first task when no input precedes it, even when Spark leaves the other
+inputs as they are. EXPLAIN shows a `PackScanPartitions` node between the scan and the shuffle, and
+its SQL metrics show the number of input partitions, the number of partitions it packed them into,
+and the largest number of input partitions in one partition. The operators above the node run once
+per packed task, so a partial aggregation there emits its rows per task, and built-in expressions
+there that take the partition index, such as `spark_partition_id()`, see the packed task's index.
+The operators below the node, if any, run as they do without packing, once per input, and
+`spark_partition_id()` there sees the input's index. Code that reads `TaskContext.partitionId()`,
+such as a UDF, sees the packed task's index wherever it runs, and so does the shuffle, so a
+round-robin repartition can place rows differently. A task that packs several inputs prefers the
+host that more of them prefer than any other host or, when no host is ahead, the hosts of the first
+of them that reports any, so inputs that prefer other hosts can be read remotely. Packing can reduce
+useful parallelism, and fewer map tasks limit how finely AQE can split a skewed shuffle partition,
+for skew joins and rebalances alike. Under AQE, a local shuffle read with one mapper per task over a
+packed shuffle no longer reports the scan's keyed layout, so where an operator needs that layout,
+AQE keeps the full shuffle read. The default is off; connectors that already size their inputs need
+not enable it.
+
+<table class="spark-config">
+ <thead><tr><th>Property Name</th><th>Default</th><th>Meaning</th><th>Since Version</th></tr></thead>
+ <tr>
+ <td><code>spark.sql.sources.v2.scanPartitionPacking.enabled</code></td>
+ <td>false</td>
+ <td>
+ When true, pack the inputs of batch V2 scans that a shuffle reads into fewer tasks, by their
+ reported sizes.
+ </td>
+ <td>4.5.0</td>
+ </tr>
+ <tr>
+ <td><code>spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes</code></td>
+ <td>128MB</td>
+ <td>
+ The maximum number of bytes to pack into a single task, as
+ <code>spark.sql.files.maxPartitionBytes</code> does for files. Spark never splits an input.
+ </td>
+ <td>4.5.0</td>
+ </tr>
+ <tr>
+ <td><code>spark.sql.sources.v2.scanPartitionPacking.openCostInBytes</code></td>
Review Comment:
**Finding 24.** `spark.sql.sources.v2.scanPartitionPacking.openCostInBytes` is `.internal()` (`SQLConf.scala:3665`), so this row would be the only place a user learns of it, as with the pipelined shuffle in finding 21. Its file counterpart, `spark.sql.files.openCostInBytes`, is public and listed in this guide (`:78`). Either drop `.internal()`, or drop this row and describe the opening cost in the text above without the key.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsSuite.scala:
##########
@@ -0,0 +1,606 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+
+import scala.util.Random
+
+import org.apache.spark.SparkConf
+import org.apache.spark.paths.SparkPath
+import org.apache.spark.sql.{DataFrame, DynamicPartitionPruningV2CatalystFilterSuiteAEOff, DynamicPartitionPruningV2CatalystFilterSuiteAEOn, DynamicPartitionPruningV2FilterSuiteAEOff, DynamicPartitionPruningV2FilterSuiteAEOn, DynamicPartitionPruningV2SuiteAEOff, DynamicPartitionPruningV2SuiteAEOn, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.plans.physical.{KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.connector.catalog.Column
+import org.apache.spark.sql.connector.expressions.Expressions.identity
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.connector.read.HasPartitionStatistics
+import org.apache.spark.sql.execution.{SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, QueryStageExec}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.datasources.{FilePartition, PartitionedFile}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, PackScanPartitionsExec, PackV2ScanPartitions, V2ScanPartitionPacking}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, EnsureRequirements, ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.functions.{broadcast, max}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StringType}
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+ private val minPartitionNum = SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM.key
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 2400L)
+
+ after { catalog.clearTables() }
+
+ // In-memory splits report 100 bytes each.
+ private def createSplits(keys: Int = 2, splits: Int = 24, keyed: Boolean = true): Unit = {
+ createTable(items, itemsColumns, if (keyed) Array(identity("id")) else Array.empty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES " + (1 to keys).flatMap { id =>
+ (1 to splits).map(i => s"($id, 'split$i', 1.0, NULL)")
+ }.mkString(", "))
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The tables whose scans a packing node packs: those below it but not below a broadcast.
+ private def packedTables(plan: SparkPlan): Seq[String] = {
+ def scans(p: SparkPlan): Seq[String] = p match {
+ case _: BroadcastExchangeLike => Nil
+ case s: BatchScanExec => Seq(s.table.name().split('.').last)
+ case other => other.children.flatMap(scans)
+ }
+ packNodes(plan).flatMap(node => scans(node.child))
+ }
+
+ test("SPARK-60265: scan packing is disabled by default") {
+ createSplits(splits = 3)
+ assert(!spark.sessionState.conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED))
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ assert(packNodes(df.queryExecution.executedPlan).isEmpty)
+ }
+
+ test("SPARK-60265: sized inputs pack as spark.sql.files.* packs files of the same sizes") {
+ case class Sized(bytes: Long) extends HasPartitionStatistics {
+ override def sizeInBytes(): OptionalLong = OptionalLong.of(bytes)
+ override def numRows(): OptionalLong = OptionalLong.empty()
+ override def filesCount(): OptionalLong = OptionalLong.empty()
+ }
+ // Above maxPartitionNum, the inputs keep the first target as a floor, which files do not.
+ // These cases don't reach that difference.
Review Comment:
**Finding 25.** The test holds for seed 60265 only. With `new Random(1)` or `new Random(60268)`, one generated case packs differently from `FilePartition` in each. In both, the cap's target (about 123 and 121 MB) is below the first target of 128 MB, so the floor applies. Skipping those cases keeps the comparison meaningful for any seed, and the comment can say why:
```scala
// Files keep no floor above the cap, so compare only where the cap's target is at least
// the first target.
val total = sizes.map(_ + openCost).sum
val first = math.min(maxBytes, math.max(openCost, total / minNum))
if (!maxNum.exists(cap => (total + cap - 1) / cap < first)) withSQLConf(conf: _*) {
// ... the comparison as today
}
```
With it, the test passes for seeds 1, 60268 and 60265.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys.{CONFIG, DESIRED_NUM_PARTITIONS, MAX_NUM_PARTITIONS, NUM_PARTITIONS}
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Immutable sizing policy that `PackV2ScanPartitions` reads from the session configuration when it
+ * plans packed shuffles, before runtime filtering. It holds the configured values only. A default
+ * that depends on the cluster, such as the minimum partition count, is resolved when
+ * `PackScanPartitionsExec` executes, so equal nodes planned at different times stay equal for
+ * exchange and stage reuse.
+ */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Option[Int],
+ maxPartitionNum: Option[Int]) extends Logging {
+
+ // As the session configuration checks them, for a policy built directly.
+ require(maxPartitionBytes > 0, "The maximum partition size must be positive.")
+ require(openCostInBytes >= 0, "The opening cost must be non-negative.")
+ require(minPartitionNum.forall(_ > 0), "The minimum partition count must be positive.")
+ require(maxPartitionNum.forall(_ > 0), "The maximum partition count must be positive.")
+
+ /**
+ * Group adjacent inputs by estimated size as `FilePartition` groups files, but in the scan's
+ * order and never splitting an input. Each input costs its size plus the opening cost for each
+ * file it reports through `filesCount`, and at least one, and it joins a group only if all of its
+ * files would fit there. As with `spark.sql.files.maxPartitionNum`, when that gives more groups
+ * than `maxPartitionNum`, the groups are sized by the cap instead, but unlike for files never
+ * with a smaller target than the first. If any input lacks a valid size, the whole scan is
+ * grouped by count into at most `maxPartitionNum` balanced ranges when that cap is set. Returns
+ * None when every input stays a partition of its own, without building a group for each.
+ */
+ def pack(partitions: Seq[InputPartition], defaultMinPartitionNum: => Int): Option[Seq[Range]] =
+ pack(partitions.length, partitions.iterator, defaultMinPartitionNum)
+
+ private def pack(
+ numInputs: Int,
+ inputs: Iterator[InputPartition],
+ defaultMinPartitionNum: => Int): Option[Seq[Range]] = {
+ // Unboxed, allocated at the first valid size and read only while every input reports one.
+ var sizes: Array[Long] = null
+ var openCosts: Array[Long] = null
+ var total = 0L
+ var sized = true
+ var index = 0
+ while (sized && inputs.hasNext) {
+ inputs.next() match {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ sized = bytes.isPresent && bytes.getAsLong >= 0
+ if (sized) {
+ if (sizes == null) {
+ sizes = new Array[Long](numInputs)
+ openCosts = new Array[Long](numInputs)
+ }
+ sizes(index) = bytes.getAsLong
+ openCosts(index) = openCost(p)
+ total = add(total, add(sizes(index), openCosts(index)))
+ }
+ case _ => sized = false
+ }
+ index += 1
+ }
+ if (!sized) {
+ // A cap of at least the number of inputs leaves each of them on its own.
+ maxPartitionNum.filter(_ < numInputs).map(byCount(numInputs, _))
+ } else if (numInputs == 0) {
+ None
+ } else {
+ val minGroups = minPartitionNum.getOrElse(defaultMinPartitionNum)
+ // As FilePartition.maxSplitBytes.
+ val target = math.min(maxPartitionBytes, math.max(openCostInBytes, total / minGroups))
+ val groups = bySize(sizes, openCosts, target)
+ // As spark.sql.files.maxPartitionNum: above the cap, size the groups by the cap instead. Next
+ // fit leaves room at the end of each group, so the cap's target can be smaller than the first
+ // one, which could only give more groups, and the first target stays the floor.
+ val numGroups = groups.fold(numInputs)(_.size)
+ maxPartitionNum.filter(numGroups > _) match {
Review Comment:
**Finding 23.** When `ceilDiv(total, cap)` is not above `target`, the second `bySize` gets the same target and returns the same groups. The warning still says that Spark rescaled them by ignoring `maxPartitionBytes`. The unit case for a cap of 17 (`V2ScanPartitionPackingSuite.scala:126`) logs "The number of partitions is 20, which exceeds the maximum number configured: 17. Spark rescales it to 20 by ignoring the configuration of spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes." Packing again only when the cap's target is above the first removes both the message and the second pass:
```suggestion
maxPartitionNum.filter(cap => numGroups > cap && ceilDiv(total, cap) > target) match {
```
With it, that case logs nothing and keeps its 20 groups, and `V2ScanPartitionPackingSuite` and the parity test still pass. The `math.max` at `:103` can then go.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6586802889
Thanks @peter-toth. All points are addressed in 3231cced and 67187986, with follow-ups in 06a5b46e, 56e153c4 and a020f22f:
1. **Cached and checkpointed plans.** Packing is now in `CacheManager`'s list of configs turned off for cached plans, unless `canChangeCachedPlanOutputPartitioning` is set. For checkpoints, `withRegularShuffle` only re-plans when local pipelined shuffle applies, so turning packing off there would not always take effect. Instead, `QueryExecution.forCheckpoint` plans with packing off, and `Dataset.checkpoint` passes that execution to `LogicalRDD.fromDataset`, so a checkpoint's statistics, partitioning and ordering all come from the execution that produced its RDD. The three SPARK-53322 checkpoint tests are back to master's expectations and pass in the packing re-run suite. New tests cover your cached-scan join, also with `canChangeCachedPlanOutputPartitioning` enabled, and `checkpoint()` and `localCheckpoint()` directly. The tuning-doc paragraph about turning packing off before materializing is replaced, and the `canChangeCachedPlanOutputPartitioning` doc now lists scan packing.
2. **Description.** Rewritten to describe the change against master; the measurements are in the comment above.
3. **Separate rule.** `PackV2ScanPartitions` is now its own rule, right after `StampUnionDecisions` in both `QueryExecution.preparations` and AQE's `queryStagePreparationRules`; AQE passes `requiredDistribution`. `EnsureRequirements` is unchanged from master, so the shadowed `finalPlan` is gone. The repeated-planning test runs the new rule after `EnsureRequirements`.
4. **Test tags.** Added `@ExtendedSQLTest` to the three re-run suites.
5. **Migration note.** Removed here and moved to a separate docs PR for `master` and `branch-4.2`: #59970 (SPARK-60763).
7. **Typed accessors.** Added for the five new configs.
8. **JIRA.** SPARK-60265 now describes the size-based packing.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446996548
##########
docs/sql-performance-tuning.md:
##########
@@ -640,6 +640,21 @@ The following SQL properties enable Storage Partition Join in different join que
</td>
<td>3.3.0</td>
</tr>
+ <tr>
+ <td><code>spark.sql.sources.v2.bucketing.groupScanPartitions.enabled</code></td>
+ <td>false</td>
+ <td>
+ When enabled, coalesce scan splits sharing a reported partition key into one task,
Review Comment:
Done in 06a5b46e: the tuning section now says storage-partitioned joins and other consumers of keyed layouts keep their existing grouping, so this option is not needed for them.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4696823457
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys.{CONFIG, DESIRED_NUM_PARTITIONS, MAX_NUM_PARTITIONS, NUM_PARTITIONS}
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Immutable sizing policy that `PackV2ScanPartitions` reads from the session configuration when it
+ * plans packed shuffles, before runtime filtering. It holds the configured values only. A default
+ * that depends on the cluster, such as the minimum partition count, is resolved when
+ * `PackScanPartitionsExec` executes, so equal nodes planned at different times stay equal for
+ * exchange and stage reuse.
+ */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Option[Int],
+ maxPartitionNum: Option[Int]) extends Logging {
+
+ /**
+ * Group adjacent inputs by estimated size as `FilePartition` groups files, but in the scan's
+ * order and never splitting an input. Each input costs its size plus the opening cost for each
+ * file it reports through `filesCount`, and at least one, and it joins a group only if all of its
+ * files would fit there. As with
+ * `spark.sql.files.maxPartitionNum`, when that gives more groups than `maxPartitionNum`, the
+ * groups are sized by the cap instead. If any input lacks a valid size, the whole scan is grouped
+ * by count into at most `maxPartitionNum` balanced ranges when that cap is set. Returns None when
+ * every input stays a partition of its own, without building a group for each.
+ */
+ def pack(partitions: Seq[InputPartition], defaultMinPartitionNum: => Int): Option[Seq[Range]] =
+ pack(partitions.length, partitions.iterator, defaultMinPartitionNum)
+
+ private def pack(
+ numInputs: Int,
+ inputs: Iterator[InputPartition],
+ defaultMinPartitionNum: => Int): Option[Seq[Range]] = {
+ // Unboxed, allocated at the first valid size and read only while every input reports one.
+ var sizes: Array[Long] = null
+ var openCosts: Array[Long] = null
+ var total = 0L
+ var sized = true
+ var index = 0
+ while (sized && inputs.hasNext) {
+ inputs.next() match {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ sized = bytes.isPresent && bytes.getAsLong >= 0
+ if (sized) {
+ if (sizes == null) {
+ sizes = new Array[Long](numInputs)
+ openCosts = new Array[Long](numInputs)
+ }
+ sizes(index) = bytes.getAsLong
+ openCosts(index) = openCost(p)
+ total = add(total, add(sizes(index), openCosts(index)))
+ }
+ case _ => sized = false
+ }
+ index += 1
+ }
+ if (!sized) {
+ // A cap of at least the number of inputs leaves each of them on its own.
+ maxPartitionNum.filter(_ < numInputs).map(byCount(numInputs, _))
+ } else if (numInputs == 0) {
+ None
+ } else {
+ val minGroups = minPartitionNum.getOrElse(defaultMinPartitionNum)
+ // As FilePartition.maxSplitBytes.
+ val groups = bySize(sizes, openCosts,
+ math.min(maxPartitionBytes, math.max(openCostInBytes, total / minGroups)))
+ // As spark.sql.files.maxPartitionNum: above the cap, size the groups by the cap instead.
+ val numGroups = groups.fold(numInputs)(_.size)
+ maxPartitionNum.filter(numGroups > _) match {
+ case Some(cap) =>
+ val capped = bySize(sizes, openCosts, ceilDiv(total, cap))
Review Comment:
**Finding 19.** When packing by size gives more groups than `maxPartitionNum`, the inputs are packed again with a target of `ceilDiv(total, cap)`. Next fit leaves room at the end of each group, so the first pass can give more groups than `total / target`. A cap between those two counts then makes the second target smaller than the first, and the second pass merges less:
- 30 inputs of 60, 60 and 70 MB, repeated, at the defaults (`128MB`, `4MB` opening cost) with `minPartitionNum=1`: without a cap, the 60 MB inputs pair up and each 70 MB input stays alone, so the scan runs 20 tasks.
- With `maxPartitionNum` set to 17, 18 or 19, the target drops to about 119, 112 or 106 MB. No two inputs fit together, so all 30 run apart, while the warning says Spark "rescales it to 30".
This is the rule I suggested for finding 17, and `FilePartition` behaves the same: `getFilePartitions` over the same sizes, sorted as file scans sort them, also gives 30 for those caps. Since the cap is there to widen groups, the second pass can keep the first target as a floor:
```scala
val target = math.min(maxPartitionBytes, math.max(openCostInBytes, total / minGroups))
val groups = bySize(sizes, openCosts, target)
...
val capped = bySize(sizes, openCosts, math.max(target, ceilDiv(total, cap)))
```
I ran this on this head. The example then gives 20 tasks for caps 16 to 19, and 15 tasks for a cap of 15. `V2ScanPartitionPackingSuite`, `PackV2ScanPartitionsSuite`, `PackV2ScanPartitionsReadSuite` and `PackV2ScanPartitionsPipelinedSuite` still pass. That includes the `FilePartition` parity test, whose generated sizes don't hit this shape. The parity test's comment and the "As `spark.sql.files.maxPartitionNum`" wording would then need to say where the two differ. The files side can get the same floor in a ticket of its own.
##########
docs/sql-v2-data-sources.md:
##########
@@ -362,6 +362,23 @@ representation of a batch read. It has two methods:
serializable handle representing a data split. It may optionally declare `preferredLocations()`
for data locality.
+Inputs can also implement
+[`HasPartitionStatistics`](api/java/org/apache/spark/sql/connector/read/HasPartitionStatistics.html)
+to report their estimated `sizeInBytes()`: the bytes the input reads from storage, such as the
+length of its files, without any opening cost. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark can pack adjacent inputs by size into
+fewer tasks where a shuffle reads the scan, adding an opening cost for each file an input reports
+through `filesCount()`, and at least one. This applies to keyed and unkeyed batch scans and is
+disabled by default. Inputs are packed in the order the scan reads them, which for a keyed scan with
+V2 bucketing enabled is the order of their partition keys. Return `OptionalLong.empty()` when the
+size is unknown. If any input of a scan reports no size, Spark leaves the scan's inputs unchanged,
Review Comment:
**Finding 20.** For a keyed scan, this doesn't quite hold. Runtime filtering pads each pruned split with an empty partition (`PushDownUtils.scala:449-464`), and `packSlots` folds every empty partition into the group before it, even when the inputs stay apart (`V2ScanPartitionPacking.scala:115-146`). So a pruned keyed scan whose inputs report no size runs fewer tasks than it has partitions. The tuning guide says so ("even when Spark leaves the other inputs as they are"), but this page and the `maxPartitionNum` doc (`SQLConf.scala:3694`, "such a scan's inputs are left as they are") don't. One sentence in both would do, e.g. "Partitions that runtime filtering emptied still join a neighboring task."
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,112 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
+
+When every input of a scan reports a non-negative `HasPartitionStatistics.sizeInBytes()`, Spark
+packs consecutive inputs into tasks as it packs files: a file joins the current task unless its size
+would take the task past the target, and an input joins only if all of the files it reports would.
+Each input adds its size plus an opening cost for each file it reports through
+`HasPartitionStatistics.filesCount()`, and at least one. Unlike files, which Spark sorts by size
+before packing, the inputs keep the order the scan reads them in. The suggested minimum count helps
+retain parallelism for small scans. Packing never divides a connector input, however large.
+Reported sizes are estimates, so this is not a bound on runtime memory or CPU. As with
+`spark.sql.files.maxPartitionNum`, when packing by size gives more tasks than
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum`, Spark packs the inputs again with a
+target of the scan's total size divided by that cap, ignoring
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes`. If any input of a scan reports no
+valid size, Spark leaves the scan's inputs as they are, unless
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum` is set. Then it groups all of the scan's
+inputs by count into at most that many tasks, which balances input counts, not bytes. This applies
+to any eligible V2 scan with such an input, such as a scan of a Python data source or of a connector
+whose inputs do not implement `HasPartitionStatistics`, but not to file-based V2 sources.
+
+Spark decides the tasks when the shuffle's map stage runs, from the inputs that runtime filtering,
+such as dynamic partition pruning, leaves. An input that runtime filtering emptied joins the task of
+the input before it, or the first task when no input precedes it, even when Spark leaves the other
+inputs as they are. EXPLAIN shows a `PackScanPartitions` node between the scan and the shuffle, and
+its SQL metrics show the number of input partitions, the number of partitions it packed them into,
+and the largest number of input partitions in one partition. The operators above the node run once
+per packed task, so a partial aggregation there emits its rows per task, and built-in expressions
+there that take the partition index, such as `spark_partition_id()`, see the packed task's index.
+The operators below the node, if any, run as they do without packing, once per input, and
+`spark_partition_id()` there sees the input's index. Code that reads `TaskContext.partitionId()`,
+such as a UDF, sees the packed task's index wherever it runs, and so does the shuffle, so a
+round-robin repartition can place rows differently. Packing can reduce useful parallelism, and fewer
+map tasks limit how finely AQE can split a skewed shuffle partition, for skew joins and rebalances
+alike. Under AQE, a local shuffle read with one mapper per task over a packed shuffle no longer
+reports the scan's keyed layout, so where an operator needs that layout, AQE keeps the full shuffle
+read. With the experimental local pipelined shuffle (`spark.sql.shuffle.localPipelined.enabled`), a
Review Comment:
**Finding 21.** `spark.sql.shuffle.localPipelined.enabled` is `.internal()` (`SQLConf.scala:1481-1482`), and this sentence would be its only mention in `docs/`. The interaction is already stated in the code comments and the PR description. In the user guide, I'd drop the sentence or describe the behavior without naming the key.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4720526233
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsReadSuite.scala:
##########
@@ -0,0 +1,978 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.{SparkConf, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{DynamicPruningExpression, Literal}
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.connector.catalog.{Column, Table}
+import org.apache.spark.sql.connector.expressions.{FieldReference, LiteralValue, NamedReference, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.Expressions.{identity, sort}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate}
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionKey, HasPartitionStatistics, InputPartition, PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsReportOrdering, SupportsReportPartitioning, SupportsRuntimeV2Filtering}
+import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning, UnknownPartitioning}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, FormattedMode, InputAdapter, PartialReducerPartitionSpec, ProjectedBroadcastValueSubqueryExec, SimpleMode, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, SortAggregateExec}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, FileScan, PackScanPartitionsExec}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, PipelinedShuffleTestSession, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, expr, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsReadSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 300L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after {
+ catalog.clearTables()
+ }
+
+ private def populate(): Unit = {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ "(1, 'aa', 1.0, NULL), (1, 'bb', 2.0, NULL), (1, 'cc', 3.0, NULL), " +
+ "(2, 'aa', 4.0, NULL), (2, 'bb', 5.0, NULL), (2, 'cc', 6.0, NULL)")
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The number of rows in each partition of the only packing node of `df`. Over a columnar scan,
+ // the node packs batches.
+ private def rowsPerPackedTask(df: DataFrame): Seq[Int] = {
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ if (nodes.head.supportsColumnar) {
+ nodes.head.executeColumnar()
+ .mapPartitions(batches => Iterator.single(batches.map(_.numRows).sum)).collect().toSeq
+ } else {
+ nodes.head.execute().mapPartitions(rows => Iterator.single(rows.size)).collect().toSeq
+ }
+ }
+
+ private def sized(sizes: String): DataFrame =
+ spark.read.format(classOf[SizedPackingRowSource].getName).option("sizes", sizes).load()
+
+ test("SPARK-60265: packed readers preserve storage filters and their checked column") {
+ // The storage filter source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.V2_STORAGE_FILTER_PUSHDOWN_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1000") {
+ withTable("packing_bloom_build") {
+ spark.range(0, 30).selectExpr("id AS bk", "id AS bv")
+ .write.format("parquet").saveAsTable("packing_bloom_build")
+ for (columnar <- Seq(false, true); adaptive <- Seq(false, true);
+ giveUp <- Seq(false, true)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ StorageFilterTestSource.reset()
+ val probe = spark.read.format(classOf[StorageFilterTestSource].getName)
+ .option("numPartitions", "10").option("columnar", columnar.toString)
+ .option("giveUp", giveUp.toString).load()
+ val build = spark.table("packing_bloom_build").where("bv = 5")
+ val df = probe.join(build, probe("k") === build("bk"))
+ .select(probe("k"), probe("v"))
+ assert(df.collect().toSeq === Seq(Row(5L, 50L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).find(_.storageFilters.nonEmpty).get
+ val node = packNodes(plan).find(n => collectScans(n).contains(scan)).get
+ assert(scan.inputPartitions.size === 10)
+ assert(node.supportsColumnar === columnar)
+ val packed = if (columnar) node.executeColumnar() else node.execute()
+ assert(packed.getNumPartitions === 2)
+ assert(scan.appendsCheckedColumn)
+ assert(scan.supportsColumnar === columnar)
+ assert(StorageFilterTestSource.filteredReaders.get() === 10)
+ assert(StorageFilterTestSource.checkedColumnRequests.get() === 10)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: columnar readers keep reused batches correct through a packed shuffle") {
+ withTempView("columnar") {
+ spark.read.format(classOf[PackingColumnarScanSource].getName).load()
+ .createOrReplaceTempView("columnar")
+ val expected = Seq((1, 1, Seq(20, 21, 22, 10, 11)), (1, 2, Seq(5, 6)),
+ (2, 3, Seq(30, 31))).flatMap { case (i, k, values) =>
+ values.map(j => Row(j, 1L, i, k))
+ }
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ // This source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE j > 10" else ""
+ val df = sql("SELECT j, count(*), max(i), max(k) FROM columnar" + where + " GROUP BY j")
+ val answers = if (filter) expected.filter(_.getInt(0) > 10) else expected
+ checkAnswer(df, answers)
+ checkAnswer(df, answers)
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ // Directly above the scan, the node packs its batches, and the rows are converted above
+ // the node.
+ val repartitioned = spark.table("columnar").repartition(3)
+ checkAnswer(repartitioned,
+ expected.map(row => Row(row.getInt(2), row.getInt(0), row.getInt(3))))
+ val node = packNodes(repartitioned.queryExecution.executedPlan).head
+ assert(node.supportsColumnar)
+ assert(node.executeColumnar().getNumPartitions === 2)
+ assert(collect(repartitioned.queryExecution.executedPlan) {
+ case ColumnarToRowExec(InputAdapter(_: PackScanPartitionsExec)) => true
+ case ColumnarToRowExec(_: PackScanPartitionsExec) => true
+ }.size === 1)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: real unkeyed readers honor byte bounds and the missing-size fallback") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "100") {
+ def expected(n: Int): Seq[Row] = (0 until n).flatMap(i => (0 to i).map(j => Row(i, j)))
+ val bounded = sized("30,40,200,20,30,90").repartition(2)
+ checkAnswer(bounded, expected(6))
+ assert(rowsPerPackedTask(bounded) === Seq(3, 3, 9, 6))
+
+ // As with spark.sql.files.maxPartitionNum, above the cap the inputs are packed by the
+ // scan's total size over it.
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2") {
+ val capped = sized(Seq.fill(8)("100").mkString(",")).repartition(2)
+ checkAnswer(capped, expected(8))
+ assert(rowsPerPackedTask(capped) === Seq(10, 26))
+ }
+
+ // A scan with an input that reports no size is grouped by count, and only under the cap.
+ val unsized = "?,20,-1,40,?"
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "3") {
+ val capped = sized(unsized).repartition(2)
+ checkAnswer(capped, expected(5))
+ assert(rowsPerPackedTask(capped) === Seq(1, 5, 9))
+ }
+ val unchanged = sized(unsized).repartition(2)
+ checkAnswer(unchanged, expected(5))
+ assert(rowsPerPackedTask(unchanged) === Seq(1, 2, 3, 4, 5))
+ }
+ }
+
+ test("SPARK-60265: packed tasks prefer the host that most of their inputs report") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ // Three inputs per task. Each task's first input reports the other task's host, which is
+ // the one the scheduler would take through the lineage if the task named no host.
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", Seq.fill(6)("100").mkString(","))
+ .option("hosts", "h2,h1,h1,h1,h2,h2")
+ .load()
+ .repartition(2)
+ checkAnswer(df, (0 until 6).flatMap(i => (0 to i).map(j => Row(i, j))))
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ val packed = nodes.head.execute()
+ assert(packed.partitions.indices.map(sparkContext.getPreferredLocs(packed, _).map(_.host))
+ === Seq(Seq("h1"), Seq("h2")))
+ }
+ }
+
+ test("SPARK-60265: packed columnar readers close on early stop and task failure") {
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = spark.read.format(classOf[PackingColumnarScanSource].getName).load().repartition(3)
+ val packed = packNodes(df.queryExecution.executedPlan).head.executeColumnar()
+ PackingColumnarReaderFactory.opened.set(0)
+ PackingColumnarReaderFactory.closed.set(0)
+ assert(packed.mapPartitions(_.take(1)).count() === 2)
+ assert(PackingColumnarReaderFactory.opened.get() === 2)
+ assert(PackingColumnarReaderFactory.closed.get() === 2)
+ intercept[SparkException] {
+ packed.mapPartitions { batches =>
+ if (batches.hasNext) throw new IllegalStateException("intentional reader failure")
+ batches
+ }.count()
+ }
+ assert(PackingColumnarReaderFactory.opened.get() > 2)
+ eventually(timeout(10.seconds), interval(10.milliseconds)) {
+ assert(PackingColumnarReaderFactory.closed.get() ===
+ PackingColumnarReaderFactory.opened.get())
+ }
+ }
+ }
+
+ test("SPARK-60265: a range shuffle over packed inputs keeps the complete global ordering") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT id, name FROM testcat.ns.$items ORDER BY name, id")
+ assert(df.collect().toSeq === Seq(Row(1, "aa"), Row(2, "aa"), Row(1, "bb"),
+ Row(2, "bb"), Row(1, "cc"), Row(2, "cc")))
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle above a storage-partitioned join leaves the join's inputs alone") {
+ populate()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); partial <- Seq(false, true)) {
+ withSQLConf(enabled -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> partial.toString) {
+ val df = sql(s"SELECT /*+ MERGE(i, p) */ i.name, count(*), max(i.id) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(packNodes(plan).isEmpty)
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ assert(collectGroupPartitions(plan).nonEmpty)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+
+ test("SPARK-60265: shuffles over packed scans remain reusable and execute repeatedly") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true") {
+ val query = s"SELECT name, count(*), max(id) FROM testcat.ns.$items GROUP BY name"
+ val df = sql(s"($query) UNION ALL ($query)")
+ val expected = Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L))
+ checkAnswer(df, expected ++ expected)
+ checkAnswer(df, expected ++ expected)
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case r: ReusedExchangeExec => r }.nonEmpty)
+ val nodes = packNodes(plan)
+ assert(nodes.nonEmpty && nodes.forall(_.execute().getNumPartitions == 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: V2 file scans keep the partitions spark.sql.files.* plans") {
+ withTempPath { dir =>
+ spark.range(0, 80, 1, 8).selectExpr("id", "id % 4 AS k").write.parquet(dir.getCanonicalPath)
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.USE_V1_SOURCE_LIST.key -> "",
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> "8",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.read.parquet(dir.getCanonicalPath).groupBy("k").count()
+ checkAnswer(df, (0L until 4L).map(k => Row(k, 20L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.scan.isInstanceOf[FileScan])
+ assert(packNodes(plan).isEmpty)
+ assert(scan.inputRDD.getNumPartitions === 8)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a sort aggregate that uses the scan's ordering") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ // Hash and object-hash aggregates, which ReplaceHashWithSortAgg both replaces, and max of a
+ // string, which plans a sort aggregate directly.
+ val aggregates = Seq(
+ "count(*)" -> Seq(Row("n0", 3L), Row("n1", 3L)),
+ "size(collect_list(id))" -> Seq(Row("n0", 3), Row("n1", 3)),
+ "max(cast(id AS STRING))" -> Seq(Row("n0", "6"), Row("n1", "5")))
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ (aggregate, expected) <- aggregates) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT name, $aggregate FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, expected)
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(collect(exchange.child) { case a: BaseAggregateExec => a.getClass } ===
+ Seq(classOf[SortAggregateExec]))
+ // No sort is added: the partial sort aggregate reads the scan's ordering directly, and
+ // the node goes between it and the shuffle. It still packs there: two tasks, each with
+ // the aggregate's rows for three one-row inputs.
+ assert(collect(exchange.child) { case s: SortExec => s }.isEmpty)
+ if (packing) {
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(exchange.child.children.head.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ }
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ // Six one-row inputs of 100 bytes, sorted by name, which pack into two tasks of three.
+ private def populateOrderedByName(): Unit = {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ }
+
+ test("SPARK-60265: partition-dependent expressions below the node keep the input's partition") {
+ populateOrderedByName()
+ // The partial sort aggregate reads the scan's ordering through the project, so the node goes
+ // above the aggregate, and the project runs once per input below it. The built-in expression
+ // sees the input's partition there, and the UDF that reads the task's sees the packed task.
+ val taskPartition = udf(() => TaskContext.getPartitionId()).asNondeterministic()
+ withSQLConf(enabled -> "true") {
+ val df = spark.table(s"testcat.ns.$items")
+ .select($"name", expr("spark_partition_id()").as("pid"), taskPartition().as("tid"))
+ .groupBy("name").agg(expr("collect_set(pid)"), expr("collect_set(tid)"))
+ val rows = df.collect()
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(rows.flatMap(_.getSeq[Int](1)).toSet === (0 until 6).toSet)
+ assert(rows.flatMap(_.getSeq[Int](2)).toSet === Set(0, 1))
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a broadcast hash join whose streamed side's order " +
+ "an operator above it reads") {
+ populateOrderedByName()
+ createTable(purchases, purchasesColumns, Array.empty)
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+ (1 to 6).map(i => s"($i, 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The join keeps the streamed scan's ordering, which the partial sort aggregate above it
+ // reads, so the node goes above the aggregate, with the join below it.
+ val df = sql(s"SELECT /*+ BROADCAST(p) */ i.name, size(collect_list(i.id)) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("n0", 3), Row("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ val packed = exchange.child.children.head
+ assert(packed.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(packed.exists(_.isInstanceOf[BroadcastHashJoinExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a global sort that a keyed scan's layout satisfies") {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ (1 to 6).map(i => s"($i, 'n${i % 2}', 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.V2_BUCKETING_ENABLED.key -> "true",
+ SQLConf.V2_BUCKETING_SORTING_ENABLED.key -> "true",
+ SQLConf.REMOVE_REDUNDANT_SORTS_ENABLED.key -> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The keyed scan's layout satisfies the sort's ordered distribution, so no range shuffle
+ // sits below the sort, and the node goes above it. The scan's ordering satisfies the sort
+ // too, so it stays only with RemoveRedundantSorts off.
+ val df = spark.table(s"testcat.ns.$items").orderBy("id").groupBy("name")
+ .agg(expr("size(collect_list(id))"))
+ // checkAnswer would compare the rows in order, because of the sort.
+ assert(df.collect().map(row => (row.getString(0), row.getInt(1))).sorted.toSeq ===
+ Seq(("n0", 3), ("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ val nodes = packNodes(plan)
+ assert(nodes.size === 1)
+ assert(nodes.head.child.exists {
Review Comment:
I checked this. With the search trying only the scan position and the fallback (`pathToScan(top).tail.reverseIterator.take(1)`), all 310 tests of `PackV2ScanPartitionsSuite`, `PackV2ScanPartitionsReadSuite`, `PackV2ScanPartitionsPipelinedSuite` and `KeyGroupedPartitioningPackScanPartitionsSuite` pass. So no test pins a position between the scan and the shuffle's child yet.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
Posted by "rekbun (via GitHub)" <gi...@apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4340490733
##########
docs/sql-performance-tuning.md:
##########
@@ -640,6 +640,21 @@ The following SQL properties enable Storage Partition Join in different join que
</td>
<td>3.3.0</td>
</tr>
+ <tr>
+ <td><code>spark.sql.sources.v2.bucketing.groupScanPartitions.enabled</code></td>
+ <td>false</td>
+ <td>
+ When enabled, coalesce scan splits sharing a reported partition key into one task,
Review Comment:
Will do.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4426649041
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnsureRequirements.scala:
##########
@@ -1461,5 +1461,6 @@ case class EnsureRequirements(
} else {
newPlan
}
+ PackV2ScanPartitions(finalPlan, requiredDistribution)
Review Comment:
**Finding 3.** Called from the end of `EnsureRequirements.apply`, packing runs on every `EnsureRequirements` call. That includes the re-runs inside `ConvertSortMergeJoinToShuffledHashJoin` (`ConvertSortMergeJoinToShuffledHashJoin.scala:155`) and `OptimizeSkewedJoin` (`OptimizeSkewedJoin.scala:270`), and tests or extensions that call `EnsureRequirements()(plan)`. The plan-change log also attributes the rewrite to `EnsureRequirements`.
Packing is a separate concern from satisfying requirements. `DisableUnnecessaryBucketedScan` is the precedent: a standalone rule after `EnsureRequirements` that withdraws a scan's layout claim. A packing rule can sit right after `StampUnionDecisions` in both `QueryExecution.preparations` and AQE's `queryStagePreparationRules`, so every rule after it sees the same plan as today. In AQE it can take `requiredDistribution` as `EnsureRequirements` does (`AdaptiveSparkPlanExec.scala:141`).
I tried that on this head. 357 of the 358 tests in the packing suites, the three re-run suites and `EnsureRequirementsSuite` pass. The one failure is "repeated requirement planning keeps packing stable", which calls `EnsureRequirements()` directly and expects a packed scan. It would call the new rule after it instead.
If you keep the current shape, please rename the inner `val finalPlan` at line 1453. It shadows the new outer one, and the two have different types (`Seq[SparkPlan]` and `SparkPlan`).
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.rdd.{PartitionCoalescer, PartitionGroup, RDD}
+import org.apache.spark.sql.catalyst.plans.physical.KeyedPartitioning
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionStatistics, InputPartition, PartitionReaderFactory, Scan}
+
+/** Immutable sizing policy captured when a scan is prepared, before runtime filtering. */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Int,
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. Missing,
+ * negative or mixed statistics use the explicit count cap, or leave inputs unchanged.
+ * The cap is only a fallback: it never overrides the size limit for inputs reporting bytes.
+ * Empty runtime-pruned slots are retained and contribute no bytes or opening cost.
Review Comment:
**Finding 6.** Since 4372e37d08b both callers pass only `Some` inputs: `BatchScanExec.scala:192` passes the inputs left after `:183` filters out the pruned slots, and `PackV2ScanPartitions.scala:60` wraps the unfiltered inputs. So the `None` case and this sentence describe a path nothing takes, and the last assertion of "overflow, exact limits and runtime-pruned empty slots" pins it. `pack(partitions: Seq[InputPartition])` would say what it handles.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ */
+object PackV2ScanPartitions extends Rule[SparkPlan] {
+ override def apply(plan: SparkPlan): SparkPlan = apply(plan, None)
+
+ def apply(plan: SparkPlan, requiredDistribution: Option[Distribution]): SparkPlan = {
+ if (!conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED)) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM).getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM))
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
+ options.pack(scan.inputPartitions.map(Some(_))).size < scan.inputPartitions.size =>
+ scan.withPartitionPacking(options)
+ case _: BatchScanExec => node
+ case _: ShuffleExchangeLike | _: BroadcastExchangeLike =>
+ node.withNewChildren(node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ node.requiredChildOrdering(i).nonEmpty)
+ })
+ case sort: SortExec =>
+ // Keep a scan ordering that makes this sort redundant. Otherwise the existing sort
+ // establishes ordering itself, so packing cannot add a new sort or lose its output order.
+ val redundant = SortOrder.orderingSatisfies(sort.child.outputOrdering, sort.sortOrder)
+ sort.withNewChildren(Seq(rewrite(sort.child,
+ needsPartitioning || sort.requiredChildDistribution.head != UnspecifiedDistribution,
+ redundant)))
+ case _: ProjectExec | _: FilterExec | _: BaseAggregateExec |
+ _: BroadcastHashJoinExec | _: BroadcastNestedLoopJoinExec |
+ _: V2TableWriteExec | _: DataWritingCommandExec | _: WriteFilesExec =>
+ val children = node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ needsPartitioning || node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ needsOrdering || node.requiredChildOrdering(i).nonEmpty)
+ }
+ node.withNewChildren(children)
+ case _ =>
+ // Includes GroupPartitionsExec, UnionExec, windows, explicit coalesces and extensions.
+ // An exchange further down can still isolate a scan from these consumers.
+ node.mapChildren(rewrite(_, needsPartitioning = true, needsOrdering = true))
+ }
+ }
+
+ rewrite(plan, requiredDistribution.exists(_ != UnspecifiedDistribution), needsOrdering = false)
Review Comment:
**Finding 1.** The walk starts with `needsPartitioning` only when an AQE `requiredDistribution` is set, so the root scan of a plan being cached or checkpointed is packed. That plan's `outputPartitioning` is what a later query plans against: `InMemoryTableScanExec` and the checkpoint's `LogicalRDD` both report it, and SPARK-53322 relies on it for SPJ.
Measured on this head: a cached `items` table (keyed by `id`, two splits each for keys 1 and 3), joined to `purchases` (keyed by `item_id`), broadcast off, with the packing settings of `PackV2ScanPartitionsPlanSuite`:
| | AQE off | AQE on |
|---|---|---|
| packing off (as on master) | 0 shuffles, 2 `GroupPartitionsExec` | 0 shuffles, 2 `GroupPartitionsExec` |
| packing on | 2 shuffles, no `GroupPartitionsExec` | 2 shuffles, no `GroupPartitionsExec` |
All four runs return the same rows. `CacheManager.getOrCloneSessionWithConfigsOff` already turns off the rules that change a cached plan's output partitioning, unless `spark.sql.optimizer.canChangeCachedPlanOutputPartitioning` is set. Adding packing there:
```scala
disableConfigs =
disableConfigs :+ SQLConf.ADAPTIVE_EXECUTION_APPLY_FINAL_STAGE_SHUFFLE_OPTIMIZATIONS :+
SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED
```
gives 0 shuffles and 2 `GroupPartitionsExec` in all four runs. None of this PR's tests cache a packed scan.
The checkpoint case is already in this PR's own test changes. With packing on, "SPARK-53322: checkpointed scans are used for SPJ" goes from 1 to 3 shuffles with `pushPartValues`, and "SPARK-53322: checkpointed scans can shuffle other children on SPJ" from 2 to 3. `Dataset.checkpoint` plans through `QueryExecution.withRegularShuffle`, which already re-plans with a config turned off through `getOrCloneSessionWithConfigsOff`, so packing could be turned off for checkpoints the same way. I have not measured that one. With both in place, the paragraph in `sql-performance-tuning.md` that asks users to turn packing off before materializing can go.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsSuite.scala:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.catalyst.plans.physical.UnknownPartitioning
+import org.apache.spark.sql.connector.catalog.Identifier
+import org.apache.spark.sql.connector.expressions.Expressions.identity
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+import org.apache.spark.sql.execution.{CoalesceExec, ProjectExec}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.datasources.v2.V2ScanPartitionPacking
+import org.apache.spark.sql.execution.exchange.{EnsureRequirements, PackV2ScanPartitions, ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.internal.SQLConf
+
+class V2ScanPartitionPackingSuite extends org.apache.spark.SparkFunSuite {
+ private case class Sized(bytes: Option[Long]) extends HasPartitionStatistics {
+ override def sizeInBytes(): OptionalLong = bytes.map(OptionalLong.of)
+ .getOrElse(OptionalLong.empty())
+ override def numRows(): OptionalLong = OptionalLong.empty()
+ override def filesCount(): OptionalLong = OptionalLong.empty()
+ }
+ private def inputs(sizes: Long*): Seq[Option[InputPartition]] =
+ sizes.map(size => Some(Sized(Some(size))))
+
+ test("pack actual input sizes, keeping oversized splits separate and covering each input once") {
+ val policy = V2ScanPartitionPacking(100, 0, 1, Some(1))
+ val parts = inputs(30, 40, 200, 20, 30, 90)
+ val groups = policy.pack(parts)
+ assert(groups === Seq(Seq(0, 1), Seq(2), Seq(3, 4), Seq(5)))
+ assert(groups.flatten === parts.indices)
+ assert(policy.pack(Seq.empty).isEmpty)
+ assert(policy.pack(inputs(0, 0, 0)) === Seq(Seq(0, 1, 2)))
+ }
+
+ test("opening cost and suggested parallelism constrain small inputs") {
+ assert(V2ScanPartitionPacking(100, 10, 1, None).pack(inputs(40, 40, 0)) ===
+ Seq(Seq(0, 1), Seq(2)))
+ assert(V2ScanPartitionPacking(1000, 0, 3, None).pack(inputs(100, 100, 100, 100)) ===
+ Seq(Seq(0), Seq(1), Seq(2), Seq(3)))
+ assert(V2ScanPartitionPacking(5, 10, 1, None).pack(inputs(0, 0)) ===
+ Seq(Seq(0), Seq(1)))
+ }
+
+ test("missing, mixed and negative sizes require an explicit count fallback") {
+ val unknown = Some(new InputPartition {})
+ Seq(unknown, Some(Sized(None)), Some(Sized(Some(-1)))).foreach { p =>
+ val parts = inputs(30, 40) :+ p
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(parts).size === 3)
+ assert(V2ScanPartitionPacking(100, 0, 1, Some(2)).pack(parts) ===
+ Seq(Seq(0), Seq(1, 2)))
+ assert(V2ScanPartitionPacking(100, 0, 1, Some(10)).pack(parts).size === 3)
+ }
+ }
+
+ test("overflow, exact limits and runtime-pruned empty slots") {
+ val policy = V2ScanPartitionPacking(Long.MaxValue, 10, 1, None)
+ assert(policy.pack(inputs(Long.MaxValue, 1)) === Seq(Seq(0), Seq(1)))
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(inputs(100, 1)) ===
+ Seq(Seq(0), Seq(1)))
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(
+ Seq(None, Some(Sized(Some(30))), None, Some(Sized(Some(40))))) ===
+ Seq(Seq(0, 1, 2, 3)))
+ }
+}
+
+class PackV2ScanPartitionsSuite extends KeyGroupedPartitioningSuiteBase {
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 2400L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after { catalog.clearTables() }
+
+ private def createSplits(keys: Int = 2, splits: Int = 24, keyed: Boolean = true): Unit = {
+ createTable(items, itemsColumns, if (keyed) Array(identity("id")) else Array.empty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES " + (1 to keys).flatMap { id =>
+ (1 to splits).map(i => s"($id, 'split$i', 1.0, NULL)")
+ }.mkString(", "))
+ }
+
+ test("SPARK-60265: scan packing is disabled by default") {
+ createSplits(splits = 3)
+ assert(!spark.sessionState.conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED))
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ assert(collectScans(df.queryExecution.executedPlan).forall(_.partitionPacking.isEmpty))
+ }
+
+ test("SPARK-60265: size-pack keyed and unkeyed scans before partial aggregation") {
+ for (keyed <- Seq(false, true)) {
+ createSplits(keyed = keyed)
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ bucketing <- Seq(false, true)) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_ENABLED.key -> bucketing.toString) {
+ val df = sql(s"SELECT price, count(*), max(id) FROM testcat.ns.$items GROUP BY price")
+ checkAnswer(df, Seq(Row(1.0, 48L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.inputRDD.getNumPartitions === (if (packing) 2 else 48))
+ assert(scan.partitionPacking.isDefined === packing)
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ val aggregate = collect(exchange.child) { case a: BaseAggregateExec => a }.head
+ // Once per packed task, rather than once per split inside a CoalesceExec.
+ val partialRows = aggregate.execute().count()
+ assert(partialRows === (if (packing) 2L else 48L))
+ assert(collect(plan) { case c: CoalesceExec => c }.isEmpty)
+ assert(ValidateRequirements.validate(stripAQEPlan(plan)))
+ }
+ }
+ catalog.dropTable(Identifier.of(Array("ns"), items))
+ }
+ }
+
+ test("SPARK-60265: packing depends on bytes rather than key count") {
+ createSplits(keys = 1)
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "600") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 24).map(i => Row(s"split$i", 1L)))
+ val scan = collectScans(df.queryExecution.executedPlan).head
+ assert(scan.inputRDD.getNumPartitions === 4)
+ assert(scan.outputPartitioning === UnknownPartitioning(0))
+ assert(scan.outputOrdering.isEmpty)
+ }
+ }
+
+ test("SPARK-60265: row conversion survives direct collection, shuffle, filtering and codegen") {
+ createSplits(splits = 3)
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE id > 0" else ""
+ val direct = sql(s"SELECT id, name FROM testcat.ns.$items$where")
+ checkAnswer(direct, for (id <- 1 to 2; i <- 1 to 3) yield Row(id, s"split$i"))
+ val plan = stripAQEPlan(direct.queryExecution.executedPlan)
+ assert(collectScans(plan).head.partitionPacking.isDefined)
+ assert(collect(plan) { case p: ProjectExec => p }.nonEmpty || codegen)
+ assert(plan.execute().map(_.isInstanceOf[UnsafeRow]).collect().forall(value => value))
+ val shuffled = sql(s"SELECT name, count(*), max(id) FROM testcat.ns.$items$where " +
+ "GROUP BY name")
+ checkAnswer(shuffled, (1 to 3).map(i => Row(s"split$i", 2L, 2L)))
+ assert(ValidateRequirements.validate(stripAQEPlan(shuffled.queryExecution.executedPlan)))
+ }
+ }
+ }
+
+ test("SPARK-60265: repeated requirement planning keeps packing stable") {
+ createSplits(splits = 3)
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ val once = EnsureRequirements()(df.queryExecution.sparkPlan)
+ val twice = EnsureRequirements()(once)
+ assert(PackV2ScanPartitions(twice) === twice)
+ assert(collectScans(twice).head.partitionPacking.isDefined)
+ assert(ValidateRequirements.validate(twice))
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ }
+ }
+
+ test("SPARK-60265: empty scans and explicit coalesces remain unchanged") {
+ createTable(items, itemsColumns, Array(identity("id")))
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val empty = spark.table(s"testcat.ns.$items")
+ checkAnswer(empty, Seq.empty)
+ assert(collectScans(empty.queryExecution.executedPlan).head.partitionPacking.isEmpty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES (1, 'a', 1.0, NULL), (2, 'b', 1.0, NULL)")
+ val input = spark.table(s"testcat.ns.$items")
+ val df = input.coalesce(1).groupBy("name").count()
+ checkAnswer(df, Seq(Row("a", 1L), Row("b", 1L)))
+ assert(collectScans(df.queryExecution.executedPlan).head.partitionPacking.isEmpty)
+ assert(collect(df.queryExecution.executedPlan) { case c: CoalesceExec => c.numPartitions } ===
+ Seq(1))
+ }
+ }
+}
+
+/** Re-run existing SPJ, ordering and reuse regressions with scan packing enabled. */
+class KeyGroupedPartitioningPackScanPartitionsSuite extends KeyGroupedPartitioningSuite {
Review Comment:
**Finding 4.** `KeyGroupedPartitioningSuite` and both runtime-filter suites carry `@ExtendedSQLTest`, but the annotation has no `@Inherited` (`common/tags/src/test/java/org/apache/spark/tags/ExtendedSQLTest.java:28-30`). That is why the parents re-annotate each runtime-filter subclass (`KeyGroupedPartitioningSuite.scala:11108` and `:11122`). So these three subclasses are untagged, and `build_and_test.yml` runs them in "sql - other tests" instead of "sql - extended tests". This one is a full re-run of the largest SPJ suite. Please add the tag to all three (plus the `org.apache.spark.tags.ExtendedSQLTest` import):
```scala
@ExtendedSQLTest
class KeyGroupedPartitioningPackScanPartitionsSuite extends KeyGroupedPartitioningSuite {
```
##########
docs/sql-migration-guide.md:
##########
@@ -106,6 +106,8 @@ license: |
## Upgrading from Spark SQL 4.1 to 4.2
+- Since Spark 4.2, V2 scans no longer unconditionally group input splits sharing a reported partition key into one task (SPARK-55092). Spark still groups splits when needed to satisfy a downstream distribution, such as for a storage-partitioned join. Other scans can execute one task per split, increasing overhead for connectors with many small splits per key. Before 4.2, grouping multiple splits also discarded their reported ordering. Spark 4.4 introduces the default-off `spark.sql.sources.v2.scanPartitionPacking.enabled` option to pack eligible batch V2 scan inputs by estimated size, with an explicit count fallback when sizes are unavailable. This policy is independent of partition keys and does not restore unconditional per-key grouping. See [DataSource V2 Scan Task Sizing](sql-performance-tuning.html#datasource-v2-scan-task-sizing) for its scope and tradeoffs.
Review Comment:
**Finding 5.** This note documents a 4.2 behavior change, so 4.2.x users should find it in `branch-4.2`'s migration guide. In this PR, which is a 4.4 feature, it only reaches `branch-4.x` and `master`, and its "Spark 4.4 introduces ..." sentence keeps it from being backported as written. Could the SPARK-55092 note go into a separate docs PR that can also be merged to `branch-4.2`? This PR then needs only the tuning section, since a new opt-in option needs no migration note. Also, the blank line after this bullet turns the whole section into a loose list.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4530311922
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, ShuffleExchangeLike}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+
+/**
+ * Marks V2 scans for packing after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged. Under AQE, a
+ * local shuffle read with one mapper per task reports the layout below its shuffle, which a
+ * packed scan no longer claims.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ * The rule only marks a scan and does not plan its inputs: `BatchScanExec.inputRDD` decides the
+ * groups at execution, from the inputs that runtime filtering leaves.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ * `keepRootLayout` keeps every claim that reaches the plan's root, for a plan whose output
+ * partitioning and ordering reach a consumer, such as a streaming micro-batch's sink.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None,
+ keepRootLayout: Boolean = false) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum,
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty && !scan.scan.isInstanceOf[FileScan] =>
+ // A V2 file scan is already sized by spark.sql.files.*, as a V1 file scan is.
+ scan.withPartitionPacking(options)
+ case _: BatchScanExec => node
+ case _: ShuffleExchangeLike | _: BroadcastExchangeLike =>
+ node.withNewChildren(node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ node.requiredChildOrdering(i).nonEmpty)
+ })
+ case sort: SortExec =>
+ // Keep a scan ordering that makes this sort redundant. Otherwise the existing sort
+ // establishes ordering itself, so packing cannot add a new sort or lose its output order.
+ val redundant = SortOrder.orderingSatisfies(sort.child.outputOrdering, sort.sortOrder)
+ sort.withNewChildren(Seq(rewrite(sort.child,
+ needsPartitioning || sort.requiredChildDistribution.head != UnspecifiedDistribution,
+ redundant)))
+ case _: ProjectExec | _: FilterExec | _: BaseAggregateExec |
+ _: BroadcastHashJoinExec | _: BroadcastNestedLoopJoinExec |
+ _: V2TableWriteExec | _: DataWritingCommandExec | _: WriteFilesExec =>
+ // ReplaceHashWithSortAgg runs later and uses the ordering of an aggregate's child. A V1
+ // file write reads its child's ordering only with planned writes off or concurrent
+ // output writers on, both internal settings, and then sorts the scan's rows itself.
+ val sortAggregate = node match {
+ case agg: BaseAggregateExec => ReplaceHashWithSortAgg.canReplace(agg)
+ case _ => false
+ }
+ val children = node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ needsPartitioning || node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ needsOrdering || sortAggregate || node.requiredChildOrdering(i).nonEmpty)
+ }
+ node.withNewChildren(children)
+ case _ =>
+ // Includes GroupPartitionsExec, UnionExec, windows, explicit coalesces and extensions.
+ // An exchange further down can still isolate a scan from these consumers.
+ node.mapChildren(rewrite(_, needsPartitioning = true, needsOrdering = true))
+ }
+ }
+
+ rewrite(plan, keepRootLayout || requiredDistribution.exists(_ != UnspecifiedDistribution),
Review Comment:
Done. `ExistingRDD`, `Dataset`, `InsertAdaptiveSparkPlan` and `IncrementalExecution` are back to master, so the checkpoint runs `withRegularShuffle` again and `fromDataset` has no `producedBy`. `forCheckpoint`, `lazyCheckpointPlan`, `executedPlanPrepared`, `keepsRootLayout`, the `keepRootLayout` parameters, `requiredDistribution` and `BatchScanExec.withoutPacking` are gone. `PackV2ScanPartitions` is now an object that `QueryExecution` and `AdaptiveSparkPlanExec` list right after `StampUnionDecisions`, and it calls `rewrite(plan, needsPartitioning = false, needsOrdering = false)`. The `CacheManager` line stays.
With packing on, a checkpoint with packed scans at its root no longer records their layout, so a later join over it shuffles. `PackV2ScanPartitionsPlanSuite` checks that, and the tuning guide and the description state it in one sentence. The packing re-run of `KeyGroupedPartitioningSuite` excludes the three SPARK-53322 checkpoint tests, with a comment pointing to that test.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "ulysses-you (via GitHub) via reviews" <re...@spark.apache.org>.
ulysses-you commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4703248894
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsReadSuite.scala:
##########
@@ -0,0 +1,887 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.{SparkConf, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{DynamicPruningExpression, Literal}
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.connector.catalog.{Column, Table}
+import org.apache.spark.sql.connector.expressions.{FieldReference, LiteralValue, NamedReference, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.Expressions.{identity, sort}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate}
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionKey, HasPartitionStatistics, InputPartition, PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsReportOrdering, SupportsReportPartitioning, SupportsRuntimeV2Filtering}
+import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning, UnknownPartitioning}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, FormattedMode, InputAdapter, PartialReducerPartitionSpec, ProjectedBroadcastValueSubqueryExec, SimpleMode, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, SortAggregateExec}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, FileScan, PackScanPartitionsExec}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, PipelinedShuffleTestSession, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.SortMergeJoinExec
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, expr, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsReadSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 300L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after {
+ catalog.clearTables()
+ }
+
+ private def populate(): Unit = {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ "(1, 'aa', 1.0, NULL), (1, 'bb', 2.0, NULL), (1, 'cc', 3.0, NULL), " +
+ "(2, 'aa', 4.0, NULL), (2, 'bb', 5.0, NULL), (2, 'cc', 6.0, NULL)")
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The number of rows in each partition of the only packing node of `df`. Over a columnar scan,
+ // the node packs batches.
+ private def rowsPerPackedTask(df: DataFrame): Seq[Int] = {
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ if (nodes.head.supportsColumnar) {
+ nodes.head.executeColumnar()
+ .mapPartitions(batches => Iterator.single(batches.map(_.numRows).sum)).collect().toSeq
+ } else {
+ nodes.head.execute().mapPartitions(rows => Iterator.single(rows.size)).collect().toSeq
+ }
+ }
+
+ private def sized(sizes: String): DataFrame =
+ spark.read.format(classOf[SizedPackingRowSource].getName).option("sizes", sizes).load()
+
+ test("SPARK-60265: packed readers preserve storage filters and their checked column") {
+ // The storage filter source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.V2_STORAGE_FILTER_PUSHDOWN_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1000") {
+ withTable("packing_bloom_build") {
+ spark.range(0, 30).selectExpr("id AS bk", "id AS bv")
+ .write.format("parquet").saveAsTable("packing_bloom_build")
+ for (columnar <- Seq(false, true); adaptive <- Seq(false, true);
+ giveUp <- Seq(false, true)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ StorageFilterTestSource.reset()
+ val probe = spark.read.format(classOf[StorageFilterTestSource].getName)
+ .option("numPartitions", "10").option("columnar", columnar.toString)
+ .option("giveUp", giveUp.toString).load()
+ val build = spark.table("packing_bloom_build").where("bv = 5")
+ val df = probe.join(build, probe("k") === build("bk"))
+ .select(probe("k"), probe("v"))
+ assert(df.collect().toSeq === Seq(Row(5L, 50L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).find(_.storageFilters.nonEmpty).get
+ val node = packNodes(plan).find(n => collectScans(n).contains(scan)).get
+ assert(scan.inputPartitions.size === 10)
+ assert(node.supportsColumnar === columnar)
+ val packed = if (columnar) node.executeColumnar() else node.execute()
+ assert(packed.getNumPartitions === 2)
+ assert(scan.appendsCheckedColumn)
+ assert(scan.supportsColumnar === columnar)
+ assert(StorageFilterTestSource.filteredReaders.get() === 10)
+ assert(StorageFilterTestSource.checkedColumnRequests.get() === 10)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: columnar readers keep reused batches correct through a packed shuffle") {
+ withTempView("columnar") {
+ spark.read.format(classOf[PackingColumnarScanSource].getName).load()
+ .createOrReplaceTempView("columnar")
+ val expected = Seq((1, 1, Seq(20, 21, 22, 10, 11)), (1, 2, Seq(5, 6)),
+ (2, 3, Seq(30, 31))).flatMap { case (i, k, values) =>
+ values.map(j => Row(j, 1L, i, k))
+ }
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ // This source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE j > 10" else ""
+ val df = sql("SELECT j, count(*), max(i), max(k) FROM columnar" + where + " GROUP BY j")
+ val answers = if (filter) expected.filter(_.getInt(0) > 10) else expected
+ checkAnswer(df, answers)
+ checkAnswer(df, answers)
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ // Directly above the scan, the node packs its batches, and the rows are converted above
+ // the node.
+ val repartitioned = spark.table("columnar").repartition(3)
+ checkAnswer(repartitioned,
+ expected.map(row => Row(row.getInt(2), row.getInt(0), row.getInt(3))))
+ val node = packNodes(repartitioned.queryExecution.executedPlan).head
+ assert(node.supportsColumnar)
+ assert(node.executeColumnar().getNumPartitions === 2)
+ assert(collect(repartitioned.queryExecution.executedPlan) {
+ case ColumnarToRowExec(InputAdapter(_: PackScanPartitionsExec)) => true
+ case ColumnarToRowExec(_: PackScanPartitionsExec) => true
+ }.size === 1)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: real unkeyed readers honor byte bounds and the missing-size fallback") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "100") {
+ def expected(n: Int): Seq[Row] = (0 until n).flatMap(i => (0 to i).map(j => Row(i, j)))
+ val bounded = sized("30,40,200,20,30,90").repartition(2)
+ checkAnswer(bounded, expected(6))
+ assert(rowsPerPackedTask(bounded) === Seq(3, 3, 9, 6))
+
+ // As with spark.sql.files.maxPartitionNum, above the cap the inputs are packed by the
+ // scan's total size over it.
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2") {
+ val capped = sized(Seq.fill(8)("100").mkString(",")).repartition(2)
+ checkAnswer(capped, expected(8))
+ assert(rowsPerPackedTask(capped) === Seq(10, 26))
+ }
+
+ // A scan with an input that reports no size is grouped by count, and only under the cap.
+ val unsized = "?,20,-1,40,?"
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "3") {
+ val capped = sized(unsized).repartition(2)
+ checkAnswer(capped, expected(5))
+ assert(rowsPerPackedTask(capped) === Seq(1, 5, 9))
+ }
+ val unchanged = sized(unsized).repartition(2)
+ checkAnswer(unchanged, expected(5))
+ assert(rowsPerPackedTask(unchanged) === Seq(1, 2, 3, 4, 5))
+ }
+ }
+
+ test("SPARK-60265: packed tasks prefer the host that most of their inputs report") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ // Three inputs per task. Each task's first input reports the other task's host, which is
+ // the one the scheduler would take through the lineage if the task named no host.
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", Seq.fill(6)("100").mkString(","))
+ .option("hosts", "h2,h1,h1,h1,h2,h2")
+ .load()
+ .repartition(2)
+ checkAnswer(df, (0 until 6).flatMap(i => (0 to i).map(j => Row(i, j))))
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ val packed = nodes.head.execute()
+ assert(packed.partitions.indices.map(sparkContext.getPreferredLocs(packed, _).map(_.host))
+ === Seq(Seq("h1"), Seq("h2")))
+ }
+ }
+
+ test("SPARK-60265: packed columnar readers close on early stop and task failure") {
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = spark.read.format(classOf[PackingColumnarScanSource].getName).load().repartition(3)
+ val packed = packNodes(df.queryExecution.executedPlan).head.executeColumnar()
+ PackingColumnarReaderFactory.opened.set(0)
+ PackingColumnarReaderFactory.closed.set(0)
+ assert(packed.mapPartitions(_.take(1)).count() === 2)
+ assert(PackingColumnarReaderFactory.opened.get() === 2)
+ assert(PackingColumnarReaderFactory.closed.get() === 2)
+ intercept[SparkException] {
+ packed.mapPartitions { batches =>
+ if (batches.hasNext) throw new IllegalStateException("intentional reader failure")
+ batches
+ }.count()
+ }
+ assert(PackingColumnarReaderFactory.opened.get() > 2)
+ eventually(timeout(10.seconds), interval(10.milliseconds)) {
+ assert(PackingColumnarReaderFactory.closed.get() ===
+ PackingColumnarReaderFactory.opened.get())
+ }
+ }
+ }
+
+ test("SPARK-60265: a range shuffle over packed inputs keeps the complete global ordering") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT id, name FROM testcat.ns.$items ORDER BY name, id")
+ assert(df.collect().toSeq === Seq(Row(1, "aa"), Row(2, "aa"), Row(1, "bb"),
+ Row(2, "bb"), Row(1, "cc"), Row(2, "cc")))
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle above a storage-partitioned join leaves the join's inputs alone") {
+ populate()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); partial <- Seq(false, true)) {
+ withSQLConf(enabled -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> partial.toString) {
+ val df = sql(s"SELECT /*+ MERGE(i, p) */ i.name, count(*), max(i.id) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(packNodes(plan).isEmpty)
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ assert(collectGroupPartitions(plan).nonEmpty)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+
+ test("SPARK-60265: shuffles over packed scans remain reusable and execute repeatedly") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true") {
+ val query = s"SELECT name, count(*), max(id) FROM testcat.ns.$items GROUP BY name"
+ val df = sql(s"($query) UNION ALL ($query)")
+ val expected = Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L))
+ checkAnswer(df, expected ++ expected)
+ checkAnswer(df, expected ++ expected)
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case r: ReusedExchangeExec => r }.nonEmpty)
+ val nodes = packNodes(plan)
+ assert(nodes.nonEmpty && nodes.forall(_.execute().getNumPartitions == 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: V2 file scans keep the partitions spark.sql.files.* plans") {
+ withTempPath { dir =>
+ spark.range(0, 80, 1, 8).selectExpr("id", "id % 4 AS k").write.parquet(dir.getCanonicalPath)
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.USE_V1_SOURCE_LIST.key -> "",
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> "8",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.read.parquet(dir.getCanonicalPath).groupBy("k").count()
+ checkAnswer(df, (0L until 4L).map(k => Row(k, 20L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.scan.isInstanceOf[FileScan])
+ assert(packNodes(plan).isEmpty)
+ assert(scan.inputRDD.getNumPartitions === 8)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a sort aggregate that uses the scan's ordering") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ // Hash and object-hash aggregates, which ReplaceHashWithSortAgg both replaces, and max of a
+ // string, which plans a sort aggregate directly.
+ val aggregates = Seq(
+ "count(*)" -> Seq(Row("n0", 3L), Row("n1", 3L)),
+ "size(collect_list(id))" -> Seq(Row("n0", 3), Row("n1", 3)),
+ "max(cast(id AS STRING))" -> Seq(Row("n0", "6"), Row("n1", "5")))
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ (aggregate, expected) <- aggregates) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT name, $aggregate FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, expected)
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(collect(exchange.child) { case a: BaseAggregateExec => a.getClass } ===
+ Seq(classOf[SortAggregateExec]))
+ // No sort is added: the partial sort aggregate reads the scan's ordering directly, and
+ // the node goes between it and the shuffle. It still packs there: two tasks, each with
+ // the aggregate's rows for three one-row inputs.
+ assert(collect(exchange.child) { case s: SortExec => s }.isEmpty)
+ if (packing) {
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(exchange.child.children.head.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ }
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: packing runs after RemoveRedundantSorts drops a sort the scan's ordering " +
+ "makes redundant") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The project keeps the sort from being the shuffle's direct child, so only the scan's
+ // ordering makes it redundant. Packed first, the node would go below the sort, which
+ // would then stay.
+ val df = spark.table(s"testcat.ns.$items").sortWithinPartitions("name")
+ .selectExpr("name", "price * 2 AS p").repartition(3, $"p")
+ // checkAnswer would compare the rows in order, because of the sort.
+ assert(df.collect().map(_.getString(0)).sorted.toSeq ===
+ Seq.fill(3)("n0") ++ Seq.fill(3)("n1"))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(collect(plan) { case s: SortExec => s }.isEmpty)
+ assert(packNodes(plan).map(_.child.isInstanceOf[BatchScanExec]) === Seq(true))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: a keyed scan's inputs are packed in key order only with V2 bucketing") {
+ for (bucketing <- Seq(true, false)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_BUCKETING_ENABLED.key -> bucketing.toString,
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "128",
+ SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES.key -> "4") {
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", "100,20,100,20").option("keys", "1,2,1,2").load()
+ .groupBy("j").count()
+ checkAnswer(df, Seq(Row(0, 4L), Row(1, 3L), Row(2, 2L), Row(3, 1L)))
+ // In key order, the two 100-byte inputs cannot share a task.
+ assert(packNodes(df.queryExecution.executedPlan).head.execute().getNumPartitions ===
+ (if (bucketing) 3 else 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: the packing node reports what it packed and shows in both explain modes") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ // What the SQL tab shows for the node.
+ val metrics = runAndFetchMetrics(df.collect()).collect {
+ case ((_, node, name), value) if node == "PackScanPartitions" => name -> value
+ }
+ assert(metrics.get("number of input partitions").contains("6"), metrics)
+ assert(metrics.get("number of partitions").contains("2"), metrics)
+ assert(metrics.get("max partitions per group").contains("3"), metrics)
+ checkAnswer(df, Seq(Row("aa", 2L), Row("bb", 2L), Row("cc", 2L)))
+ Seq(SimpleMode, FormattedMode).foreach { mode =>
+ assert(df.queryExecution.explainString(mode).contains("PackScanPartitions"), mode)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: partition-dependent expressions above the node see the packed task") {
+ populate()
+ // The node goes directly above the scan, so the built-in expression and code that reads the
+ // task's partition id, such as this UDF, both see the packed task.
+ val taskPartition = udf(() => TaskContext.getPartitionId()).asNondeterministic()
+ for (packing <- Seq(false, true)) {
+ withSQLConf(enabled -> packing.toString) {
+ val ids = spark.table(s"testcat.ns.$items")
+ .select(expr("spark_partition_id()").as("pid"), taskPartition().as("tid"))
Review Comment:
Nit: `docs/sql-performance-tuning.md` notes that `spark_partition_id()` below `PackScanPartitionsExec` sees the input partition index while `TaskContext.partitionId()` sees the packed task index, whereas this test only places `PackScanPartitionsExec` directly above `BatchScanExec`. Consider also covering a case where `PackScanPartitionsExec` sits above `ProjectExec` (for example under a partial `SortAggregateExec` reading scan ordering).
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsSuite.scala:
##########
@@ -0,0 +1,559 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+
+import scala.util.Random
+
+import org.apache.spark.SparkConf
+import org.apache.spark.paths.SparkPath
+import org.apache.spark.sql.{DataFrame, DynamicPartitionPruningV2CatalystFilterSuiteAEOff, DynamicPartitionPruningV2CatalystFilterSuiteAEOn, DynamicPartitionPruningV2FilterSuiteAEOff, DynamicPartitionPruningV2FilterSuiteAEOn, DynamicPartitionPruningV2SuiteAEOff, DynamicPartitionPruningV2SuiteAEOn, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.plans.physical.{KeyedPartitioning, PartitioningCollection}
+import org.apache.spark.sql.connector.catalog.Column
+import org.apache.spark.sql.connector.expressions.Expressions.identity
+import org.apache.spark.sql.connector.expressions.Transform
+import org.apache.spark.sql.connector.read.HasPartitionStatistics
+import org.apache.spark.sql.execution.{SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, QueryStageExec}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.datasources.{FilePartition, PartitionedFile}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, PackScanPartitionsExec, PackV2ScanPartitions, V2ScanPartitionPacking}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, EnsureRequirements, ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.functions.{broadcast, max}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StringType}
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+ private val minPartitionNum = SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM.key
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 2400L)
+
+ after { catalog.clearTables() }
+
+ // In-memory splits report 100 bytes each.
+ private def createSplits(keys: Int = 2, splits: Int = 24, keyed: Boolean = true): Unit = {
+ createTable(items, itemsColumns, if (keyed) Array(identity("id")) else Array.empty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES " + (1 to keys).flatMap { id =>
+ (1 to splits).map(i => s"($id, 'split$i', 1.0, NULL)")
+ }.mkString(", "))
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The tables whose scans a packing node packs: those below it but not below a broadcast.
+ private def packedTables(plan: SparkPlan): Seq[String] = {
+ def scans(p: SparkPlan): Seq[String] = p match {
+ case _: BroadcastExchangeLike => Nil
+ case s: BatchScanExec => Seq(s.table.name().split('.').last)
+ case other => other.children.flatMap(scans)
+ }
+ packNodes(plan).flatMap(node => scans(node.child))
+ }
+
+ test("SPARK-60265: scan packing is disabled by default") {
+ createSplits(splits = 3)
+ assert(!spark.sessionState.conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED))
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ assert(packNodes(df.queryExecution.executedPlan).isEmpty)
+ }
+
+ test("SPARK-60265: sized inputs pack as spark.sql.files.* packs files of the same sizes") {
+ case class Sized(bytes: Long) extends HasPartitionStatistics {
+ override def sizeInBytes(): OptionalLong = OptionalLong.of(bytes)
+ override def numRows(): OptionalLong = OptionalLong.empty()
+ override def filesCount(): OptionalLong = OptionalLong.empty()
+ }
+ // Above maxPartitionNum, the inputs keep the first target as a floor, which files do not.
+ // These cases don't reach that difference.
+ val mb = 1024L * 1024
+ // (sizes, maxPartitionBytes, openCostInBytes, minPartitionNum, maxPartitionNum)
+ val fixed = Seq(
+ (Seq.fill(40)(62 * mb), 128 * mb, 4 * mb, 1, None),
+ (Seq(50 * mb, 44 * mb), 100 * mb, 4 * mb, 1, None),
+ (Seq.fill(1000)(0L), 128 * mb, 4 * mb, 1, None),
+ // The minimum-count target rounds down, as maxSplitBytes does: 39 / 5 = 7 keeps each apart.
+ (Seq(12L, 0L, 4L, 7L), 128L, 4L, 5, None),
+ // Above the cap, whose target rounds up: 11 / 2 = 6.
+ (Seq(1L, 3L, 1L), 5L, 2L, 1, Some(2)),
+ // Above the cap, and still 3 groups after packing again, as for files.
+ (Seq(120 * mb, 10 * mb, 124 * mb), 128 * mb, 4 * mb, 1, Some(2)),
+ (Seq.fill(8)(100L), 100L, 0L, 1, Some(2)))
+ val random = new Random(60265)
+ val generated = Seq.fill(300) {
+ val sizes = Seq.fill(1 + random.nextInt(40))(random.nextLong(200 * mb))
+ (sizes, Seq(64 * mb, 128 * mb)(random.nextInt(2)), Seq(0L, 4 * mb)(random.nextInt(2)),
+ 1 + random.nextInt(8), Option.when(random.nextBoolean())(1 + random.nextInt(sizes.size)))
+ }
+ (fixed ++ generated).foreach { case (sizes, maxBytes, openCost, minNum, maxNum) =>
+ val conf = Seq(SQLConf.FILES_MAX_PARTITION_BYTES.key -> maxBytes.toString,
+ SQLConf.FILES_OPEN_COST_IN_BYTES.key -> openCost.toString,
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> minNum.toString) ++
+ maxNum.map(SQLConf.FILES_MAX_PARTITION_NUM.key -> _.toString)
+ withSQLConf(conf: _*) {
+ // Each file records its position as its start offset, which packing does not read.
+ val files = sizes.zipWithIndex.map { case (size, index) =>
+ PartitionedFile(InternalRow.empty, SparkPath.fromPathString(s"/f$index"), index, size)
+ }
+ val splitBytes = FilePartition.maxSplitBytes(spark, sizes.map(_ + openCost).sum)
+ val expected = FilePartition.getFilePartitions(spark, files, splitBytes)
+ .map(_.files.map(_.start.toInt).toSeq)
+ val packed = V2ScanPartitionPacking(maxBytes, openCost, Some(minNum), maxNum)
+ .pack(sizes.map(Sized), 1).getOrElse(sizes.indices.map(Seq(_)))
+ assert(packed === expected, s"sizes=$sizes maxBytes=$maxBytes openCost=$openCost " +
+ s"minPartitionNum=$minNum maxPartitionNum=$maxNum")
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle reads keyed and unkeyed scans packed directly above the scan") {
+ for (keyed <- Seq(false, true)) {
+ createSplits(keyed = keyed)
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ bucketing <- Seq(false, true)) {
+ withSQLConf(enabled -> packing.toString, minPartitionNum -> "1",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_ENABLED.key -> bucketing.toString) {
+ val df = sql(s"SELECT price, count(*), max(id) FROM testcat.ns.$items GROUP BY price")
+ checkAnswer(df, Seq(Row(1.0, 48L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ // The shuffle's map stage runs one task per packed group.
+ assert(exchange.child.execute().getNumPartitions === (if (packing) 2 else 48))
+ // The scan runs as without the node, which sits directly above it. The partial
+ // aggregate above the node emits its rows once per packed group.
+ val scan = collectScans(plan).head
+ assert(scan.inputRDD.getNumPartitions === 48)
+ assert(scan.outputPartitioning.isInstanceOf[KeyedPartitioning] === (keyed && bucketing))
+ assert(packNodes(plan).forall(_.child eq scan))
+ val aggregate = collect(exchange.child) { case a: BaseAggregateExec => a }.head
+ assert(aggregate.execute().count() === (if (packing) 2L else 48L))
+ assert(meetsRequirements(plan))
+ }
+ }
+ catalog.clearTables()
+ }
+ }
+
+ test("SPARK-60265: the node goes directly above a scan that a shuffle reads through the " +
+ "listed operators") {
+ createSplits(splits = 3)
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", minPartitionNum -> "1",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_ENABLED.key -> "true") {
+ val itemsDf = spark.table(s"testcat.ns.$items")
+ val purchasesDf = spark.table(s"testcat.ns.$purchases")
+ def check(df: DataFrame, expected: Seq[String]): Unit = {
+ df.collect()
+ val plan = df.queryExecution.executedPlan
+ withClue(s"adaptive=$adaptive\n${plan.treeString}") {
+ assert(packedTables(plan).sorted === expected.sorted)
+ // Nothing on these paths relies on the scan's ordering.
+ assert(packNodes(plan).forall(_.child.isInstanceOf[BatchScanExec]))
+ assert(meetsRequirements(plan))
+ }
+ }
+ val itemsName = items
+ val purchasesName = purchases
+ // Projects, filters and partial aggregates below a shuffle.
+ check(itemsDf.where("price > 0").groupBy("name").count(), Seq(itemsName))
+ // A sort that a partial sort aggregate needs, since max of a string has no hash aggregate.
+ // The sort goes above the node.
+ val sorted = itemsDf.groupBy("price").agg(max("name"))
+ check(sorted, Seq(itemsName))
+ val sortedExchange = collect(sorted.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }.head
+ assert(collect(sortedExchange.child) { case s: SortExec => s }
+ .exists(_.exists(_.isInstanceOf[PackScanPartitionsExec])))
+ // A broadcast hash join's streamed side, but not its build side.
+ check(itemsDf.join(broadcast(purchasesDf), $"id" === $"item_id").groupBy("name").count(),
+ Seq(itemsName))
+ // Both sides of a sort-merge join that shuffles them.
+ check(itemsDf.join(purchasesDf, itemsDf("price") === purchasesDf("price")),
+ Seq(itemsName, purchasesName))
+ // A global sort's range shuffle.
+ check(itemsDf.orderBy("name"), Seq(itemsName))
+ // An explicit repartition keeps its output count.
+ val repartitioned = itemsDf.repartition(5)
+ check(repartitioned, Seq(itemsName))
+ assert(repartitioned.rdd.getNumPartitions === 5)
+ // No shuffle reads the scans: at the root, under a storage-partitioned join, and under an
+ // aggregate on the key.
+ check(itemsDf, Nil)
+ check(itemsDf.join(purchasesDf, $"id" === $"item_id"), Nil)
+ check(itemsDf.groupBy("id").count(), Nil)
+ // A union or a coalesce sits between the shuffle and the scans.
+ check(itemsDf.union(itemsDf).groupBy("name").count(), Nil)
+ check(itemsDf.coalesce(2).groupBy("name").count(), Nil)
+ }
+ }
+ }
+
+ test("SPARK-60265: a local sort that a shuffle reads directly is still removed with packing") {
+ createSplits(splits = 3)
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true)) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.table(s"testcat.ns.$items").sortWithinPartitions("name")
+ .repartition(3, $"price")
+ checkAnswer(df, spark.table(s"testcat.ns.$items"))
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case s: SortExec => s }.isEmpty, plan.treeString)
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ }
+ }
+ }
+
+ test("SPARK-60265: planning again does not pack again") {
+ createSplits(splits = 3)
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ val once = PackV2ScanPartitions(EnsureRequirements()(df.queryExecution.sparkPlan))
+ assert(packNodes(once).size === 1)
+ assert(PackV2ScanPartitions(EnsureRequirements()(once)) === once)
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ }
+ }
+
+ test("SPARK-60265: the minimum packed task count defaults to the leaf node parallelism") {
+ createSplits()
+ for (parallelism <- Seq(1, 4)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.LEAF_NODE_DEFAULT_PARALLELISM.key -> parallelism.toString) {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 24).map(i => Row(s"split$i", 2L)))
+ // 4800 bytes: one task holds at most 2400 of them, or 1200 to make four tasks.
+ assert(packNodes(df.queryExecution.executedPlan).head.execute().getNumPartitions ===
+ (if (parallelism == 1) 2 else 4))
+ }
+ }
+ }
+
+ test("SPARK-60265: the opening cost is charged for each file an input reports") {
+ // In-memory splits report 100 bytes in 100 files each. A cost of 1 per file gives 12 splits of
+ // 200 bytes per task, where a cost of 1 per split would give 23 splits of 101 bytes.
+ createSplits()
+ withSQLConf(enabled -> "true", minPartitionNum -> "1",
+ SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES.key -> "1",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 24).map(i => Row(s"split$i", 2L)))
+ assert(packNodes(df.queryExecution.executedPlan).head.execute().getNumPartitions === 4)
+ }
+ }
+
+ test("SPARK-60265: plans packed at different default parallelism stay equal") {
+ createSplits()
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val sparkPlan = EnsureRequirements()(
+ sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name").queryExecution.sparkPlan)
+ val packed = Seq(2, 4).map { parallelism =>
+ withSQLConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM.key -> parallelism.toString) {
+ PackV2ScanPartitions(sparkPlan)
+ }
+ }
+ assert(packed.forall(packNodes(_).size == 1))
+ // Stage and broadcast reuse compare plans, so equality must not depend on the cluster.
+ assert(packed.head.sameResult(packed.last))
+ }
+ }
+
+ test("SPARK-60265: the node leaves an RDD whose partitions are not a scan's as it is") {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val child = spark.range(0, 6, 1, 3).queryExecution.executedPlan
+ val node = PackScanPartitionsExec(child, V2ScanPartitionPacking(300L, 0L, Some(1), Some(1)))
+ val rdd = node.execute()
+ assert(rdd.getNumPartitions === 3)
+ assert(rdd.map(_.getLong(0)).collect().toSeq === (0L until 6L))
+ assert(node.metrics("numPartitions").value === 3)
+ }
+ }
+
+ test("SPARK-60265: a broadcast hash join's streamed side is packed on either build side") {
+ createSplits()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); buildLeft <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", minPartitionNum -> "1",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val itemsDf = spark.table(s"testcat.ns.$items")
+ val purchasesDf = spark.table(s"testcat.ns.$purchases")
+ val joined = if (buildLeft) {
+ broadcast(purchasesDf).join(itemsDf, $"item_id" === $"id")
+ } else {
+ itemsDf.join(broadcast(purchasesDf), $"id" === $"item_id")
+ }
+ val df = joined.groupBy("name").count()
+ checkAnswer(df, (1 to 24).map(i => Row(s"split$i", 2L)))
+ val plan = df.queryExecution.executedPlan
+ withClue(s"adaptive=$adaptive buildLeft=$buildLeft\n${plan.treeString}") {
+ val joins = collect(plan) { case j: BroadcastHashJoinExec => j }
+ assert(joins.map(_.buildSide) === Seq(if (buildLeft) BuildLeft else BuildRight))
+ assert(packedTables(plan) === Seq(items))
+ assert(packNodes(plan).forall(_.child.isInstanceOf[BatchScanExec]))
+ // The 48 splits of 100 bytes run in two map tasks of 2,400 bytes.
+ assert(packNodes(plan).map(_.execute().getNumPartitions) === Seq(2))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: AQE reads the shuffle of a packed keyed scan in full where a join needs it") {
+ // The query of "SPARK-59671: an AQE local read over a split scan does not lose matches",
+ // which the packing re-run of KeyGroupedPartitioningSuite excludes: its setup expects the
+ // scan's keyed layout to reach a local read, and over a packed shuffle it does not. The
+ // matches across the splits of key 1 must still all be found.
+ val idCols = Array(Column.create("id", IntegerType), Column.create("data", StringType))
+ createTable("lrt", idCols, Array(identity("id")))
+ createTable("lrs1", idCols, Array.empty[Transform])
+ createTable("lrs2", idCols, Array.empty[Transform])
+ val pad = "x" * 4096
+ sql(s"INSERT INTO testcat.ns.lrt VALUES (1, 't1a$pad')")
+ sql(s"INSERT INTO testcat.ns.lrt VALUES (1, 't1b$pad')")
+ sql("INSERT INTO testcat.ns.lrt VALUES (2, 't2a')")
+ sql("INSERT INTO testcat.ns.lrs1 VALUES (1, 's1a'), (2, 's1b')")
+ sql("INSERT INTO testcat.ns.lrs2 VALUES (1, 's2a'), (2, 's2b')")
+ withSQLConf(enabled -> "true", minPartitionNum -> "1",
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> "true",
+ SQLConf.V2_BUCKETING_PUSH_PART_VALUES_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "true",
+ SQLConf.ADAPTIVE_AUTO_BROADCASTJOIN_THRESHOLD.key -> "1k",
+ SQLConf.COALESCE_PARTITIONS_ENABLED.key -> "false",
+ SQLConf.SHUFFLE_PARTITIONS.key -> "4") {
Review Comment:
Non-blocking: with `V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES = 2400L`, `lrt`'s three 100-byte splits pack into `numMappers = 1`, so `OptimizeShuffleWithLocalRead` emits four `PartialMapperPartitionSpec(0, ...)` specs and `AQEShuffleReadExec.outputPartitioning` falls back to `UnknownPartitioning(4)` by mapper-index uniqueness alone (`1 != 4`) without consulting `PackScanPartitionsExec.outputPartitioning`. Even with `numMappers = 2` (e.g., `200` / `3`), `lrt` reports an ungrouped `KeyedPartitioning([[1], [1], [2]], isGrouped = false)` that `ValidateRequirements` already rejects on the upper `SortMergeJoinExec`. To make this test discriminate `PackScanPartitionsExec.outputPartitioning`, use `numMappers > 1` with `SHUFFLE_PARTITIONS >= numMappers` and a keyed scan whose unpacked layout would satisfy the join (or clarify the comment/PR description).
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{FilterExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.BroadcastHashJoinExec
+
+/**
+ * Packs the partitions of a V2 batch scan that a shuffle reads, with `PackScanPartitionsExec`,
+ * when the shuffle's child reads one scan through operators that compute each of their partitions
+ * from one scan partition: projects, filters, sorts, partial aggregates and the streamed side of a
+ * broadcast hash join. The list starts from the operators that `DisableUnnecessaryBucketedScan`
+ * allows; others that also map partitions one to one, such as expand and generate, are not packed
+ * yet. Scans of file-based V2 sources are left to `spark.sql.files.*`, as V1 file scans are.
+ *
+ * The node reports no partitioning and no ordering, so it goes at the lowest point on that path
+ * where the plan still meets every operator's requirements, checked with `ValidateRequirements`.
+ * That is directly above the scan unless an operator on the path relies on the scan's ordering,
+ * such as a partial sort aggregate with no sort between it and the scan. The node then goes above
+ * that operator. Directly below the shuffle is the last candidate, and is kept even if the check
+ * fails there, since a shuffle requires nothing of its child. The operators above the node run
+ * once per packed partition, and those below it once per input.
+ *
+ * Above the shuffle, only an AQE local read with one mapper per task reports the layout from
+ * before the shuffle. Over a packed shuffle that read reports none, and AQE keeps the full shuffle
+ * read where an operator needs the scan's layout.
+ *
+ * The rule runs after `ReplaceHashWithSortAgg` and `RemoveRedundantSorts`, so the check sees which
+ * operators rely on the scan's ordering once those rules have decided.
+ */
+object PackV2ScanPartitions extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val packing = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum,
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+ plan.transformUp {
+ case shuffle: ShuffleExchangeExec if readsOneScan(shuffle.child) =>
+ shuffle.withNewChildren(Seq(packAtLowestSafePoint(shuffle.child, packing)))
+ }
+ }
+
+ // The node itself is not listed, so a child that is already packed is not packed again.
+ private def readsOneScan(plan: SparkPlan): Boolean = plan match {
+ case scan: BatchScanExec => !scan.scan.isInstanceOf[FileScan]
+ case _: ProjectExec | _: FilterExec | _: SortExec => readsOneScan(plan.children.head)
Review Comment:
Nit: `SortExec` is matched regardless of `global` (consistent with `DisableUnnecessaryBucketedScan.isAllowedUnaryExecNode`). When `SortExec(global = true)` survives above a key-ordered scan beneath a downstream shuffle, `ValidateRequirements` places `PackScanPartitionsExec` above it; consider adding a test for that fallback path.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys.{CONFIG, DESIRED_NUM_PARTITIONS, MAX_NUM_PARTITIONS, NUM_PARTITIONS}
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Immutable sizing policy that `PackV2ScanPartitions` reads from the session configuration when it
+ * plans packed shuffles, before runtime filtering. It holds the configured values only. A default
+ * that depends on the cluster, such as the minimum partition count, is resolved when
+ * `PackScanPartitionsExec` executes, so equal nodes planned at different times stay equal for
+ * exchange and stage reuse.
+ */
+case class V2ScanPartitionPacking(
Review Comment:
Nit: consider adding `require` guards (`maxPartitionBytes > 0`, `openCostInBytes >= 0`, `minPartitionNum.forall(_ > 0)`, `maxPartitionNum.forall(_ > 0)`) so direct callers in package `v2` do not rely solely on `SQLConf` validators.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import org.apache.spark.sql.catalyst.optimizer.{BuildLeft, BuildRight}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{FilterExec, ProjectExec, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.exchange.{ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.execution.joins.BroadcastHashJoinExec
+
+/**
+ * Packs the partitions of a V2 batch scan that a shuffle reads, with `PackScanPartitionsExec`,
+ * when the shuffle's child reads one scan through operators that compute each of their partitions
+ * from one scan partition: projects, filters, sorts, partial aggregates and the streamed side of a
+ * broadcast hash join. The list starts from the operators that `DisableUnnecessaryBucketedScan`
+ * allows; others that also map partitions one to one, such as expand and generate, are not packed
+ * yet. Scans of file-based V2 sources are left to `spark.sql.files.*`, as V1 file scans are.
+ *
+ * The node reports no partitioning and no ordering, so it goes at the lowest point on that path
+ * where the plan still meets every operator's requirements, checked with `ValidateRequirements`.
+ * That is directly above the scan unless an operator on the path relies on the scan's ordering,
+ * such as a partial sort aggregate with no sort between it and the scan. The node then goes above
+ * that operator. Directly below the shuffle is the last candidate, and is kept even if the check
+ * fails there, since a shuffle requires nothing of its child. The operators above the node run
+ * once per packed partition, and those below it once per input.
+ *
+ * Above the shuffle, only an AQE local read with one mapper per task reports the layout from
+ * before the shuffle. Over a packed shuffle that read reports none, and AQE keeps the full shuffle
+ * read where an operator needs the scan's layout.
+ *
+ * The rule runs after `ReplaceHashWithSortAgg` and `RemoveRedundantSorts`, so the check sees which
+ * operators rely on the scan's ordering once those rules have decided.
+ */
+object PackV2ScanPartitions extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val packing = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum,
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+ plan.transformUp {
+ case shuffle: ShuffleExchangeExec if readsOneScan(shuffle.child) =>
+ shuffle.withNewChildren(Seq(packAtLowestSafePoint(shuffle.child, packing)))
+ }
+ }
+
+ // The node itself is not listed, so a child that is already packed is not packed again.
+ private def readsOneScan(plan: SparkPlan): Boolean = plan match {
+ case scan: BatchScanExec => !scan.scan.isInstanceOf[FileScan]
+ case _: ProjectExec | _: FilterExec | _: SortExec => readsOneScan(plan.children.head)
+ case agg: BaseAggregateExec if agg.requiredChildDistributionExpressions.isEmpty =>
+ readsOneScan(agg.child)
+ case join: BroadcastHashJoinExec => readsOneScan(streamedSide(join))
+ case _ => false
+ }
+
+ private def streamedSide(join: BroadcastHashJoinExec): SparkPlan = join.buildSide match {
+ case BuildLeft => join.right
+ case BuildRight => join.left
+ }
+
+ /**
+ * Tries the node above each operator below `top`, the shuffle's child, on its path from the scan
+ * up, and keeps the first plan that passes `ValidateRequirements`. Otherwise the node goes
+ * directly above `top`.
+ */
+ private def packAtLowestSafePoint(top: SparkPlan, packing: V2ScanPartitionPacking): SparkPlan = {
+ pathToScan(top).tail.reverseIterator
+ .map(packAbove(top, _, packing))
+ .find(ValidateRequirements.validate)
+ .getOrElse(PackScanPartitionsExec(top, packing))
+ }
+
+ // The operators from `plan` down to the scan, in that order. `readsOneScan` held for `plan`.
+ private def pathToScan(plan: SparkPlan): List[SparkPlan] = plan match {
+ case scan: BatchScanExec => scan :: Nil
+ case join: BroadcastHashJoinExec => join :: pathToScan(streamedSide(join))
+ case other => other :: pathToScan(other.children.head)
+ }
+
+ // `plan` with the node above `target`, an operator on its path to the scan.
+ private def packAbove(
+ plan: SparkPlan,
+ target: SparkPlan,
+ packing: V2ScanPartitionPacking): SparkPlan = {
+ if (plan eq target) {
+ PackScanPartitionsExec(plan, packing)
+ } else {
+ plan match {
+ case join: BroadcastHashJoinExec => join.buildSide match {
Review Comment:
Nit: `readsOneScan`, `pathToScan`, and this `BroadcastHashJoinExec` branch support placing `PackScanPartitionsExec` above `BroadcastHashJoinExec` (when an operator above BHJ relies on the streamed scan's ordering), while existing BHJ tests only place `PackScanPartitionsExec` below BHJ. Consider adding a test for this placement path.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub)" <gi...@apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6531367774
Moved from the PR description: local synthetic measurements of size-based packing against `COALESCE`, measured on 4372e37d.
#### Local synthetic measurements against COALESCE
These use `local[4]`, AQE off, a 4 MiB size target, zero opening cost, suggested minimum four tasks, two warmup rounds and five measured rounds. The row source reports estimated sizes of 16 bytes per row; no storage IO is simulated. COALESCE is placed before partial aggregation. Complete aggregate results match in every case.
| Layout | Original tasks / median ms | Size-packed tasks / median ms | Count-matched COALESCE tasks / median ms | Bucket-count COALESCE tasks / median ms |
| --- | --- | --- | --- | --- |
| 512 small inputs, eight keys | 512 / 1,085 | 4 / 57 | 4 / 60 | 8 / 67 |
| 64 larger inputs, one key | 64 / 228 | 16 / 165 | 16 / 188 | 1 / 610 |
| 32 small + four oversized inputs, one key | 36 / 170 | 5 / 105 | 5 / 287 | 1 / 321 |
The small uniform case performs similarly with a suitable COALESCE. In the skewed case, count-matched COALESCE places all four large inputs in one task; size packing leaves each oversized input separate. One-task COALESCE removes the exchange, while the default and packed cases retain the required exchange. These local timings illustrate the sizing tradeoff and do not establish production speedups. The measurement source and reproduction command are below. The generated CSV records trial ranges and every task's row count.
<details>
<summary>Local measurement source, trial ranges and reproduction</summary>
Save the source below as `/tmp/ScanPackingMeasurements.scala`, then run from this Spark checkout using JDK 25:
```bash
build/sbt -Phive \
'set LocalProject("sql") / Test / unmanagedSources += file("/tmp/ScanPackingMeasurements.scala")' \
'sql/Test/runMain org.apache.spark.sql.connector.ScanPackingMeasurements /tmp/scan-packing-measurements.csv'
```
The SBT source setting applies only to that invocation. The fixture uses existing Spark test helpers and stays outside the PR source tree. It generates rows, with no storage IO. Five measured rounds follow two warmup rounds; case order is shuffled deterministically. A one-task COALESCE legitimately removes the exchange, and the reproducer checks that shape as well as complete answers.
| Layout | Variant | Min–max ms | Largest task, rows |
| --- | --- | ---: | ---: |
| small_inputs | default | 1063.5–1143.3 | 128 |
| small_inputs | size_packing | 52.2–63.7 | 16,384 |
| small_inputs | coalesce_matching_count | 53.4–64.3 | 16,384 |
| small_inputs | coalesce_key_count | 60.3–74.9 | 8,192 |
| large_single_key | default | 220.2–230.8 | 65,536 |
| large_single_key | size_packing | 163.1–167.9 | 262,144 |
| large_single_key | coalesce_matching_count | 181.6–192.1 | 262,144 |
| large_single_key | coalesce_key_count | 608.7–623.3 | 4,194,304 |
| skewed_inputs | default | 157.2–179.9 | 524,288 |
| skewed_inputs | size_packing | 95.3–123.8 | 524,288 |
| skewed_inputs | coalesce_matching_count | 283.0–290.9 | 2,099,200 |
| skewed_inputs | coalesce_key_count | 318.5–354.4 | 2,113,536 |
```scala
package org.apache.spark.sql.connector
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import java.util.OptionalLong
import scala.collection.mutable
import scala.util.Random
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.connector.catalog.Table
import org.apache.spark.sql.connector.expressions.FieldReference
import org.apache.spark.sql.connector.read._
import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning}
import org.apache.spark.sql.execution.CoalesceExec
import org.apache.spark.sql.execution.datasources.v2.BatchScanExec
import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
import org.apache.spark.sql.functions._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.util.CaseInsensitiveStringMap
// Local synthetic measurements, outside the PR source tree. No file IO is simulated.
class ScanPackingMeasurementSource extends TestingV2Source {
override def getTable(options: CaseInsensitiveStringMap): Table = new SimpleBatchTable {
override def newScanBuilder(options: CaseInsensitiveStringMap): ScanBuilder =
new SimpleScanBuilder with SupportsReportPartitioning {
private val keys = options.get("keys").toInt
private val inputs = options.get("rows").split(",").zipWithIndex.map { case (rows, i) =>
ScanPackingMeasurementInput(i % keys, rows.toInt)
}
override def planInputPartitions(): Array[InputPartition] =
inputs.map(p => p: InputPartition)
override def outputPartitioning(): Partitioning =
new KeyGroupedPartitioning(Array(FieldReference("i")), inputs.length)
override def createReaderFactory(): PartitionReaderFactory =
ScanPackingMeasurementReaderFactory
}
}
}
case class ScanPackingMeasurementInput(key: Int, rows: Int)
extends HasPartitionStatistics with HasPartitionKey {
override def partitionKey(): InternalRow = InternalRow(key)
override def sizeInBytes(): OptionalLong = OptionalLong.of(rows.toLong * 16)
override def numRows(): OptionalLong = OptionalLong.of(rows)
override def filesCount(): OptionalLong = OptionalLong.empty()
}
object ScanPackingMeasurementReaderFactory extends PartitionReaderFactory {
override def createReader(input: InputPartition): PartitionReader[InternalRow] = {
val p = input.asInstanceOf[ScanPackingMeasurementInput]
new PartitionReader[InternalRow] {
private var row = -1
override def next(): Boolean = { row += 1; row < p.rows }
override def get(): InternalRow = InternalRow(p.key, row)
override def close(): Unit = {}
}
}
}
object ScanPackingMeasurements {
case class Scenario(name: String, keys: Int, rows: Seq[Int])
case class Variant(name: String, packing: Boolean, coalesce: Option[Int])
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder().master("local[4]")
.appName("SPARK-60265 local scan packing measurements")
.config("spark.ui.enabled", "false")
.config(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key, "false")
.config(SQLConf.SHUFFLE_PARTITIONS.key, "4")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key, "4MB")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES.key, "0")
.config(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM.key, "4")
.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
val out = mutable.ArrayBuffer.empty[String]
out += "scenario,variant,raw_inputs,scan_stage_tasks,shuffles,rows," +
"median_ms,min_ms,max_ms,task_rows"
try {
val scenarios = Seq(
Scenario("small_inputs", 8, Seq.fill(512)(128)),
Scenario("large_single_key", 1, Seq.fill(64)(65536)),
Scenario("skewed_inputs", 1, Seq.fill(32)(512) ++ Seq.fill(4)(524288)))
scenarios.foreach { scenario =>
def query(v: Variant): DataFrame = {
spark.conf.set(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key, v.packing)
val loaded = spark.read.format(classOf[ScanPackingMeasurementSource].getName)
.option("keys", scenario.keys).option("rows", scenario.rows.mkString(",")).load()
val input = v.coalesce.map(loaded.coalesce).getOrElse(loaded)
input.groupBy((col("j") % 32).as("g"))
.agg(count(lit(1)).as("n"), sum("i").as("k"), sum("j").as("s"))
}
val packed = Variant("size_packing", true, None)
val initial = query(packed)
val packedScan = initial.queryExecution.executedPlan.collect {
case scan: BatchScanExec => scan
}.head
val packedCount = packedScan.inputRDD.getNumPartitions
val variants = Seq(
Variant("default", false, None), packed,
Variant("coalesce_matching_count", false, Some(packedCount)),
Variant("coalesce_key_count", false, Some(scenario.keys)))
val samples = mutable.Map.empty[String, Vector[Double]].withDefaultValue(Vector.empty)
var expected = Option.empty[Seq[Row]]
// Two warmup rounds, then five interleaved measured rounds with deterministic ordering.
for (round <- -2 until 5; variant <- new Random(42 + round).shuffle(variants)) {
val df = query(variant)
val started = System.nanoTime()
val answer = df.collect().toSeq.sortBy(_.getInt(0))
val elapsed = (System.nanoTime() - started) / 1000000.0
assert(answer.map(_.getLong(1)).sum == scenario.rows.map(_.toLong).sum)
expected.foreach(rows => assert(answer == rows))
expected = Some(answer)
val shuffles = df.queryExecution.executedPlan.collect {
case e: ShuffleExchangeExec => e
}.size
assert(shuffles == (if (variant.coalesce.contains(1)) 0 else 1))
if (round >= 0) samples(variant.name) = samples(variant.name) :+ elapsed
}
variants.foreach { variant =>
val df = query(variant)
df.collect()
val plan = df.queryExecution.executedPlan
val scan = plan.collect { case scan: BatchScanExec => scan }.head
val counts = plan.collect { case c: CoalesceExec => c }.headOption match {
case Some(c) => c.execute().mapPartitions(i => Iterator.single(i.size)).collect().toSeq
case None => scan.inputRDD.mapPartitions(i => Iterator.single(i.size)).collect().toSeq
}
assert(counts.map(_.toLong).sum == scenario.rows.map(_.toLong).sum)
val times = samples(variant.name).sorted
val shuffles = plan.collect { case e: ShuffleExchangeExec => e }.size
val line = Seq(scenario.name, variant.name, scenario.rows.size, counts.size, shuffles,
scenario.rows.map(_.toLong).sum, f"${times(times.size / 2)}%.3f",
f"${times.head}%.3f", f"${times.last}%.3f", counts.mkString(";")).mkString(",")
out += line
println("MEASUREMENT " + line.split(",").take(9).mkString(","))
}
}
Files.write(Paths.get(args(0)), (out.mkString("\n") + "\n")
.getBytes(StandardCharsets.UTF_8))
} finally {
spark.stop()
}
}
}
```
</details>
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6340980826
Thanks for the concrete case, that helps.
One note on the pre-4.2 behavior: when a key had more than one split, 4.1 grouped them and dropped the scan's reported ordering (`DataSourceV2ScanExecBase.outputOrdering`). So with 24 files per bucket, those scans had fewer tasks but no ordering before 4.2 either.
Where a plan uses the scan's partitioning, like a storage-partitioned join or an aggregate on the bucket key, `EnsureRequirements` already groups the splits with a `GroupPartitionsExec`. So the scans that still run one task per split are the ones whose partitioning nothing uses: below a shuffle, or with no such consumer at all, like a collect, a write or the streamed side of a broadcast join.
I'm not against a default-off option for this. Is the case below a shuffle the only one you need? If so, nothing there needs the splits grouped by key, since the shuffle redistributes the rows anyway. A coalesce placed where an exchange goes above the keyed scan would be enough, for example down to the scan's number of keys, which is the task count you had before 4.2. Placed only there, it can't break a consumer that relies on the keyed partitioning. Unlike grouping by key, it doesn't turn a key with many splits into one large task. It also wouldn't need the k-way merge handling, the `peel` and `withJoinKeyPositions` exceptions, or the `preserveScanGrouping` flag. If your connector reports `HasPartitionStatistics.sizeInBytes()`, the target could also be a size, like `spark.sql.files.maxPartitionBytes` for file sources.
The current head also changes two plans with the option on:
- With `spark.sql.sources.v2.bucketing.partiallyClusteredDistribution.enabled`, the SPJ is planned from the already grouped scan. On the SPARK-42038 test data the join runs 3 tasks instead of 7.
- A `SORT BY id, name` over a source that reports `[id, name]` keeps its `SortExec`, also with `spark.sql.sources.v2.bucketing.preserveOrderingOnCoalesce.enabled`.
Neither shape has an exchange above the scan, so a coalesce only there would leave both alone.
Separately, SPARK-55092 changed this behavior in 4.2 without a migration note. If we agree on the option, could you add one in this PR? It could describe the 4.2 change and point to the option.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6697765973
Thanks for another pass, @peter-toth. All seven points are addressed in dc626a7c49a, which is rebased onto master, so packing now builds on your SPARK-60752.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446987272
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsSuite.scala:
##########
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+
+import org.apache.spark.SparkConf
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.catalyst.plans.physical.UnknownPartitioning
+import org.apache.spark.sql.connector.catalog.Identifier
+import org.apache.spark.sql.connector.expressions.Expressions.identity
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+import org.apache.spark.sql.execution.{CoalesceExec, ProjectExec}
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.datasources.v2.V2ScanPartitionPacking
+import org.apache.spark.sql.execution.exchange.{EnsureRequirements, PackV2ScanPartitions, ShuffleExchangeExec, ValidateRequirements}
+import org.apache.spark.sql.internal.SQLConf
+
+class V2ScanPartitionPackingSuite extends org.apache.spark.SparkFunSuite {
+ private case class Sized(bytes: Option[Long]) extends HasPartitionStatistics {
+ override def sizeInBytes(): OptionalLong = bytes.map(OptionalLong.of)
+ .getOrElse(OptionalLong.empty())
+ override def numRows(): OptionalLong = OptionalLong.empty()
+ override def filesCount(): OptionalLong = OptionalLong.empty()
+ }
+ private def inputs(sizes: Long*): Seq[Option[InputPartition]] =
+ sizes.map(size => Some(Sized(Some(size))))
+
+ test("pack actual input sizes, keeping oversized splits separate and covering each input once") {
+ val policy = V2ScanPartitionPacking(100, 0, 1, Some(1))
+ val parts = inputs(30, 40, 200, 20, 30, 90)
+ val groups = policy.pack(parts)
+ assert(groups === Seq(Seq(0, 1), Seq(2), Seq(3, 4), Seq(5)))
+ assert(groups.flatten === parts.indices)
+ assert(policy.pack(Seq.empty).isEmpty)
+ assert(policy.pack(inputs(0, 0, 0)) === Seq(Seq(0, 1, 2)))
+ }
+
+ test("opening cost and suggested parallelism constrain small inputs") {
+ assert(V2ScanPartitionPacking(100, 10, 1, None).pack(inputs(40, 40, 0)) ===
+ Seq(Seq(0, 1), Seq(2)))
+ assert(V2ScanPartitionPacking(1000, 0, 3, None).pack(inputs(100, 100, 100, 100)) ===
+ Seq(Seq(0), Seq(1), Seq(2), Seq(3)))
+ assert(V2ScanPartitionPacking(5, 10, 1, None).pack(inputs(0, 0)) ===
+ Seq(Seq(0), Seq(1)))
+ }
+
+ test("missing, mixed and negative sizes require an explicit count fallback") {
+ val unknown = Some(new InputPartition {})
+ Seq(unknown, Some(Sized(None)), Some(Sized(Some(-1)))).foreach { p =>
+ val parts = inputs(30, 40) :+ p
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(parts).size === 3)
+ assert(V2ScanPartitionPacking(100, 0, 1, Some(2)).pack(parts) ===
+ Seq(Seq(0), Seq(1, 2)))
+ assert(V2ScanPartitionPacking(100, 0, 1, Some(10)).pack(parts).size === 3)
+ }
+ }
+
+ test("overflow, exact limits and runtime-pruned empty slots") {
+ val policy = V2ScanPartitionPacking(Long.MaxValue, 10, 1, None)
+ assert(policy.pack(inputs(Long.MaxValue, 1)) === Seq(Seq(0), Seq(1)))
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(inputs(100, 1)) ===
+ Seq(Seq(0), Seq(1)))
+ assert(V2ScanPartitionPacking(100, 0, 1, None).pack(
+ Seq(None, Some(Sized(Some(30))), None, Some(Sized(Some(40))))) ===
+ Seq(Seq(0, 1, 2, 3)))
+ }
+}
+
+class PackV2ScanPartitionsSuite extends KeyGroupedPartitioningSuiteBase {
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 2400L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after { catalog.clearTables() }
+
+ private def createSplits(keys: Int = 2, splits: Int = 24, keyed: Boolean = true): Unit = {
+ createTable(items, itemsColumns, if (keyed) Array(identity("id")) else Array.empty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES " + (1 to keys).flatMap { id =>
+ (1 to splits).map(i => s"($id, 'split$i', 1.0, NULL)")
+ }.mkString(", "))
+ }
+
+ test("SPARK-60265: scan packing is disabled by default") {
+ createSplits(splits = 3)
+ assert(!spark.sessionState.conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED))
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ assert(collectScans(df.queryExecution.executedPlan).forall(_.partitionPacking.isEmpty))
+ }
+
+ test("SPARK-60265: size-pack keyed and unkeyed scans before partial aggregation") {
+ for (keyed <- Seq(false, true)) {
+ createSplits(keyed = keyed)
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ bucketing <- Seq(false, true)) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_ENABLED.key -> bucketing.toString) {
+ val df = sql(s"SELECT price, count(*), max(id) FROM testcat.ns.$items GROUP BY price")
+ checkAnswer(df, Seq(Row(1.0, 48L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.inputRDD.getNumPartitions === (if (packing) 2 else 48))
+ assert(scan.partitionPacking.isDefined === packing)
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ val aggregate = collect(exchange.child) { case a: BaseAggregateExec => a }.head
+ // Once per packed task, rather than once per split inside a CoalesceExec.
+ val partialRows = aggregate.execute().count()
+ assert(partialRows === (if (packing) 2L else 48L))
+ assert(collect(plan) { case c: CoalesceExec => c }.isEmpty)
+ assert(ValidateRequirements.validate(stripAQEPlan(plan)))
+ }
+ }
+ catalog.dropTable(Identifier.of(Array("ns"), items))
+ }
+ }
+
+ test("SPARK-60265: packing depends on bytes rather than key count") {
+ createSplits(keys = 1)
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "600") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, (1 to 24).map(i => Row(s"split$i", 1L)))
+ val scan = collectScans(df.queryExecution.executedPlan).head
+ assert(scan.inputRDD.getNumPartitions === 4)
+ assert(scan.outputPartitioning === UnknownPartitioning(0))
+ assert(scan.outputOrdering.isEmpty)
+ }
+ }
+
+ test("SPARK-60265: row conversion survives direct collection, shuffle, filtering and codegen") {
+ createSplits(splits = 3)
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE id > 0" else ""
+ val direct = sql(s"SELECT id, name FROM testcat.ns.$items$where")
+ checkAnswer(direct, for (id <- 1 to 2; i <- 1 to 3) yield Row(id, s"split$i"))
+ val plan = stripAQEPlan(direct.queryExecution.executedPlan)
+ assert(collectScans(plan).head.partitionPacking.isDefined)
+ assert(collect(plan) { case p: ProjectExec => p }.nonEmpty || codegen)
+ assert(plan.execute().map(_.isInstanceOf[UnsafeRow]).collect().forall(value => value))
+ val shuffled = sql(s"SELECT name, count(*), max(id) FROM testcat.ns.$items$where " +
+ "GROUP BY name")
+ checkAnswer(shuffled, (1 to 3).map(i => Row(s"split$i", 2L, 2L)))
+ assert(ValidateRequirements.validate(stripAQEPlan(shuffled.queryExecution.executedPlan)))
+ }
+ }
+ }
+
+ test("SPARK-60265: repeated requirement planning keeps packing stable") {
+ createSplits(splits = 3)
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = sql(s"SELECT name, count(*) FROM testcat.ns.$items GROUP BY name")
+ val once = EnsureRequirements()(df.queryExecution.sparkPlan)
+ val twice = EnsureRequirements()(once)
+ assert(PackV2ScanPartitions(twice) === twice)
+ assert(collectScans(twice).head.partitionPacking.isDefined)
+ assert(ValidateRequirements.validate(twice))
+ checkAnswer(df, (1 to 3).map(i => Row(s"split$i", 2L)))
+ }
+ }
+
+ test("SPARK-60265: empty scans and explicit coalesces remain unchanged") {
+ createTable(items, itemsColumns, Array(identity("id")))
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val empty = spark.table(s"testcat.ns.$items")
+ checkAnswer(empty, Seq.empty)
+ assert(collectScans(empty.queryExecution.executedPlan).head.partitionPacking.isEmpty)
+ sql(s"INSERT INTO testcat.ns.$items VALUES (1, 'a', 1.0, NULL), (2, 'b', 1.0, NULL)")
+ val input = spark.table(s"testcat.ns.$items")
+ val df = input.coalesce(1).groupBy("name").count()
+ checkAnswer(df, Seq(Row("a", 1L), Row("b", 1L)))
+ assert(collectScans(df.queryExecution.executedPlan).head.partitionPacking.isEmpty)
+ assert(collect(df.queryExecution.executedPlan) { case c: CoalesceExec => c.numPartitions } ===
+ Seq(1))
+ }
+ }
+}
+
+/** Re-run existing SPJ, ordering and reuse regressions with scan packing enabled. */
+class KeyGroupedPartitioningPackScanPartitionsSuite extends KeyGroupedPartitioningSuite {
Review Comment:
Done in 3231cced: added `@ExtendedSQLTest` to all three suites.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7144397377
Thanks @ulysses-you and @peter-toth. Updated in 73d0543, and rebased on master without #60453:
- `PackV2ScanPartitions` tries the node at each position from the scan up and keeps the first where `ValidateRequirements.validate` passes; directly below the shuffle is the fallback. For projects, filters, local sorts, partial hash aggregates and a broadcast hash join's streamed side, the node goes directly above the scan. In Peter's case it goes above the partial `SortAggregateExec`, and no sort is added.
- @ulysses-you, the rule runs after `ReplaceHashWithSortAgg` and `RemoveRedundantSorts`, in both `QueryExecution.preparations` and AQE's `queryStagePreparationRules`, so the check sees which operators rely on the scan's ordering once those rules have decided. A new test fails if it runs before `RemoveRedundantSorts`.
- The opening cost is charged per file: `openCostInBytes * max(filesCount.orElse(1), 1)`. An input joins a task only if all of its files would, as `FilePartition` checks each file.
- The five configs and their doc rows say 4.5.0.
- The AQE local-read test pins the plan: no shuffle read sits over the `lrt` shuffle, so the sort merge join reads it in full, and the only local reads are the broadcast builds over `lrs1` and `lrs2`. Those report no keyed layout, which holds trivially since both tables are unkeyed.
With the node above the scan, `KeyGroupedPartitioningPackScanPartitionsSuite` also excludes the SPARK-58974 collapse skew guard test. Only its setup check fails: where the `items` side is shuffled, the `Project` it inspects for the collapsed layout now reads the node. What it checks there (no `GroupPartitionsExec`, the shuffle counts) is decided before packing, and its plans without a shuffle aren't packed.
I filed SPARK-62333 for coalescing whole key groups above `GroupPartitionsExec`.
The description is updated to match.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4514417220
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,30 +865,32 @@ private[sql] object GroupPartitionsExec {
*
* Unlike Spark's default coalescer which tries to minimize data movement, this coalescer
* groups partitions based on their partition keys to maintain the grouping semantics
- * required for storage-partitioned operations.
+ * required for storage-partitioned operations. V2 scan partition packing uses it for its groups
+ * too.
*
* @param groupedPartitions Sequence where each element is a sequence of input partition
- * indices that should be grouped together
+ * indices that should be grouped together. Only the driver reads it,
+ * so it is not serialized into tasks.
*/
class GroupedPartitionCoalescer(
Review Comment:
**Finding 16.** This narrows what I asked for in finding 14. Reusing this coalescer for packing is right, but changing it is an improvement of its own, separate from packing:
- The groups stay out of the task binary. `GroupPartitionsExec` has always shipped them there, although only `getPartitions` on the driver reads them.
- Tied hosts are spread across groups, and a group of one partition names no location.
For `GroupPartitionsExec` over a scan, none of the location changes fire, because its child's RDD reports no locations. This PR's test "storage-partitioned groups over a scan take their first input's location" shows it. So the location changes only pay off for packing, and they are why the description needs its "With the option off" paragraph. Packing does not need them to work correctly.
Could you move these changes, the new `GroupPartitionsExecSuite` test and the locality checks in `PackV2ScanPartitionsReadSuite` (`:135` and `:175-179`) to a separate improvement ticket and PR that lands before this one? This PR can then use the coalescer as that PR leaves it.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, ShuffleExchangeLike}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+
+/**
+ * Marks V2 scans for packing after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged. Under AQE, a
+ * local shuffle read with one mapper per task reports the layout below its shuffle, which a
+ * packed scan no longer claims.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ * The rule only marks a scan and does not plan its inputs: `BatchScanExec.inputRDD` decides the
+ * groups at execution, from the inputs that runtime filtering leaves.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ * `keepRootLayout` keeps every claim that reaches the plan's root, for a plan whose output
+ * partitioning and ordering reach a consumer, such as a streaming micro-batch's sink.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None,
+ keepRootLayout: Boolean = false) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum,
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty && !scan.scan.isInstanceOf[FileScan] =>
+ // A V2 file scan is already sized by spark.sql.files.*, as a V1 file scan is.
+ scan.withPartitionPacking(options)
+ case _: BatchScanExec => node
+ case _: ShuffleExchangeLike | _: BroadcastExchangeLike =>
+ node.withNewChildren(node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ node.requiredChildOrdering(i).nonEmpty)
+ })
+ case sort: SortExec =>
+ // Keep a scan ordering that makes this sort redundant. Otherwise the existing sort
+ // establishes ordering itself, so packing cannot add a new sort or lose its output order.
+ val redundant = SortOrder.orderingSatisfies(sort.child.outputOrdering, sort.sortOrder)
+ sort.withNewChildren(Seq(rewrite(sort.child,
+ needsPartitioning || sort.requiredChildDistribution.head != UnspecifiedDistribution,
+ redundant)))
+ case _: ProjectExec | _: FilterExec | _: BaseAggregateExec |
+ _: BroadcastHashJoinExec | _: BroadcastNestedLoopJoinExec |
+ _: V2TableWriteExec | _: DataWritingCommandExec | _: WriteFilesExec =>
+ // ReplaceHashWithSortAgg runs later and uses the ordering of an aggregate's child. A V1
+ // file write reads its child's ordering only with planned writes off or concurrent
+ // output writers on, both internal settings, and then sorts the scan's rows itself.
+ val sortAggregate = node match {
+ case agg: BaseAggregateExec => ReplaceHashWithSortAgg.canReplace(agg)
+ case _ => false
+ }
+ val children = node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ needsPartitioning || node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ needsOrdering || sortAggregate || node.requiredChildOrdering(i).nonEmpty)
+ }
+ node.withNewChildren(children)
+ case _ =>
+ // Includes GroupPartitionsExec, UnionExec, windows, explicit coalesces and extensions.
+ // An exchange further down can still isolate a scan from these consumers.
+ node.mapChildren(rewrite(_, needsPartitioning = true, needsOrdering = true))
+ }
+ }
+
+ rewrite(plan, keepRootLayout || requiredDistribution.exists(_ != UnspecifiedDistribution),
Review Comment:
**Finding 18.** Spark already has a rule like this one. `DisableUnnecessaryBucketedScan` withdraws a V1 bucketed scan's layout where nothing uses it. It starts at the root as if nothing consumed it (`DisableUnnecessaryBucketedScan.scala:152`), and only cached plans opt out, through `CacheManager` (SPARK-33075). It does nothing for checkpoints or streaming. On master, a join of two bucketed tables runs without a shuffle, but the same join on a `localCheckpoint()` of one of them shuffles, with AQE on and off.
This PR goes further. It also keeps the root's layout for checkpoints and streaming micro-batches. All of that only keeps a layout for later queries. A withdrawn claim is recorded as withdrawn, so the rows stay correct without it. Part of it follows what I asked for in findings 1 and 10, so this walks back the checkpoint half of finding 1.
Following the bucketed-scan rule means calling `rewrite(plan, needsPartitioning = false, needsOrdering = false)` here, so the rule needs no parameters. The rest then changes like this:
- `ExistingRDD.scala`, `Dataset.scala`, `InsertAdaptiveSparkPlan.scala` and `IncrementalExecution.scala` go back to master. The checkpoint runs `withRegularShuffle` again, and `fromDataset` loses `producedBy`.
- `QueryExecution.scala` and `AdaptiveSparkPlanExec.scala` keep only the rule in their preparation lists. `forCheckpoint`, `lazyCheckpointPlan`, `executedPlanPrepared`, `keepsRootLayout` and the `keepRootLayout` parameters go.
- `BatchScanExec.withoutPacking` goes, since only the checkpoint uses it.
- The `CacheManager` line stays, since the bucketed-scan rule has it too.
- The tuning guide and the description say in one sentence that a checkpoint or a `foreachBatch` Dataset with packed scans at its root does not record their layout, as with auto bucketed scans.
I tried it on this head with the packing suites, the three packing re-runs and the DPP packing suites:
- 588 of 603 tests pass, and no test returns other rows.
- 12 of the 15 failures check the put-back, `keepRootLayout` or `requiredDistribution` themselves.
- The other 3 are the SPARK-53322 checkpoint tests in the packing re-run of `KeyGroupedPartitioningSuite` ("checkpointed scans avoid shuffles for aggregates", "are used for SPJ", "can shuffle other children on SPJ"). With packing on, a later join or aggregate over a checkpointed keyed scan then shuffles. That is the cost, the same one auto bucketed scans have.
Treating the root as a consumer instead would keep those three, but DPP would no longer reuse the join's broadcast. The build side at a DPP subquery's root would stay unpacked while the join packs it below its broadcast, and 61 tests fail that way.
So I'd follow the bucketed-scan rule, and keeping the root's layout can come back as a follow-up if someone needs it.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+
+/**
+ * Immutable sizing policy captured when a scan is prepared, before runtime filtering. It holds the
+ * configured values only. A default that depends on the cluster, such as the minimum partition
+ * count, is resolved when the scan executes, so equal scans planned at different times stay equal.
+ */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Option[Int],
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. If any input
+ * lacks a valid size, the whole scan is grouped by count into at most `maxPartitionNum`
+ * balanced ranges when that cap is set. Returns None when every input stays a partition of its
+ * own, without building a group for each.
+ */
+ def pack(partitions: Seq[InputPartition], defaultMinPartitionNum: => Int): Option[Seq[Range]] = {
+ val numInputs = partitions.length
+ // Unboxed, allocated at the first valid size and read only while every input reports one.
+ var costs: Array[Long] = null
+ var total = 0L
+ var sized = true
+ val inputs = partitions.iterator
+ var index = 0
+ while (sized && inputs.hasNext) {
+ inputs.next() match {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ sized = bytes.isPresent && bytes.getAsLong >= 0
+ if (sized) {
+ if (costs == null) costs = new Array[Long](numInputs)
+ costs(index) = add(bytes.getAsLong, openCostInBytes)
+ total = add(total, costs(index))
+ }
+ case _ => sized = false
+ }
+ index += 1
+ }
+ if (!sized) {
+ // A cap of at least the number of inputs leaves each of them on its own.
+ maxPartitionNum.filter(_ < numInputs).map(byCount(numInputs, _))
+ } else if (numInputs == 0) {
+ None
+ } else {
+ bySize(costs, total, minPartitionNum.getOrElse(defaultMinPartitionNum))
Review Comment:
**Finding 17.** `spark.sql.files.maxPartitionNum` caps the task count of a file scan. When packing by `maxPartitionBytes` gives more partitions than the cap, `FilePartition.getFilePartitions` packs again by `total / maxPartitionNum` and logs a warning (`FilePartition.scala:98-109`). This config has the same name and the same place in the docs, but it caps only a scan with an input that reports no size. A scan whose inputs all report sizes ignores it. Finding 15 only asked the description to say so. This one is about the behaviour itself.
I measured it with 8 inputs of 100 bytes each, `maxPartitionBytes=100` and `maxPartitionNum=2`:
- This V2 scan runs 8 tasks.
- A Parquet scan that `spark.sql.files.maxPartitionBytes` splits into 36 partitions runs 3 tasks with `spark.sql.files.maxPartitionNum=2`.
So a user who sets both families the same way gets a cap on file scans and none on V2 scans. Once this is released, the meaning of a public config is hard to change. Giving it the files meaning on both paths removes the difference. Above the cap, the scan sizes its groups by the cap, and without sizes it groups by count as now. Here:
```scala
val minGroups = minPartitionNum.getOrElse(defaultMinPartitionNum)
val groups = bySize(costs,
math.min(maxPartitionBytes, math.max(openCostInBytes, ceilDiv(total, minGroups))))
// As spark.sql.files.maxPartitionNum: above the cap, size the groups by the cap instead.
val count = groups.fold(numInputs)(_.size)
maxPartitionNum.filter(count > _) match {
case Some(cap) => bySize(costs, ceilDiv(total, cap))
case None => groups
}
```
with `bySize` taking the target instead of computing it, and `ceilDiv` the rounding it does now. With it, the scan above runs 2 tasks. The packing suites pass, except one assertion in "pack actual input sizes, keeping oversized splits separate and covering each input once" (`V2ScanPartitionPackingSuite.scala:38`), which sets `maxPartitionNum = Some(1)` on sized inputs and expects the current meaning. The config doc, the tuning guide and the `Batch.planInputPartitions` javadoc need the same change.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub)" <gi...@apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6504859237
I’ve updated the PR with the Spark-side size-based packing approach we discussed, keeping it default-off. I’ve also added the 4.2 migration note, regression tests and local comparisons with COALESCE.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
Posted by "szehon-ho (via GitHub)" <gi...@apache.org>.
szehon-ho commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4319679103
##########
docs/sql-performance-tuning.md:
##########
@@ -640,6 +640,21 @@ The following SQL properties enable Storage Partition Join in different join que
</td>
<td>3.3.0</td>
</tr>
+ <tr>
+ <td><code>spark.sql.sources.v2.bucketing.groupScanPartitions.enabled</code></td>
+ <td>false</td>
+ <td>
+ When enabled, coalesce scan splits sharing a reported partition key into one task,
Review Comment:
can we also document here that it is not required for SPJ case which does grouping?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6285700295
Thanks for the PR, @rekbun.
I'd rather not make the grouping logic more complex without a concrete case that needs it. Could you share which connector and what table layout you hit this with?
The only connector I know of that reports `KeyGroupedPartitioning` through `SupportsReportPartitioning` is Iceberg, and it doesn't seem to have this problem. With `spark.sql.iceberg.planning.preserve-data-grouping` on, it packs the files of each partition into task groups of `read.split.target-size` (128 MB by default). So it reports several splits for a key only when the key holds more data than that, or when adaptive split sizing splits a small scan to use the cluster's parallelism. In both cases one task per split is what we want below a shuffle.
If a scan doesn't need its `KeyGroupedPartitioning` but has too many small splits, grouping them by key may not be the best answer either. It brings back the pre-4.2 behavior, and I think the current one is better:
- A large key becomes one large task.
- It undoes Iceberg's adaptive split sizing.
There are other ways to cut the number of tasks:
- `coalesce()` or the `COALESCE` hint over the scan works as a workaround today.
- A size-based packing could use `HasPartitionStatistics.sizeInBytes()`, like the file sources do with `spark.sql.files.maxPartitionBytes`.
- Or another connector could pack its splits the way Iceberg does.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4530302690
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+
+/**
+ * Immutable sizing policy captured when a scan is prepared, before runtime filtering. It holds the
+ * configured values only. A default that depends on the cluster, such as the minimum partition
+ * count, is resolved when the scan executes, so equal scans planned at different times stay equal.
+ */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Option[Int],
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. If any input
+ * lacks a valid size, the whole scan is grouped by count into at most `maxPartitionNum`
+ * balanced ranges when that cap is set. Returns None when every input stays a partition of its
+ * own, without building a group for each.
+ */
+ def pack(partitions: Seq[InputPartition], defaultMinPartitionNum: => Int): Option[Seq[Range]] = {
+ val numInputs = partitions.length
+ // Unboxed, allocated at the first valid size and read only while every input reports one.
+ var costs: Array[Long] = null
+ var total = 0L
+ var sized = true
+ val inputs = partitions.iterator
+ var index = 0
+ while (sized && inputs.hasNext) {
+ inputs.next() match {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ sized = bytes.isPresent && bytes.getAsLong >= 0
+ if (sized) {
+ if (costs == null) costs = new Array[Long](numInputs)
+ costs(index) = add(bytes.getAsLong, openCostInBytes)
+ total = add(total, costs(index))
+ }
+ case _ => sized = false
+ }
+ index += 1
+ }
+ if (!sized) {
+ // A cap of at least the number of inputs leaves each of them on its own.
+ maxPartitionNum.filter(_ < numInputs).map(byCount(numInputs, _))
+ } else if (numInputs == 0) {
+ None
+ } else {
+ bySize(costs, total, minPartitionNum.getOrElse(defaultMinPartitionNum))
Review Comment:
Done, as you suggested. When packing by size gives more groups than the cap, `pack` packs again with a target of the scan's total size, including opening costs, divided by the cap. It logs the same warning as `FilePartition`, naming the packing `maxPartitionBytes` key. A scan with an input that reports no size is still grouped by count into at most that many tasks. The config doc, the tuning guide, the config table, the `Batch.planInputPartitions` javadoc and the DataSource V2 guide now say this. A committed `PythonDataSourceSuite` test covers the count path with a Python data source. `V2ScanPartitionPackingSuite` covers the cap, and the "real unkeyed readers" test in `PackV2ScanPartitionsReadSuite` covers your 8-input case end to end. The `:38` assertion no longer sets a cap.
The rule itself now matches files too. An input joins a group unless its size would take the group past the target, and it then adds its size plus the opening cost. The minimum-count target rounds down, as `maxSplitBytes` does, and `openCostInBytes` is internal, as `spark.sql.files.openCostInBytes` is. "sized inputs pack as spark.sql.files.* packs files of the same sizes" in `PackV2ScanPartitionsSuite` runs fixed and random sizes through `FilePartition.getFilePartitions` and `pack` and compares the groups. Before grouping, file scans also split files into chunks of at most `maxSplitBytes` and sort them by size. Packing does neither: it keeps the scan's order and never splits an input.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "ulysses-you (via GitHub) via reviews" <re...@spark.apache.org>.
ulysses-you commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7119540591
thank you @peter-toth and @rekbun , agreed with the lowest safe point, and with deciding it through `ValidateRequirements` rather than an operator list. One thing need to notice, the rule which insert the new operator should be put after the `RemoveRedundantSorts` to make sure it won't break other optimization rules.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "spark-test (via GitHub) via reviews" <re...@spark.apache.org>.
spark-test commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4719962701
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsReadSuite.scala:
##########
@@ -0,0 +1,978 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.{SparkConf, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{DynamicPruningExpression, Literal}
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.connector.catalog.{Column, Table}
+import org.apache.spark.sql.connector.expressions.{FieldReference, LiteralValue, NamedReference, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.Expressions.{identity, sort}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate}
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionKey, HasPartitionStatistics, InputPartition, PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsReportOrdering, SupportsReportPartitioning, SupportsRuntimeV2Filtering}
+import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning, UnknownPartitioning}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, FormattedMode, InputAdapter, PartialReducerPartitionSpec, ProjectedBroadcastValueSubqueryExec, SimpleMode, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, SortAggregateExec}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, FileScan, PackScanPartitionsExec}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, PipelinedShuffleTestSession, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, expr, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsReadSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 300L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after {
+ catalog.clearTables()
+ }
+
+ private def populate(): Unit = {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ "(1, 'aa', 1.0, NULL), (1, 'bb', 2.0, NULL), (1, 'cc', 3.0, NULL), " +
+ "(2, 'aa', 4.0, NULL), (2, 'bb', 5.0, NULL), (2, 'cc', 6.0, NULL)")
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The number of rows in each partition of the only packing node of `df`. Over a columnar scan,
+ // the node packs batches.
+ private def rowsPerPackedTask(df: DataFrame): Seq[Int] = {
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ if (nodes.head.supportsColumnar) {
+ nodes.head.executeColumnar()
+ .mapPartitions(batches => Iterator.single(batches.map(_.numRows).sum)).collect().toSeq
+ } else {
+ nodes.head.execute().mapPartitions(rows => Iterator.single(rows.size)).collect().toSeq
+ }
+ }
+
+ private def sized(sizes: String): DataFrame =
+ spark.read.format(classOf[SizedPackingRowSource].getName).option("sizes", sizes).load()
+
+ test("SPARK-60265: packed readers preserve storage filters and their checked column") {
+ // The storage filter source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.V2_STORAGE_FILTER_PUSHDOWN_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1000") {
+ withTable("packing_bloom_build") {
+ spark.range(0, 30).selectExpr("id AS bk", "id AS bv")
+ .write.format("parquet").saveAsTable("packing_bloom_build")
+ for (columnar <- Seq(false, true); adaptive <- Seq(false, true);
+ giveUp <- Seq(false, true)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ StorageFilterTestSource.reset()
+ val probe = spark.read.format(classOf[StorageFilterTestSource].getName)
+ .option("numPartitions", "10").option("columnar", columnar.toString)
+ .option("giveUp", giveUp.toString).load()
+ val build = spark.table("packing_bloom_build").where("bv = 5")
+ val df = probe.join(build, probe("k") === build("bk"))
+ .select(probe("k"), probe("v"))
+ assert(df.collect().toSeq === Seq(Row(5L, 50L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).find(_.storageFilters.nonEmpty).get
+ val node = packNodes(plan).find(n => collectScans(n).contains(scan)).get
+ assert(scan.inputPartitions.size === 10)
+ assert(node.supportsColumnar === columnar)
+ val packed = if (columnar) node.executeColumnar() else node.execute()
+ assert(packed.getNumPartitions === 2)
+ assert(scan.appendsCheckedColumn)
+ assert(scan.supportsColumnar === columnar)
+ assert(StorageFilterTestSource.filteredReaders.get() === 10)
+ assert(StorageFilterTestSource.checkedColumnRequests.get() === 10)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: columnar readers keep reused batches correct through a packed shuffle") {
+ withTempView("columnar") {
+ spark.read.format(classOf[PackingColumnarScanSource].getName).load()
+ .createOrReplaceTempView("columnar")
+ val expected = Seq((1, 1, Seq(20, 21, 22, 10, 11)), (1, 2, Seq(5, 6)),
+ (2, 3, Seq(30, 31))).flatMap { case (i, k, values) =>
+ values.map(j => Row(j, 1L, i, k))
+ }
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ // This source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE j > 10" else ""
+ val df = sql("SELECT j, count(*), max(i), max(k) FROM columnar" + where + " GROUP BY j")
+ val answers = if (filter) expected.filter(_.getInt(0) > 10) else expected
+ checkAnswer(df, answers)
+ checkAnswer(df, answers)
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ // Directly above the scan, the node packs its batches, and the rows are converted above
+ // the node.
+ val repartitioned = spark.table("columnar").repartition(3)
+ checkAnswer(repartitioned,
+ expected.map(row => Row(row.getInt(2), row.getInt(0), row.getInt(3))))
+ val node = packNodes(repartitioned.queryExecution.executedPlan).head
+ assert(node.supportsColumnar)
+ assert(node.executeColumnar().getNumPartitions === 2)
+ assert(collect(repartitioned.queryExecution.executedPlan) {
+ case ColumnarToRowExec(InputAdapter(_: PackScanPartitionsExec)) => true
+ case ColumnarToRowExec(_: PackScanPartitionsExec) => true
+ }.size === 1)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: real unkeyed readers honor byte bounds and the missing-size fallback") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "100") {
+ def expected(n: Int): Seq[Row] = (0 until n).flatMap(i => (0 to i).map(j => Row(i, j)))
+ val bounded = sized("30,40,200,20,30,90").repartition(2)
+ checkAnswer(bounded, expected(6))
+ assert(rowsPerPackedTask(bounded) === Seq(3, 3, 9, 6))
+
+ // As with spark.sql.files.maxPartitionNum, above the cap the inputs are packed by the
+ // scan's total size over it.
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2") {
+ val capped = sized(Seq.fill(8)("100").mkString(",")).repartition(2)
+ checkAnswer(capped, expected(8))
+ assert(rowsPerPackedTask(capped) === Seq(10, 26))
+ }
+
+ // A scan with an input that reports no size is grouped by count, and only under the cap.
+ val unsized = "?,20,-1,40,?"
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "3") {
+ val capped = sized(unsized).repartition(2)
+ checkAnswer(capped, expected(5))
+ assert(rowsPerPackedTask(capped) === Seq(1, 5, 9))
+ }
+ val unchanged = sized(unsized).repartition(2)
+ checkAnswer(unchanged, expected(5))
+ assert(rowsPerPackedTask(unchanged) === Seq(1, 2, 3, 4, 5))
+ }
+ }
+
+ test("SPARK-60265: packed tasks prefer the host that most of their inputs report") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ // Three inputs per task. Each task's first input reports the other task's host, which is
+ // the one the scheduler would take through the lineage if the task named no host.
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", Seq.fill(6)("100").mkString(","))
+ .option("hosts", "h2,h1,h1,h1,h2,h2")
+ .load()
+ .repartition(2)
+ checkAnswer(df, (0 until 6).flatMap(i => (0 to i).map(j => Row(i, j))))
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ val packed = nodes.head.execute()
+ assert(packed.partitions.indices.map(sparkContext.getPreferredLocs(packed, _).map(_.host))
+ === Seq(Seq("h1"), Seq("h2")))
+ }
+ }
+
+ test("SPARK-60265: packed columnar readers close on early stop and task failure") {
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = spark.read.format(classOf[PackingColumnarScanSource].getName).load().repartition(3)
+ val packed = packNodes(df.queryExecution.executedPlan).head.executeColumnar()
+ PackingColumnarReaderFactory.opened.set(0)
+ PackingColumnarReaderFactory.closed.set(0)
+ assert(packed.mapPartitions(_.take(1)).count() === 2)
+ assert(PackingColumnarReaderFactory.opened.get() === 2)
+ assert(PackingColumnarReaderFactory.closed.get() === 2)
+ intercept[SparkException] {
+ packed.mapPartitions { batches =>
+ if (batches.hasNext) throw new IllegalStateException("intentional reader failure")
+ batches
+ }.count()
+ }
+ assert(PackingColumnarReaderFactory.opened.get() > 2)
+ eventually(timeout(10.seconds), interval(10.milliseconds)) {
+ assert(PackingColumnarReaderFactory.closed.get() ===
+ PackingColumnarReaderFactory.opened.get())
+ }
+ }
+ }
+
+ test("SPARK-60265: a range shuffle over packed inputs keeps the complete global ordering") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT id, name FROM testcat.ns.$items ORDER BY name, id")
+ assert(df.collect().toSeq === Seq(Row(1, "aa"), Row(2, "aa"), Row(1, "bb"),
+ Row(2, "bb"), Row(1, "cc"), Row(2, "cc")))
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle above a storage-partitioned join leaves the join's inputs alone") {
+ populate()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); partial <- Seq(false, true)) {
+ withSQLConf(enabled -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> partial.toString) {
+ val df = sql(s"SELECT /*+ MERGE(i, p) */ i.name, count(*), max(i.id) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(packNodes(plan).isEmpty)
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ assert(collectGroupPartitions(plan).nonEmpty)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+
+ test("SPARK-60265: shuffles over packed scans remain reusable and execute repeatedly") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true") {
+ val query = s"SELECT name, count(*), max(id) FROM testcat.ns.$items GROUP BY name"
+ val df = sql(s"($query) UNION ALL ($query)")
+ val expected = Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L))
+ checkAnswer(df, expected ++ expected)
+ checkAnswer(df, expected ++ expected)
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case r: ReusedExchangeExec => r }.nonEmpty)
+ val nodes = packNodes(plan)
+ assert(nodes.nonEmpty && nodes.forall(_.execute().getNumPartitions == 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: V2 file scans keep the partitions spark.sql.files.* plans") {
+ withTempPath { dir =>
+ spark.range(0, 80, 1, 8).selectExpr("id", "id % 4 AS k").write.parquet(dir.getCanonicalPath)
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.USE_V1_SOURCE_LIST.key -> "",
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> "8",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.read.parquet(dir.getCanonicalPath).groupBy("k").count()
+ checkAnswer(df, (0L until 4L).map(k => Row(k, 20L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.scan.isInstanceOf[FileScan])
+ assert(packNodes(plan).isEmpty)
+ assert(scan.inputRDD.getNumPartitions === 8)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a sort aggregate that uses the scan's ordering") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ // Hash and object-hash aggregates, which ReplaceHashWithSortAgg both replaces, and max of a
+ // string, which plans a sort aggregate directly.
+ val aggregates = Seq(
+ "count(*)" -> Seq(Row("n0", 3L), Row("n1", 3L)),
+ "size(collect_list(id))" -> Seq(Row("n0", 3), Row("n1", 3)),
+ "max(cast(id AS STRING))" -> Seq(Row("n0", "6"), Row("n1", "5")))
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ (aggregate, expected) <- aggregates) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT name, $aggregate FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, expected)
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(collect(exchange.child) { case a: BaseAggregateExec => a.getClass } ===
+ Seq(classOf[SortAggregateExec]))
+ // No sort is added: the partial sort aggregate reads the scan's ordering directly, and
+ // the node goes between it and the shuffle. It still packs there: two tasks, each with
+ // the aggregate's rows for three one-row inputs.
+ assert(collect(exchange.child) { case s: SortExec => s }.isEmpty)
+ if (packing) {
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(exchange.child.children.head.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ }
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ // Six one-row inputs of 100 bytes, sorted by name, which pack into two tasks of three.
+ private def populateOrderedByName(): Unit = {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ }
+
+ test("SPARK-60265: partition-dependent expressions below the node keep the input's partition") {
+ populateOrderedByName()
+ // The partial sort aggregate reads the scan's ordering through the project, so the node goes
+ // above the aggregate, and the project runs once per input below it. The built-in expression
+ // sees the input's partition there, and the UDF that reads the task's sees the packed task.
+ val taskPartition = udf(() => TaskContext.getPartitionId()).asNondeterministic()
+ withSQLConf(enabled -> "true") {
+ val df = spark.table(s"testcat.ns.$items")
+ .select($"name", expr("spark_partition_id()").as("pid"), taskPartition().as("tid"))
+ .groupBy("name").agg(expr("collect_set(pid)"), expr("collect_set(tid)"))
+ val rows = df.collect()
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(rows.flatMap(_.getSeq[Int](1)).toSet === (0 until 6).toSet)
+ assert(rows.flatMap(_.getSeq[Int](2)).toSet === Set(0, 1))
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a broadcast hash join whose streamed side's order " +
+ "an operator above it reads") {
+ populateOrderedByName()
+ createTable(purchases, purchasesColumns, Array.empty)
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+ (1 to 6).map(i => s"($i, 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The join keeps the streamed scan's ordering, which the partial sort aggregate above it
+ // reads, so the node goes above the aggregate, with the join below it.
+ val df = sql(s"SELECT /*+ BROADCAST(p) */ i.name, size(collect_list(i.id)) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("n0", 3), Row("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ val packed = exchange.child.children.head
+ assert(packed.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(packed.exists(_.isInstanceOf[BroadcastHashJoinExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a global sort that a keyed scan's layout satisfies") {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ (1 to 6).map(i => s"($i, 'n${i % 2}', 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.V2_BUCKETING_ENABLED.key -> "true",
+ SQLConf.V2_BUCKETING_SORTING_ENABLED.key -> "true",
+ SQLConf.REMOVE_REDUNDANT_SORTS_ENABLED.key -> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The keyed scan's layout satisfies the sort's ordered distribution, so no range shuffle
+ // sits below the sort, and the node goes above it. The scan's ordering satisfies the sort
+ // too, so it stays only with RemoveRedundantSorts off.
+ val df = spark.table(s"testcat.ns.$items").orderBy("id").groupBy("name")
+ .agg(expr("size(collect_list(id))"))
+ // checkAnswer would compare the rows in order, because of the sort.
+ assert(df.collect().map(row => (row.getString(0), row.getInt(1))).sorted.toSeq ===
+ Seq(("n0", 3), ("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ val nodes = packNodes(plan)
+ assert(nodes.size === 1)
+ assert(nodes.head.child.exists {
Review Comment:
**Nit (P3):** These assertions also hold when the packing node falls back to directly below the shuffle: the global sort is then still in the node's subtree, and the partial aggregate below the node emits one row for each one-row input, so the packed tasks still hold 3 and 3 rows (line 438). Every other placement test expects the node either directly above the scan, the first candidate, or as the shuffle's child, the fallback, so a regression of the lowest-safe-point search that skipped the candidates in between would pass the whole suite. Results would stay correct, but the partial aggregate would run once per input instead of once per packed task. Pinning the position closes the gap, for example:
```scala
val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
val aggregate = collect(exchange.child) { case a: BaseAggregateExec => a }.head
assert(aggregate.child.isInstanceOf[PackScanPartitionsExec])
val rowsPerTask = aggregate.execute().mapPartitions(rows => Iterator.single(rows.size))
assert(rowsPerTask.collect().toSeq === Seq(2, 2))
```
By the review's reading of the plan, `ObjectHashAggregateExec` and `PackScanPartitionsExec` take no part in whole-stage codegen, so nothing sits between them, and the two packed tasks hold ids 1 to 3 and 4 to 6 in key order, each with both names. With the node at the fallback, the aggregate's child is the codegen stage around the sort, and executing the aggregate gives six partitions of one row, so both checks fail. An assertion that the node's own child is the `SortExec` would not work: that child is the codegen stage around the sort.
This extends existing discussions [1](https://github.com/apache/spark/pull/59522#issuecomment-7195803224), [2](https://github.com/apache/spark/pull/59522#discussion_r4703248901).
**Verification:**
- **Behavior:** The test "the node goes above a global sort that a keyed scan's layout satisfies" in PackV2ScanPartitionsReadSuite checks, with AQE on and off, that the partial aggregate's direct child is the packing node and that the aggregate returns two rows in each of its two partitions, so it passes with the node directly above the global sort and would fail with the node directly below the shuffle.
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,114 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
Review Comment:
**Nit (P3):** This summary narrows the rule to ordering. The rule keeps the lowest position where `ValidateRequirements` passes, and that also checks each operator's required distribution. A global `SortExec` requires an `OrderedDistribution`, which a keyed scan's layout satisfies when `spark.sql.sources.v2.bucketing.sorting.enabled` is on, so no range shuffle sits below the sort. With the node directly above the scan, that check fails on the node's `UnknownPartitioning(0)`, and the node goes above the sort although nothing reads the scan's order. That is the position `PackV2ScanPartitionsReadSuite` expects in "the node goes above a global sort that a keyed scan's layout satisfies", so a reader of the guide expects the node directly above the scan in such a plan and finds it above the sort in EXPLAIN. Results are not affected. The sentence before this one states the rule correctly, so only the summary needs to change, for example:
```suggestion
partitioning or ordering. That is directly above the scan, unless an operator relies on the order
or the partitioning the scan reports, such as a sort aggregation with no sort of its own or a
global sort that a keyed scan's layout satisfies. Spark then packs above that operator.
```
The class scaladoc of `PackV2ScanPartitions` narrows it the same way at `sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PackV2ScanPartitions.scala` lines 37-38 ("relies on the scan's ordering, such as a partial sort aggregate with no sort between it and the scan"); it could say "relies on the scan's ordering or partitioning, such as a partial sort aggregate with no sort between it and the scan or a global sort that a keyed scan's layout satisfies".
**Verification:**
- **Inspection:** The placement summary in the DataSource V2 Scan Partition Packing section of docs/sql-performance-tuning.md and the class scaladoc of PackV2ScanPartitions both say that the packing node goes above an operator that relies on the scan's ordering or partitioning, and both give a global sort that a keyed scan's layout satisfies as the example of relying on the partitioning, as the rule's ValidateRequirements check decides.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4530300950
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,30 +865,32 @@ private[sql] object GroupPartitionsExec {
*
* Unlike Spark's default coalescer which tries to minimize data movement, this coalescer
* groups partitions based on their partition keys to maintain the grouping semantics
- * required for storage-partitioned operations.
+ * required for storage-partitioned operations. V2 scan partition packing uses it for its groups
+ * too.
*
* @param groupedPartitions Sequence where each element is a sequence of input partition
- * indices that should be grouped together
+ * indices that should be grouped together. Only the driver reads it,
+ * so it is not serialized into tasks.
*/
class GroupedPartitionCoalescer(
Review Comment:
Moved to SPARK-61279 (#60256): the transient groups, the tie spreading and the single-partition groups. The `:135` test is now that PR's "groups over a parent without locations take their first input's location" test. It coalesces a mapped RDD, as `GroupPartitionsExec` does over a scan, since the source the `:135` test read is a fixture of this PR. Its other test covers the tie spreading and single-partition groups that `:175-179` checked, so I dropped those checks and the source's `hosts` option here. The description's "With the option off" paragraph is gone too. This PR keeps only the call to the coalescer and a sentence in its scaladoc that mentions packing.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.connector.read.{HasPartitionStatistics, InputPartition}
+
+/**
+ * Immutable sizing policy captured when a scan is prepared, before runtime filtering. It holds the
+ * configured values only. A default that depends on the cluster, such as the minimum partition
+ * count, is resolved when the scan executes, so equal scans planned at different times stay equal.
+ */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Option[Int],
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. If any input
+ * lacks a valid size, the whole scan is grouped by count into at most `maxPartitionNum`
+ * balanced ranges when that cap is set. Returns None when every input stays a partition of its
+ * own, without building a group for each.
+ */
+ def pack(partitions: Seq[InputPartition], defaultMinPartitionNum: => Int): Option[Seq[Range]] = {
+ val numInputs = partitions.length
+ // Unboxed, allocated at the first valid size and read only while every input reports one.
+ var costs: Array[Long] = null
+ var total = 0L
+ var sized = true
+ val inputs = partitions.iterator
+ var index = 0
+ while (sized && inputs.hasNext) {
+ inputs.next() match {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ sized = bytes.isPresent && bytes.getAsLong >= 0
+ if (sized) {
+ if (costs == null) costs = new Array[Long](numInputs)
+ costs(index) = add(bytes.getAsLong, openCostInBytes)
+ total = add(total, costs(index))
+ }
+ case _ => sized = false
+ }
+ index += 1
+ }
+ if (!sized) {
+ // A cap of at least the number of inputs leaves each of them on its own.
+ maxPartitionNum.filter(_ < numInputs).map(byCount(numInputs, _))
+ } else if (numInputs == 0) {
+ None
+ } else {
+ bySize(costs, total, minPartitionNum.getOrElse(defaultMinPartitionNum))
Review Comment:
Moved to SPARK-61279 (#60256): the transient groups, the tie spreading and the single-partition groups. The `:135` test is now that PR's "groups over a parent without locations take their first input's location" test. It coalesces a mapped RDD, as `GroupPartitionsExec` does over a scan, since the source the `:135` test read is a fixture of this PR. Its other test covers the tie spreading and single-partition groups that `:175-179` checked, so I dropped those checks and the source's `hosts` option here. The description's "With the option off" paragraph is gone too. This PR keeps only the call to the coalescer and a sentence in its scaladoc that mentions packing.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7044569994
Thank for the rebase @rekbun. Let me review this PR next week.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "ulysses-you (via GitHub) via reviews" <re...@spark.apache.org>.
ulysses-you commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7092854374
Thank you @rekbun for the update, I have another thought about the position of the new operator.
# Design review: pack at the scan, not at the shuffle
## Plan B : pack directly above the BatchScan for simple plans
Today `PackV2ScanPartitions` inserts the node between a `ShuffleExchangeExec` and its child, so every operator in the chain runs once per input partition. That is where the per-input lifetime state comes from: a partial aggregate creates one fast hash map per input, a sort one sorter per input, and SPARK-61647 is needed to release the fast map arrays at task end.
If the node is inserted directly above the `BatchScanExec`, the chain above runs once per packed task. This matches what a v1 file scan does: `FilePartition` packs files into one scan partition at the scan, and every operator above runs per packed task. Concretely:
- a partial aggregate keeps one map per task and emits fewer partial rows;
- a local sort keeps one sorter per task;
- `spark_partition_id()` and `TaskContext.partitionId()` both see the packed task index, instead of the current split where the built-in sees the input index and a UDF sees the task index;
- per-input lifetime state disappears, so this feature no longer depends on SPARK-61647 (that commit can land as an independent change).
Sketch:
Shuffle
+- Project/Filter/local Sort/partial Aggregate/BHJ streamed side
+- PackScanPartitionsExec
+- BatchScanExec
The eligibility should be stated as a requirement, not only as an operator list: the path from the scan to the shuffle must be 1:1 in partitions, and the operator immediately above the node must not require a distribution or an ordering from its child:
- `ProjectExec`/`FilterExec`: no requirement;
- local `SortExec`: `UnspecifiedDistribution`, and its `outputOrdering` is valid for the packed task;
- partial `BaseAggregateExec`: `requiredChildDistributionExpressions = None` means `UnspecifiedDistribution` (`BaseAggregateExec.scala:96-116`); a sort aggregate gets its required ordering from the local sort above the node;
- `BroadcastHashJoinExec` streamed side: `UnspecifiedDistribution` (`BroadcastHashJoinExec.scala:67-75`).
A global `SortExec` must be excluded: it requires `OrderedDistribution(sortOrder)` (`SortExec.scala:55-56`), which `UnknownPartitioning(0)` does not satisfy. Today the rule matches any `SortExec`; please narrow it to local sorts, or place the node above a global sort.
With this placement the node still reports `UnknownPartitioning(0)` and no ordering, which is correct because no operator above it consumes the scan layout. The AQE local-read consequence stays as documented: a one-mapper-per-task local read over a packed shuffle reports an unknown layout, so validation keeps the full shuffle read where an operator would need the scan's keyed layout.
## Then follow-up: coalescing after GroupPartitionsExec
The plans that do expose a keyed layout (storage-partitioned joins, aggregations on the scan keys) should not be handled by tier 1. A separate follow-up can add a coalescing above `GroupPartitionsExec` with a `CoalescedKeyedPartitioning`: each task holds a set of complete key groups, the layout answers `ClusteredDistribution` for the grouped case, and pairing compares the per-task key sets, with shared group boundaries for the two sides of a join (the same shape as `CoalesceShufflePartitions` applying one set of boundaries to all stages in a group, `CoalesceShufflePartitions.scala:80-124`).
Please state the boundary explicitly for the AQE local-read case (a keyed scan that goes straight into a hash shuffle, with no GPE in the plan): either accept the loss in tier 1, or skip tier 1 when the shuffle's parent needs the pre-shuffle layout. A follow-up ticket for the GPE-based coalescing would make the split complete.
## Other findings
1. `openCostInBytes` is charged once per `InputPartition` (`V2ScanPartitionPacking.scala:68,165`), but `HasPartitionStatistics.filesCount()` reports how many files one input reads (`HasPartitionStatistics.java:44-50`), and the same javadoc defines `sizeInBytes()` as "without any opening cost". An input that reads N files pays N opens but is charged one. With one input per directory of 100 small files, the input is charged 1 MB + 4 MB instead of 1 MB + 100 * 4 MB, so the packer puts many more inputs per task than the per-open model would. Either charge `openCostInBytes * max(filesCount.getOrElse(1), 1)`, or change the `sizeInBytes()` javadoc and document the per-input model. The file-side peer charges per file (`FilePartition.scala:75-81`).
2. The five new configs and their doc rows say `4.4.0` (`SQLConf.scala:3619-3690`, `docs/sql-performance-tuning.md:755-793`). `branch-4.x` has been `4.5.0-SNAPSHOT` since 2026-11-21, and `dev/next_version_candidates.py` prints `branch-4.x 4.5.0`. These are new configs, so they should say `4.5.0`.
3. The new AQE local-read test describes the plan incorrectly (`PackV2ScanPartitionsSuite.scala:345-351`): the executed plan reads the wide side (`lrt`) in full and local-reads the narrow sides (`lrs1`/`lrs2`), which are unkeyed, so `localReads.forall(... !KeyedPartitioning)` is vacuous for the case the excluded SPARK-59671 test covered. The answer assertion is useful; please also pin the plan shape (the wide side stays a full shuffle read and no local read reports a keyed layout), or the exclusion reads as an unexplained coverage loss.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6859823579
I pushed the rework (92ad2d4). It's stacked on #60256's new head and on #60453, a separate fix it needs (the memory bullet below).
- `PackScanPartitionsExec` goes between a `ShuffleExchangeExec` and its child, as described above, and decides its groups from the scan's partitions when it executes. `BatchScanExec`, `CacheManager` and `ReplaceHashWithSortAgg` are back to master.
- The node reports `UnknownPartitioning(0)`. Above the shuffle, one reader does look at the layout from before it: an AQE local read with one mapper per task. Over a packed shuffle that read reports none, and where an operator needs the scan's layout, AQE keeps the full shuffle read. That's why `KeyGroupedPartitioningPackScanPartitionsSuite` excludes "SPARK-59671: an AQE local read over a split scan does not lose matches": its setup expects the scan's keyed layout to reach the local read. `PackV2ScanPartitionsSuite` runs the same query with packing and keeps its answer checks.
- With the opt-in local pipelined shuffle, a plan with a packing node keeps regular shuffles, since the node's width is known only at execution. `PackV2ScanPartitionsPipelinedSuite` pins that.
- The operator list is a conservative start from `DisableUnnecessaryBucketedScan`'s. Expand and generate also map partitions one to one; I left them out for now.
- Memory: a packed task runs the operators below the node once per input, and keeps whatever they leave to task completion until it ends. A partial hash aggregate's codegen fast hash map left its bucket array, 512 KiB per input, so 2,048 inputs in one task held 1 GiB. Master has the same problem in fewer plans: `GroupPartitionsExec` above a distinct aggregation's first partial aggregate held 84 MiB with 168 splits of one key. The fix is #60453 (SPARK-61647): `close()` drops the buckets. With it, a packed task over a hash aggregate keeps about 2 KiB per input.
- The read suite again checks that packed tasks prefer their inputs' majority host. I had dropped that check here earlier, but finding 1 on #60256 was about exactly this node over a scan's mapped RDD, so this is the end-to-end check for it.
Two corrections to my last comment:
- Emptied inputs stay in the groups so that every scan partition is still computed once, as on master, not because of global aggregates: the final aggregate emits its row either way.
- The rule runs after `RemoveRedundantSorts` for the local sort under a shuffle, and before columnar transitions and codegen. The skew-join reason was wrong: a shuffle that skew join optimization adds sits above a split join, which the rule doesn't follow.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7115850460
Thanks @ulysses-you and @peter-toth. I agree with the lowest safe point, and I'll implement it as a check rather than an operator list:
- The rule keeps today's eligibility: a one-to-one path from a non-file DSv2 scan to a shuffle.
- On that path, it tries the node at each position from the scan up and takes the first one where the rewritten subtree passes `ValidateRequirements.validate`. The node reports no partitioning and no ordering, so a position below an operator that relies on the scan's ordering fails, as in Peter's sort aggregate example. So does a position below a global sort, since `UnknownPartitioning` doesn't satisfy `OrderedDistribution`.
- Directly below the shuffle always passes, so no plan is worse off than with the current placement.
For projects, filters, partial hash aggregates and a broadcast hash join's streamed side, the node then goes directly above the scan. A partial aggregate builds one map per packed task instead of one per input, `spark_partition_id()` and `TaskContext.partitionId()` agree, and this PR no longer needs SPARK-61647. #60453 still fixes the `GroupPartitionsExec` case on master, so it can go in on its own. The rule still runs before the columnar transitions and `CollapseCodegenStages`, so the node goes under `ColumnarToRowExec` and doesn't split a codegen stage. I'd leave the k-way merge for later.
On the AQE local read, I'll accept the loss in this PR and state it in the description. The local read appears only when AQE turns the join above into a broadcast join at runtime, after this shuffle is planned, so the rule can't account for it. Results don't change, since AQE keeps the full shuffle read where an operator needs the keyed layout.
Other findings:
1. Agreed. The open cost will be charged per file, `openCostInBytes * max(filesCount.orElse(1), 1)`, as `FilePartition` does.
2. The five configs and their doc rows will say 4.5.0.
3. Agreed. The local reads in that test are over `lrs1` and `lrs2`, which are unkeyed, so the assertion holds trivially. I'll fix the comment and pin the plan shape: the `lrt` shuffle is read in full, and no local read reports a keyed layout.
Agreed that the follow-up needs its own ticket. To add to my earlier comment on it:
- For transforms with a `ReducibleFunction`, the existing reducers can coarsen the keys on both sides, e.g. `bucket(1024, x)` to `bucket(64, x)`, or hours to days. The layout stays a `KeyedPartitioning` over the reduced keys, so only choosing the reduction from the sizes is new.
- For identity keys, both sides need the same boundaries over the sorted keys, decided from their combined sizes. That needs a layout with a range of keys per partition.
- A key above the target stays alone, with partial clustering as today.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4745838942
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsReadSuite.scala:
##########
@@ -0,0 +1,978 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.{SparkConf, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{DynamicPruningExpression, Literal}
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.connector.catalog.{Column, Table}
+import org.apache.spark.sql.connector.expressions.{FieldReference, LiteralValue, NamedReference, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.Expressions.{identity, sort}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate}
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionKey, HasPartitionStatistics, InputPartition, PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsReportOrdering, SupportsReportPartitioning, SupportsRuntimeV2Filtering}
+import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning, UnknownPartitioning}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, FormattedMode, InputAdapter, PartialReducerPartitionSpec, ProjectedBroadcastValueSubqueryExec, SimpleMode, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, SortAggregateExec}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, FileScan, PackScanPartitionsExec}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, PipelinedShuffleTestSession, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, expr, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsReadSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 300L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after {
+ catalog.clearTables()
+ }
+
+ private def populate(): Unit = {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ "(1, 'aa', 1.0, NULL), (1, 'bb', 2.0, NULL), (1, 'cc', 3.0, NULL), " +
+ "(2, 'aa', 4.0, NULL), (2, 'bb', 5.0, NULL), (2, 'cc', 6.0, NULL)")
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The number of rows in each partition of the only packing node of `df`. Over a columnar scan,
+ // the node packs batches.
+ private def rowsPerPackedTask(df: DataFrame): Seq[Int] = {
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ if (nodes.head.supportsColumnar) {
+ nodes.head.executeColumnar()
+ .mapPartitions(batches => Iterator.single(batches.map(_.numRows).sum)).collect().toSeq
+ } else {
+ nodes.head.execute().mapPartitions(rows => Iterator.single(rows.size)).collect().toSeq
+ }
+ }
+
+ private def sized(sizes: String): DataFrame =
+ spark.read.format(classOf[SizedPackingRowSource].getName).option("sizes", sizes).load()
+
+ test("SPARK-60265: packed readers preserve storage filters and their checked column") {
+ // The storage filter source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.V2_STORAGE_FILTER_PUSHDOWN_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1000") {
+ withTable("packing_bloom_build") {
+ spark.range(0, 30).selectExpr("id AS bk", "id AS bv")
+ .write.format("parquet").saveAsTable("packing_bloom_build")
+ for (columnar <- Seq(false, true); adaptive <- Seq(false, true);
+ giveUp <- Seq(false, true)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ StorageFilterTestSource.reset()
+ val probe = spark.read.format(classOf[StorageFilterTestSource].getName)
+ .option("numPartitions", "10").option("columnar", columnar.toString)
+ .option("giveUp", giveUp.toString).load()
+ val build = spark.table("packing_bloom_build").where("bv = 5")
+ val df = probe.join(build, probe("k") === build("bk"))
+ .select(probe("k"), probe("v"))
+ assert(df.collect().toSeq === Seq(Row(5L, 50L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).find(_.storageFilters.nonEmpty).get
+ val node = packNodes(plan).find(n => collectScans(n).contains(scan)).get
+ assert(scan.inputPartitions.size === 10)
+ assert(node.supportsColumnar === columnar)
+ val packed = if (columnar) node.executeColumnar() else node.execute()
+ assert(packed.getNumPartitions === 2)
+ assert(scan.appendsCheckedColumn)
+ assert(scan.supportsColumnar === columnar)
+ assert(StorageFilterTestSource.filteredReaders.get() === 10)
+ assert(StorageFilterTestSource.checkedColumnRequests.get() === 10)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: columnar readers keep reused batches correct through a packed shuffle") {
+ withTempView("columnar") {
+ spark.read.format(classOf[PackingColumnarScanSource].getName).load()
+ .createOrReplaceTempView("columnar")
+ val expected = Seq((1, 1, Seq(20, 21, 22, 10, 11)), (1, 2, Seq(5, 6)),
+ (2, 3, Seq(30, 31))).flatMap { case (i, k, values) =>
+ values.map(j => Row(j, 1L, i, k))
+ }
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ // This source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE j > 10" else ""
+ val df = sql("SELECT j, count(*), max(i), max(k) FROM columnar" + where + " GROUP BY j")
+ val answers = if (filter) expected.filter(_.getInt(0) > 10) else expected
+ checkAnswer(df, answers)
+ checkAnswer(df, answers)
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ // Directly above the scan, the node packs its batches, and the rows are converted above
+ // the node.
+ val repartitioned = spark.table("columnar").repartition(3)
+ checkAnswer(repartitioned,
+ expected.map(row => Row(row.getInt(2), row.getInt(0), row.getInt(3))))
+ val node = packNodes(repartitioned.queryExecution.executedPlan).head
+ assert(node.supportsColumnar)
+ assert(node.executeColumnar().getNumPartitions === 2)
+ assert(collect(repartitioned.queryExecution.executedPlan) {
+ case ColumnarToRowExec(InputAdapter(_: PackScanPartitionsExec)) => true
+ case ColumnarToRowExec(_: PackScanPartitionsExec) => true
+ }.size === 1)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: real unkeyed readers honor byte bounds and the missing-size fallback") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "100") {
+ def expected(n: Int): Seq[Row] = (0 until n).flatMap(i => (0 to i).map(j => Row(i, j)))
+ val bounded = sized("30,40,200,20,30,90").repartition(2)
+ checkAnswer(bounded, expected(6))
+ assert(rowsPerPackedTask(bounded) === Seq(3, 3, 9, 6))
+
+ // As with spark.sql.files.maxPartitionNum, above the cap the inputs are packed by the
+ // scan's total size over it.
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2") {
+ val capped = sized(Seq.fill(8)("100").mkString(",")).repartition(2)
+ checkAnswer(capped, expected(8))
+ assert(rowsPerPackedTask(capped) === Seq(10, 26))
+ }
+
+ // A scan with an input that reports no size is grouped by count, and only under the cap.
+ val unsized = "?,20,-1,40,?"
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "3") {
+ val capped = sized(unsized).repartition(2)
+ checkAnswer(capped, expected(5))
+ assert(rowsPerPackedTask(capped) === Seq(1, 5, 9))
+ }
+ val unchanged = sized(unsized).repartition(2)
+ checkAnswer(unchanged, expected(5))
+ assert(rowsPerPackedTask(unchanged) === Seq(1, 2, 3, 4, 5))
+ }
+ }
+
+ test("SPARK-60265: packed tasks prefer the host that most of their inputs report") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ // Three inputs per task. Each task's first input reports the other task's host, which is
+ // the one the scheduler would take through the lineage if the task named no host.
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", Seq.fill(6)("100").mkString(","))
+ .option("hosts", "h2,h1,h1,h1,h2,h2")
+ .load()
+ .repartition(2)
+ checkAnswer(df, (0 until 6).flatMap(i => (0 to i).map(j => Row(i, j))))
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ val packed = nodes.head.execute()
+ assert(packed.partitions.indices.map(sparkContext.getPreferredLocs(packed, _).map(_.host))
+ === Seq(Seq("h1"), Seq("h2")))
+ }
+ }
+
+ test("SPARK-60265: packed columnar readers close on early stop and task failure") {
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = spark.read.format(classOf[PackingColumnarScanSource].getName).load().repartition(3)
+ val packed = packNodes(df.queryExecution.executedPlan).head.executeColumnar()
+ PackingColumnarReaderFactory.opened.set(0)
+ PackingColumnarReaderFactory.closed.set(0)
+ assert(packed.mapPartitions(_.take(1)).count() === 2)
+ assert(PackingColumnarReaderFactory.opened.get() === 2)
+ assert(PackingColumnarReaderFactory.closed.get() === 2)
+ intercept[SparkException] {
+ packed.mapPartitions { batches =>
+ if (batches.hasNext) throw new IllegalStateException("intentional reader failure")
+ batches
+ }.count()
+ }
+ assert(PackingColumnarReaderFactory.opened.get() > 2)
+ eventually(timeout(10.seconds), interval(10.milliseconds)) {
+ assert(PackingColumnarReaderFactory.closed.get() ===
+ PackingColumnarReaderFactory.opened.get())
+ }
+ }
+ }
+
+ test("SPARK-60265: a range shuffle over packed inputs keeps the complete global ordering") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT id, name FROM testcat.ns.$items ORDER BY name, id")
+ assert(df.collect().toSeq === Seq(Row(1, "aa"), Row(2, "aa"), Row(1, "bb"),
+ Row(2, "bb"), Row(1, "cc"), Row(2, "cc")))
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle above a storage-partitioned join leaves the join's inputs alone") {
+ populate()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); partial <- Seq(false, true)) {
+ withSQLConf(enabled -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> partial.toString) {
+ val df = sql(s"SELECT /*+ MERGE(i, p) */ i.name, count(*), max(i.id) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(packNodes(plan).isEmpty)
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ assert(collectGroupPartitions(plan).nonEmpty)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+
+ test("SPARK-60265: shuffles over packed scans remain reusable and execute repeatedly") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true") {
+ val query = s"SELECT name, count(*), max(id) FROM testcat.ns.$items GROUP BY name"
+ val df = sql(s"($query) UNION ALL ($query)")
+ val expected = Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L))
+ checkAnswer(df, expected ++ expected)
+ checkAnswer(df, expected ++ expected)
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case r: ReusedExchangeExec => r }.nonEmpty)
+ val nodes = packNodes(plan)
+ assert(nodes.nonEmpty && nodes.forall(_.execute().getNumPartitions == 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: V2 file scans keep the partitions spark.sql.files.* plans") {
+ withTempPath { dir =>
+ spark.range(0, 80, 1, 8).selectExpr("id", "id % 4 AS k").write.parquet(dir.getCanonicalPath)
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.USE_V1_SOURCE_LIST.key -> "",
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> "8",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.read.parquet(dir.getCanonicalPath).groupBy("k").count()
+ checkAnswer(df, (0L until 4L).map(k => Row(k, 20L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.scan.isInstanceOf[FileScan])
+ assert(packNodes(plan).isEmpty)
+ assert(scan.inputRDD.getNumPartitions === 8)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a sort aggregate that uses the scan's ordering") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ // Hash and object-hash aggregates, which ReplaceHashWithSortAgg both replaces, and max of a
+ // string, which plans a sort aggregate directly.
+ val aggregates = Seq(
+ "count(*)" -> Seq(Row("n0", 3L), Row("n1", 3L)),
+ "size(collect_list(id))" -> Seq(Row("n0", 3), Row("n1", 3)),
+ "max(cast(id AS STRING))" -> Seq(Row("n0", "6"), Row("n1", "5")))
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ (aggregate, expected) <- aggregates) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT name, $aggregate FROM testcat.ns.$items GROUP BY name")
+ checkAnswer(df, expected)
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(packNodes(plan).size === (if (packing) 1 else 0))
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(collect(exchange.child) { case a: BaseAggregateExec => a.getClass } ===
+ Seq(classOf[SortAggregateExec]))
+ // No sort is added: the partial sort aggregate reads the scan's ordering directly, and
+ // the node goes between it and the shuffle. It still packs there: two tasks, each with
+ // the aggregate's rows for three one-row inputs.
+ assert(collect(exchange.child) { case s: SortExec => s }.isEmpty)
+ if (packing) {
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(exchange.child.children.head.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ }
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ // Six one-row inputs of 100 bytes, sorted by name, which pack into two tasks of three.
+ private def populateOrderedByName(): Unit = {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ }
+
+ test("SPARK-60265: partition-dependent expressions below the node keep the input's partition") {
+ populateOrderedByName()
+ // The partial sort aggregate reads the scan's ordering through the project, so the node goes
+ // above the aggregate, and the project runs once per input below it. The built-in expression
+ // sees the input's partition there, and the UDF that reads the task's sees the packed task.
+ val taskPartition = udf(() => TaskContext.getPartitionId()).asNondeterministic()
+ withSQLConf(enabled -> "true") {
+ val df = spark.table(s"testcat.ns.$items")
+ .select($"name", expr("spark_partition_id()").as("pid"), taskPartition().as("tid"))
+ .groupBy("name").agg(expr("collect_set(pid)"), expr("collect_set(tid)"))
+ val rows = df.collect()
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ assert(rows.flatMap(_.getSeq[Int](1)).toSet === (0 until 6).toSet)
+ assert(rows.flatMap(_.getSeq[Int](2)).toSet === Set(0, 1))
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a broadcast hash join whose streamed side's order " +
+ "an operator above it reads") {
+ populateOrderedByName()
+ createTable(purchases, purchasesColumns, Array.empty)
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES " +
+ (1 to 6).map(i => s"($i, 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The join keeps the streamed scan's ordering, which the partial sort aggregate above it
+ // reads, so the node goes above the aggregate, with the join below it.
+ val df = sql(s"SELECT /*+ BROADCAST(p) */ i.name, size(collect_list(i.id)) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("n0", 3), Row("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ val exchange = collect(plan) { case s: ShuffleExchangeExec => s }.head
+ assert(exchange.child.isInstanceOf[PackScanPartitionsExec])
+ val packed = exchange.child.children.head
+ assert(packed.exists(_.isInstanceOf[SortAggregateExec]))
+ assert(packed.exists(_.isInstanceOf[BroadcastHashJoinExec]))
+ assert(rowsPerPackedTask(df) === Seq(3, 3))
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a global sort that a keyed scan's layout satisfies") {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ (1 to 6).map(i => s"($i, 'n${i % 2}', 1.0, NULL)").mkString(", "))
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.V2_BUCKETING_ENABLED.key -> "true",
+ SQLConf.V2_BUCKETING_SORTING_ENABLED.key -> "true",
+ SQLConf.REMOVE_REDUNDANT_SORTS_ENABLED.key -> "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ // The keyed scan's layout satisfies the sort's ordered distribution, so no range shuffle
+ // sits below the sort, and the node goes above it. The scan's ordering satisfies the sort
+ // too, so it stays only with RemoveRedundantSorts off.
+ val df = spark.table(s"testcat.ns.$items").orderBy("id").groupBy("name")
+ .agg(expr("size(collect_list(id))"))
+ // checkAnswer would compare the rows in order, because of the sort.
+ assert(df.collect().map(row => (row.getString(0), row.getInt(1))).sorted.toSeq ===
+ Seq(("n0", 3), ("n1", 3)))
+ val plan = df.queryExecution.executedPlan
+ withClue(plan.treeString) {
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ val nodes = packNodes(plan)
+ assert(nodes.size === 1)
+ assert(nodes.head.child.exists {
Review Comment:
Pinned in 5a14c00 with the suggested checks: the partial aggregate's child is the node, and the aggregate gives two rows in each of its two partitions. With the search limited to `take(1)`, as in the check above, the test now fails.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6838040457
Thanks, @peter-toth and @ulysses-you. I'll rework it as a separate operator, as Peter described:
- `BatchScanExec`, `CacheManager` and `ReplaceHashWithSortAgg` go back to master.
- A rule wraps a `ShuffleExchangeExec`'s child when it reads one non-file DSv2 scan through Project, Filter, Sort, a partial aggregate or a broadcast hash join's streamed side. The first four are the operator `DisableUnnecessaryBucketedScan` allows, and a broadcast hash join maps each streamed partition to one output partition. The rule runs after `RemoveRedundantSorts` rather than right after `EnsureRequirements`, so it doesn't hide the local sort that rule removes under a shuffle, and with AQE it also sees the shuffle that skew join optimization can add.
- At execution, the node packs the scan's inputs left after runtime filtering with the same packer, and runs them through `GroupedPartitionCoalescer`. It reports `UnknownPartitioning(0)`. Inputs that runtime filtering emptied stay in the groups, since a global aggregate still emits a row for an empty partition.
- Plan roots, broadcast build sides and unions stay out of this PR.
- For locations, I'll take finding 1 in #60256, so the groups vote through the scan's lineage.
@ulysses-you, agreed on the analogy with AQE's shuffle read: the node only regroups the partitions it reads. The distribution-preserving version would then be a grouping over GPE that reports a coalesced keyed partitioning, modeled on `CoalescedHashPartitioning`: whole keys per group, boundaries decided at planning from the keyed splits' sizes, and the same boundaries on both sides of a join.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4498501134
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
Review Comment:
Done in dc626a7c49a: `leafNodeDefaultParallelism`, resolved at execution so scan equality doesn't depend on the cluster.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.rdd.{PartitionCoalescer, PartitionGroup, RDD}
+import org.apache.spark.sql.catalyst.plans.physical.KeyedPartitioning
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionStatistics, InputPartition, PartitionReaderFactory, Scan}
+
+/** Immutable sizing policy captured when a scan is prepared, before runtime filtering. */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Int,
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. Missing,
+ * negative or mixed statistics use the explicit count cap, or leave inputs unchanged.
+ * The cap is only a fallback: it never overrides the size limit for inputs reporting bytes.
+ */
+ def pack(partitions: Seq[InputPartition]): Seq[Seq[Int]] = {
+ if (partitions.isEmpty) return Seq.empty
+ val costs = partitions.map {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ Option.when(bytes.isPresent && bytes.getAsLong >= 0)(
+ add(bytes.getAsLong, openCostInBytes))
+ case _ => None
+ }
+ if (costs.exists(_.isEmpty)) {
+ val count = maxPartitionNum.getOrElse(partitions.size).min(partitions.size)
+ // Balanced consecutive ranges, without integer overflow or empty groups.
+ (0 until count).map { index =>
+ val start = (index.toLong * partitions.size / count).toInt
+ val end = ((index.toLong + 1) * partitions.size / count).toInt
+ start until end
+ }
+ } else {
+ val sizes = costs.map(_.get)
+ val total = sizes.foldLeft(0L)(add)
+ val bytesPerTask = total / minPartitionNum + (if (total % minPartitionNum == 0) 0 else 1)
+ val target = math.min(maxPartitionBytes, math.max(openCostInBytes, bytesPerTask))
+ val groups = mutable.ArrayBuffer.empty[Seq[Int]]
+ val current = mutable.ArrayBuffer.empty[Int]
+ var currentBytes = 0L
+ def finish(): Unit = {
+ if (current.nonEmpty) {
+ groups += current.toVector
+ current.clear()
+ currentBytes = 0L
+ }
+ }
+ sizes.zipWithIndex.foreach { case (size, index) =>
+ if (current.nonEmpty && (size > target || currentBytes > target - size)) finish()
+ current += index
+ currentBytes = add(currentBytes, size)
+ if (size >= target && size > 0) finish()
+ }
+ finish()
+ groups.toSeq
+ }
+ }
+
+ private def add(left: Long, right: Long): Long =
+ if (left > Long.MaxValue - right) Long.MaxValue else left + right
+}
+
+/**
+ * Driver-side snapshot of a scan that has already planned its inputs. Adding task sizing reuses
+ * this metadata and factory. Only the sizing policy contributes to scan equality and display.
+ */
+class V2ScanPartitionPackingInfo(
+ val options: V2ScanPartitionPacking,
+ @transient val scan: Scan,
+ @transient val batch: Batch,
+ @transient val inputPartitions: Seq[InputPartition],
+ @transient val readerFactory: PartitionReaderFactory,
+ @transient val keyedPartitioning: Option[KeyedPartitioning]) extends Serializable {
+ override def toString: String = options.toString
+}
+
+/** Use the size planner's groups rather than the RDD coalescer's count-based grouping. */
+private[v2] class V2ScanPartitionCoalescer(@transient groups: Seq[Seq[Int]])
Review Comment:
Done in dc626a7c49a: merged into `GroupedPartitionCoalescer`, with the tie-break, `@transient` groups and no host for single-partition groups. SPJ locality over a scan is unchanged, which a test with per-input hosts checks.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4498497880
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala:
##########
@@ -425,16 +426,36 @@ class QueryExecution(
!hasShuffle(executedPlan)) {
this
} else {
- val session = SparkSession.getOrCloneSessionWithConfigsOff(
- sparkSession, Seq(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED))
- new QueryExecution(session, commandExecuted, mode = mode,
- shuffleCleanupModeOpt = shuffleCleanupModeOpt,
- refreshPhaseEnabled = refreshPhaseEnabled, analyzerOpt = Some(analyzer))
+ withConfigsOff(Seq(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED))
}
}
private[sql] def withRegularShuffle: QueryExecution = lazyRegularShuffle.get
+ /**
+ * A checkpoint reports its plan's output partitioning to the queries that read it later. Its
+ * root has no consumer when it is planned, so scan packing would withdraw a keyed partitioning
+ * those queries could use. Plan it with packing off, as well as with regular shuffles.
+ */
+ private val lazyForCheckpoint = LazyTry {
+ if (!sparkSession.sessionState.conf.v2ScanPartitionPackingEnabled) {
Review Comment:
Done in dc626a7c49a: a checkpoint changes nothing unless putting back the packed scans that reach a non-adaptive root without crossing an exchange changes the partitioning or ordering that root reports; then it reuses the Dataset's prepared plan in the same session, copying only the root path needed to put those scans back. Exchanges, query stages, adaptive roots and subquery plans are left untouched; a put-back scan with runtime filters applies them once more.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6607854493
Thank you @rekbun, let me check this tomorrow.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional coalescing of V2 scans before required shuffles [spark]
Posted by "rekbun (via GitHub)" <gi...@apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6473104114
Thanks, @peter-toth and @ulysses-you. Our inputs don’t implement HasPartitionStatistics today. The connector already has file lengths, so we can expose them.
For this PR, I’d take the Spark-side sizing approach using that existing interface. It would cover unkeyed V2 scans too. I’d start with the cases Peter listed where the plan doesn’t use the scan’s partitioning or ordering, and pack inside the scan so partial aggregation benefits as well.
I’ll keep it default-off and add the 4.2 migration note.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6795866178
@ulysses-you @rekbun, I agree that marking the scan and packing its inputs in `inputRDD` is not the nicest place for this, even if V1 does the same with `spark.sql.files.*`.
I see the problem differently, though. It is not many small partitions with distinct keys. It is many small splits, often of the same key:
- Before 4.2, `BatchScanExec` grouped the splits of a key, and now `GroupPartitionsExec` does it where a consumer needs the keyed layout.
- That grouping also happened to give sensible task sizes when nothing used the `KeyedPartitioning`.
- Without a consumer, every `InputPartition` is a task now, keyed or not.
So what's missing is packing splits by size, the way Iceberg packs its file scan tasks to a target size. That applies to unkeyed scans too. Coalescing across keys, with the layout kept, is a different feature. It only matters where a consumer reads the layout, and there GPE already groups by key.
For the mechanism, what about a separate operator instead of a mode of the scan?
- A rule right after `EnsureRequirements` puts it below each shuffle, wrapping the exchange's child, the way GPE wraps the child of the operator it serves.
- The operators between the node and the scan keep the scan's own partitioning and ordering, and the exchange never reads its child's layout. So nothing has to be proven about the rest of the plan.
- It decides the groups at execution, with a coalescer like GPE's. It uses the sizes of the scan's input partitions after runtime filtering, and reports `UnknownPartitioning(0)`.
- `BatchScanExec` can then go back to what it is on master: no packing field, no partitioning or ordering override and no packing metrics. The metrics move to the node.
- This works where the exchange's child reads one scan through narrow operators.
- The cost is that the operators between the node and the scan run once per original split. A partial aggregate, for example, then emits its partial rows per split rather than per merged task, so with many small splits of the same key it shuffles more than packing inside the scan does.
- A plan root without an exchange, such as a write, would be a separate case, with the `CacheManager` exception from the last round.
Longer term, I could imagine a partitioning that carries an optional key and an optional size per partition. A planner-inserted operator could then group by key, by size or both, to satisfy a requirement or reach a target size. It could also merge keys where that is allowed. That would also give the distribution-preserving coalescing you describe, but I'd keep it out of this PR.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4739654288
##########
python/pyspark/sql/datasource.py:
##########
@@ -678,9 +678,14 @@ def partitions(self) -> Sequence[InputPartition]:
Returns an iterator of partitions for this data source.
Partitions are used to split data reading operations into parallel tasks.
- If this method returns N partitions, the query planner will create N tasks.
+ By default, if this method returns N partitions, the query planner will create N tasks.
Each task will execute :meth:`DataSourceReader.read` in parallel, using the respective
- partition value to read the data.
+ partition value to read the data. When
+ `spark.sql.sources.v2.scanPartitionPacking.enabled` is true and
+ `spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum` is set, Spark can group
+ consecutive partitions into at most that many tasks where a shuffle reads them; see
+ "DataSource V2 Scan Partition Packing" in the SQL performance tuning guide. Such a task
+ calls :meth:`DataSourceReader.read` once for each of its partitions, one after another.
Review Comment:
**Finding 27.** With `spark.python.worker.reuse=false`, such a task keeps one Python worker for each of its partitions until it ends:
- `PythonPartitionReaderFactory.createReader` starts an evaluator, and so a worker, for each input.
- With reuse off, the worker isn't released at the end of its data (`PythonRunner.scala:1469`), and the forked worker waits for the JVM to close its socket (`python/pyspark/daemon.py:267-274`).
- The JVM stops the worker only in the task-completion listener (`PythonRunner.scala:980-989`), and starts a monitor thread for each one (`:998-999`).
- With reuse on, the default, the next input takes the same worker back from the pool.
So a task that packs k inputs holds k idle workers and k monitor threads until it ends, e.g. 500 in each task for 2,000 partitions and `maxPartitionNum=4`. I derived this from the code. Saying so here and in the `maxPartitionNum` doc would cover it, for example: "With `spark.python.worker.reuse` set to false, such a task keeps a Python worker for each of its partitions until it ends." Leaving a Python scan's inputs apart when reuse is off would avoid it instead.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/PackV2ScanPartitionsReadSuite.scala:
##########
@@ -0,0 +1,992 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import java.util.OptionalLong
+import java.util.concurrent.ConcurrentLinkedQueue
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.concurrent.duration._
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.{SparkConf, SparkException, SparkFunSuite, TaskContext}
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.{DynamicPruningExpression, Literal}
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.connector.catalog.{Column, Table}
+import org.apache.spark.sql.connector.expressions.{FieldReference, LiteralValue, NamedReference, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.Expressions.{identity, sort}
+import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate}
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionKey, HasPartitionStatistics, InputPartition, PartitionReader, PartitionReaderFactory, Scan, ScanBuilder, SupportsReportOrdering, SupportsReportPartitioning, SupportsRuntimeV2Filtering}
+import org.apache.spark.sql.connector.read.partitioning.{KeyGroupedPartitioning, Partitioning, UnknownPartitioning}
+import org.apache.spark.sql.execution.{ColumnarToRowExec, FormattedMode, InputAdapter, PartialReducerPartitionSpec, ProjectedBroadcastValueSubqueryExec, ProjectExec, SimpleMode, SortExec, SparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveSparkPlanHelper, AQEShuffleReadExec, ShuffleQueryStageExec}
+import org.apache.spark.sql.execution.aggregate.{BaseAggregateExec, SortAggregateExec}
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, FileScan, PackScanPartitionsExec}
+import org.apache.spark.sql.execution.exchange.{BroadcastExchangeLike, PipelinedShuffleTestSession, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, SortMergeJoinExec}
+import org.apache.spark.sql.execution.vectorized.OnHeapColumnVector
+import org.apache.spark.sql.functions.{broadcast, expr, udf}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+class PackV2ScanPartitionsReadSuite extends KeyGroupedPartitioningSuiteBase {
+ import testImplicits._
+ import PackV2ScanPartitionsSuite.meetsRequirements
+
+ private val enabled = SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED.key
+
+ override def sparkConf: SparkConf = super.sparkConf
+ .set(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD, -1L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES, 0L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES, 300L)
+ .set(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM, 1)
+
+ after {
+ catalog.clearTables()
+ }
+
+ private def populate(): Unit = {
+ createTable(items, itemsColumns, Array(identity("id")))
+ sql(s"INSERT INTO testcat.ns.$items VALUES " +
+ "(1, 'aa', 1.0, NULL), (1, 'bb', 2.0, NULL), (1, 'cc', 3.0, NULL), " +
+ "(2, 'aa', 4.0, NULL), (2, 'bb', 5.0, NULL), (2, 'cc', 6.0, NULL)")
+ }
+
+ private def packNodes(plan: SparkPlan): Seq[PackScanPartitionsExec] =
+ collect(plan) { case p: PackScanPartitionsExec => p }
+
+ // The number of rows in each partition of the only packing node of `df`. Over a columnar scan,
+ // the node packs batches.
+ private def rowsPerPackedTask(df: DataFrame): Seq[Int] = {
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ if (nodes.head.supportsColumnar) {
+ nodes.head.executeColumnar()
+ .mapPartitions(batches => Iterator.single(batches.map(_.numRows).sum)).collect().toSeq
+ } else {
+ nodes.head.execute().mapPartitions(rows => Iterator.single(rows.size)).collect().toSeq
+ }
+ }
+
+ private def sized(sizes: String): DataFrame =
+ spark.read.format(classOf[SizedPackingRowSource].getName).option("sizes", sizes).load()
+
+ test("SPARK-60265: packed readers preserve storage filters and their checked column") {
+ // The storage filter source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.V2_STORAGE_FILTER_PUSHDOWN_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_ENABLED.key -> "true",
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "1000") {
+ withTable("packing_bloom_build") {
+ spark.range(0, 30).selectExpr("id AS bk", "id AS bv")
+ .write.format("parquet").saveAsTable("packing_bloom_build")
+ for (columnar <- Seq(false, true); adaptive <- Seq(false, true);
+ giveUp <- Seq(false, true)) {
+ withSQLConf(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ StorageFilterTestSource.reset()
+ val probe = spark.read.format(classOf[StorageFilterTestSource].getName)
+ .option("numPartitions", "10").option("columnar", columnar.toString)
+ .option("giveUp", giveUp.toString).load()
+ val build = spark.table("packing_bloom_build").where("bv = 5")
+ val df = probe.join(build, probe("k") === build("bk"))
+ .select(probe("k"), probe("v"))
+ assert(df.collect().toSeq === Seq(Row(5L, 50L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).find(_.storageFilters.nonEmpty).get
+ val node = packNodes(plan).find(n => collectScans(n).contains(scan)).get
+ assert(scan.inputPartitions.size === 10)
+ assert(node.supportsColumnar === columnar)
+ val packed = if (columnar) node.executeColumnar() else node.execute()
+ assert(packed.getNumPartitions === 2)
+ assert(scan.appendsCheckedColumn)
+ assert(scan.supportsColumnar === columnar)
+ assert(StorageFilterTestSource.filteredReaders.get() === 10)
+ assert(StorageFilterTestSource.checkedColumnRequests.get() === 10)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: columnar readers keep reused batches correct through a packed shuffle") {
+ withTempView("columnar") {
+ spark.read.format(classOf[PackingColumnarScanSource].getName).load()
+ .createOrReplaceTempView("columnar")
+ val expected = Seq((1, 1, Seq(20, 21, 22, 10, 11)), (1, 2, Seq(5, 6)),
+ (2, 3, Seq(30, 31))).flatMap { case (i, k, values) =>
+ values.map(j => Row(j, 1L, i, k))
+ }
+ for (adaptive <- Seq(false, true); codegen <- Seq(false, true); filter <- Seq(false, true)) {
+ // This source reports no sizes, so the count cap packs it.
+ withSQLConf(enabled -> "true",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.WHOLESTAGE_CODEGEN_ENABLED.key -> codegen.toString) {
+ val where = if (filter) " WHERE j > 10" else ""
+ val df = sql("SELECT j, count(*), max(i), max(k) FROM columnar" + where + " GROUP BY j")
+ val answers = if (filter) expected.filter(_.getInt(0) > 10) else expected
+ checkAnswer(df, answers)
+ checkAnswer(df, answers)
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ // Directly above the scan, the node packs its batches, and the rows are converted above
+ // the node.
+ val repartitioned = spark.table("columnar").repartition(3)
+ checkAnswer(repartitioned,
+ expected.map(row => Row(row.getInt(2), row.getInt(0), row.getInt(3))))
+ val node = packNodes(repartitioned.queryExecution.executedPlan).head
+ assert(node.supportsColumnar)
+ assert(node.executeColumnar().getNumPartitions === 2)
+ assert(collect(repartitioned.queryExecution.executedPlan) {
+ case ColumnarToRowExec(InputAdapter(_: PackScanPartitionsExec)) => true
+ case ColumnarToRowExec(_: PackScanPartitionsExec) => true
+ }.size === 1)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: real unkeyed readers honor byte bounds and the missing-size fallback") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES.key -> "100") {
+ def expected(n: Int): Seq[Row] = (0 until n).flatMap(i => (0 to i).map(j => Row(i, j)))
+ val bounded = sized("30,40,200,20,30,90").repartition(2)
+ checkAnswer(bounded, expected(6))
+ assert(rowsPerPackedTask(bounded) === Seq(3, 3, 9, 6))
+
+ // As with spark.sql.files.maxPartitionNum, above the cap the inputs are packed by the
+ // scan's total size over it.
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2") {
+ val capped = sized(Seq.fill(8)("100").mkString(",")).repartition(2)
+ checkAnswer(capped, expected(8))
+ assert(rowsPerPackedTask(capped) === Seq(10, 26))
+ }
+
+ // A scan with an input that reports no size is grouped by count, and only under the cap.
+ val unsized = "?,20,-1,40,?"
+ withSQLConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "3") {
+ val capped = sized(unsized).repartition(2)
+ checkAnswer(capped, expected(5))
+ assert(rowsPerPackedTask(capped) === Seq(1, 5, 9))
+ assert(packNodes(capped.queryExecution.executedPlan).head
+ .metrics("maxPartitionsPerGroup").value === 2)
+ }
+ val unchanged = sized(unsized).repartition(2)
+ checkAnswer(unchanged, expected(5))
+ assert(rowsPerPackedTask(unchanged) === Seq(1, 2, 3, 4, 5))
+ assert(packNodes(unchanged.queryExecution.executedPlan).head
+ .metrics("maxPartitionsPerGroup").value === 1)
+ }
+ }
+
+ test("SPARK-60265: packed tasks prefer the host that most of their inputs report") {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ // Three inputs per task. Each task's first input reports the other task's host, which is
+ // the one the scheduler would take through the lineage if the task named no host.
+ val df = spark.read.format(classOf[SizedPackingRowSource].getName)
+ .option("sizes", Seq.fill(6)("100").mkString(","))
+ .option("hosts", "h2,h1,h1,h1,h2,h2")
+ .load()
+ .repartition(2)
+ checkAnswer(df, (0 until 6).flatMap(i => (0 to i).map(j => Row(i, j))))
+ val nodes = packNodes(df.queryExecution.executedPlan)
+ assert(nodes.size === 1)
+ val packed = nodes.head.execute()
+ assert(packed.partitions.indices.map(sparkContext.getPreferredLocs(packed, _).map(_.host))
+ === Seq(Seq("h1"), Seq("h2")))
+ }
+ }
+
+ test("SPARK-60265: packed columnar readers close on early stop and task failure") {
+ withSQLConf(enabled -> "true", SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") {
+ val df = spark.read.format(classOf[PackingColumnarScanSource].getName).load().repartition(3)
+ val packed = packNodes(df.queryExecution.executedPlan).head.executeColumnar()
+ PackingColumnarReaderFactory.opened.set(0)
+ PackingColumnarReaderFactory.closed.set(0)
+ assert(packed.mapPartitions(_.take(1)).count() === 2)
+ assert(PackingColumnarReaderFactory.opened.get() === 2)
+ assert(PackingColumnarReaderFactory.closed.get() === 2)
+ intercept[SparkException] {
+ packed.mapPartitions { batches =>
+ if (batches.hasNext) throw new IllegalStateException("intentional reader failure")
+ batches
+ }.count()
+ }
+ assert(PackingColumnarReaderFactory.opened.get() > 2)
+ eventually(timeout(10.seconds), interval(10.milliseconds)) {
+ assert(PackingColumnarReaderFactory.closed.get() ===
+ PackingColumnarReaderFactory.opened.get())
+ }
+ }
+ }
+
+ test("SPARK-60265: a range shuffle over packed inputs keeps the complete global ordering") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = sql(s"SELECT id, name FROM testcat.ns.$items ORDER BY name, id")
+ assert(df.collect().toSeq === Seq(Row(1, "aa"), Row(2, "aa"), Row(1, "bb"),
+ Row(2, "bb"), Row(1, "cc"), Row(2, "cc")))
+ assert(rowsPerPackedTask(df).size === 2)
+ assert(meetsRequirements(df.queryExecution.executedPlan))
+ }
+ }
+ }
+
+ test("SPARK-60265: a shuffle above a storage-partitioned join leaves the join's inputs alone") {
+ populate()
+ createTable(purchases, purchasesColumns, Array(identity("item_id")))
+ sql(s"INSERT INTO testcat.ns.$purchases VALUES (1, 42.0, NULL), (2, 10.0, NULL)")
+ for (adaptive <- Seq(false, true); partial <- Seq(false, true)) {
+ withSQLConf(enabled -> "true",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.V2_BUCKETING_PARTIALLY_CLUSTERED_DISTRIBUTION_ENABLED.key -> partial.toString) {
+ val df = sql(s"SELECT /*+ MERGE(i, p) */ i.name, count(*), max(i.id) " +
+ s"FROM testcat.ns.$items i JOIN testcat.ns.$purchases p ON i.id = p.item_id " +
+ "GROUP BY i.name")
+ checkAnswer(df, Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L)))
+ val plan = df.queryExecution.executedPlan
+ assert(packNodes(plan).isEmpty)
+ assert(collect(plan) { case s: ShuffleExchangeExec => s }.size === 1)
+ assert(collectGroupPartitions(plan).nonEmpty)
+ assert(meetsRequirements(plan))
+ }
+ }
+ }
+
+ test("SPARK-60265: shuffles over packed scans remain reusable and execute repeatedly") {
+ populate()
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString,
+ SQLConf.EXCHANGE_REUSE_ENABLED.key -> "true") {
+ val query = s"SELECT name, count(*), max(id) FROM testcat.ns.$items GROUP BY name"
+ val df = sql(s"($query) UNION ALL ($query)")
+ val expected = Seq(Row("aa", 2L, 2L), Row("bb", 2L, 2L), Row("cc", 2L, 2L))
+ checkAnswer(df, expected ++ expected)
+ checkAnswer(df, expected ++ expected)
+ val plan = df.queryExecution.executedPlan
+ assert(collect(plan) { case r: ReusedExchangeExec => r }.nonEmpty)
+ val nodes = packNodes(plan)
+ assert(nodes.nonEmpty && nodes.forall(_.execute().getNumPartitions == 2))
+ }
+ }
+ }
+
+ test("SPARK-60265: V2 file scans keep the partitions spark.sql.files.* plans") {
+ withTempPath { dir =>
+ spark.range(0, 80, 1, 8).selectExpr("id", "id % 4 AS k").write.parquet(dir.getCanonicalPath)
+ for (adaptive <- Seq(false, true)) {
+ withSQLConf(enabled -> "true", SQLConf.USE_V1_SOURCE_LIST.key -> "",
+ SQLConf.FILES_MIN_PARTITION_NUM.key -> "8",
+ SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM.key -> "2",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
+ val df = spark.read.parquet(dir.getCanonicalPath).groupBy("k").count()
+ checkAnswer(df, (0L until 4L).map(k => Row(k, 20L)))
+ val plan = df.queryExecution.executedPlan
+ val scan = collectScans(plan).head
+ assert(scan.scan.isInstanceOf[FileScan])
+ assert(packNodes(plan).isEmpty)
+ assert(scan.inputRDD.getNumPartitions === 8)
+ }
+ }
+ }
+ }
+
+ test("SPARK-60265: the node goes above a sort aggregate that uses the scan's ordering") {
+ createTable(items, itemsColumns, Array.empty, Array(
+ sort(FieldReference("name"), SortDirection.ASCENDING)))
+ (1 to 6).foreach { i =>
+ sql(s"INSERT INTO testcat.ns.$items VALUES ($i, 'n${i % 2}', 1.0, NULL)")
+ }
+ // Hash and object-hash aggregates, which ReplaceHashWithSortAgg both replaces, and max of a
+ // string, which plans a sort aggregate directly.
+ val aggregates = Seq(
+ "count(*)" -> Seq(Row("n0", 3L), Row("n1", 3L)),
+ "size(collect_list(id))" -> Seq(Row("n0", 3), Row("n1", 3)),
+ "max(cast(id AS STRING))" -> Seq(Row("n0", "6"), Row("n1", "5")))
+ for (adaptive <- Seq(false, true); packing <- Seq(false, true);
+ (aggregate, expected) <- aggregates) {
+ withSQLConf(enabled -> packing.toString,
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
Review Comment:
**Finding 28.** This test expects a partial `SortAggregateExec` for `count(*)` and `size(collect_list(id))`, and gets one only because `spark.sql.execution.replaceHashWithSortAgg` is on by default. With it off, this test fails, and so do "partition-dependent expressions below the node keep the input's partition" (`:367`) and "the node goes above a broadcast hash join whose streamed side's order an operator above it reads" (`:388`). Each finds a hash aggregate where it expects the sort aggregate. The root `AGENTS.md` asks a test to pin the configs its assertions depend on. Here, and in the other two tests:
```suggestion
SQLConf.REPLACE_HASH_WITH_SORT_AGG_ENABLED.key -> "true",
SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> adaptive.toString) {
```
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7315120162
@ulysses-you, can you please recheck if you are ok with this PR?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional coalescing of V2 scans before required shuffles [spark]
Posted by "ulysses-you (via GitHub)" <gi...@apache.org>.
ulysses-you commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6432136847
Thank you @peter-toth for the ping.
V1 already had this problem, and it did not solve it with a task-count target. A bucketed `FileSourceScanExec` reads exactly `numBuckets` partitions and skips the size-based file packing (`maxPartitionBytes` / `openCostInBytes`) of the non-bucketed path. That only pays off when the bucket layout saves something, so `DisableUnnecessaryBucketedScan` runs right after `EnsureRequirements` and falls back to the default file-source parallelism when no operator with a `ClusteredDistribution` / `AllTuples` requirement is reachable, or when an `Exchange` separates the scan from it.
`KeyGroupedPartitioning` is the V2 form of that claim. When SPJ cannot be used it buys nothing, yet it still shapes the plan. Today the only way to switch it off is the session-wide `spark.sql.sources.v2.bucketing.enabled`, which is all-or-nothing. I would add the V2 counterpart of `DisableUnnecessaryBucketedScan`: after `EnsureRequirements`, decide per query that no keyed distribution is consumed, and disable the keyed claim for that scan, so the scan's parallelism is whatever the connector's default planning produces, as it is for V1.
Concretely I see two directions. Both are gated by a plan-level decision about what the consumers rely on; they differ in who performs the regrouping.
**1. Disable the keyed layout when it buys nothing.** The timing is the awkward part: `Batch.planInputPartitions()` usually runs before `EnsureRequirements` has decided anything, so a Spark-side rule alone can withdraw the claim but cannot change the task count. The connector can re-plan, though, and the plan-level decision is the same for every connector. Today that decision has to be reimplemented in each connector; I did exactly that for Paimon in apache/paimon#3928, where `DisableUnnecessaryPaimonBucketedScan` is registered through a `SparkSessionExtensions` query-stage preparation rule, walks the finished physical plan with the same criteria as the V1 rule (an interesting `ClusteredDistribution` / `AllTuples` consumer reachable, or a `ShuffleExchangeLike` in between), and replaces the `BatchScanExec` with a copy whose scan has bucketed scan disabled. Because the scan is a copy rather than a mutation, partition planning runs again, and `getInputPartitions` falls back to the co
nnector's default layout. That works, but every downstream connector would repeat the same traversal, the same criteria and the same gating, and the copies will drift apart. The general form is a small connector API instead: Spark owns the detection and triggers the non-bucketed path, and the connector only returns a scan variant that plans without bucketing, as a fresh object so the re-planning is well defined. A connector then reuses the non-bucketed planning path it already has for tables that are not bucketed, instead of reimplementing the rule.
**2. Spark-side size-based re-sizing.** The gate here is not "SPJ did not happen". Coalescing inside a partition, or inside a key group, keeps the keyed layout intact, so the same sizing can apply when SPJ is in effect; only a regrouping that crosses partition boundaries requires the layout to be unused, which is the case 1 gates on. With that distinction, Spark can size the stage from an interface that already exists, and @peter-toth and @szehon-ho have both pointed at it: `HasPartitionStatistics` (`@since 4.0.0`, SPARK-42040) is a public mix-in on `InputPartition` that reports `sizeInBytes()`, `numRows()` and `filesCount()`, and its javadoc says Spark will use it to decide whether partition grouping applies, though nothing in Spark consumes it yet. Spark can sum the reported bytes, pick a target task size, and coalesce to `ceil(total / target)` tasks inside a partition, or across the stage when nothing relies on the layout, leaving the plan alone when sizes are absent. That is d
ata-aware, unlike a key-count target, and it is not specific to keyed scans, so it could be the general option that was asked for here. Two limits: it only helps connectors that implement the mix-in (Iceberg does not today, and a connector like the one in this PR would need to report sizes), and coalescing only merges adjacent splits, so the resulting task sizes are approximate where a connector-side packer could do better.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446992212
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.rdd.{PartitionCoalescer, PartitionGroup, RDD}
+import org.apache.spark.sql.catalyst.plans.physical.KeyedPartitioning
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionStatistics, InputPartition, PartitionReaderFactory, Scan}
+
+/** Immutable sizing policy captured when a scan is prepared, before runtime filtering. */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Int,
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. Missing,
+ * negative or mixed statistics use the explicit count cap, or leave inputs unchanged.
+ * The cap is only a fallback: it never overrides the size limit for inputs reporting bytes.
+ * Empty runtime-pruned slots are retained and contribute no bytes or opening cost.
Review Comment:
Done in 3231cced: `pack` now takes `Seq[InputPartition]`.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4470165520
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
+ options.pack(scan.inputPartitions).size < scan.inputPartitions.size =>
Review Comment:
**Finding 9.** This guard calls `planInputPartitions()` on every candidate scan while planning, and `withPartitionPacking` then creates its reader factory. On master, an unkeyed scan whose `columnarSupportMode()` is `SUPPORTED` or `UNSUPPORTED` plans its inputs only at execution (SPARK-44505). With a runtime filter it plans only the filtered scan, since `replanWithRuntimeFilters` takes the original inputs by name (`PushDownUtils.scala:295`).
I measured it with an unkeyed source of 8 sized inputs that supports runtime filtering, joined to a small table so that DPP keeps 2 of them. These are its `planInputPartitions()` calls:
| | while planning | in total |
|---|---|---|
| packing off, AQE off or on | 0 | 1 (2 inputs) |
| packing on, AQE off | 1 (8 inputs) | 2 |
| packing on, AQE on | 1 (8 inputs) | 3 (8, 8, 2) |
So with packing on, the scan plans the whole table that DPP is there to skip, and AQE plans it once more when it re-plans. For a connector like Iceberg that is file planning over the whole table. The rows are the same in every run.
Nothing above an eligible scan uses its partitioning or ordering, so the rule could mark every eligible scan and leave the grouping to `inputRDD`. It already packs the filtered inputs there, and keeps them as they are when nothing merges. The snapshot then has no planning-time decision to keep consistent, so a packed copy can plan its inputs like any other copy. I tried this by dropping the guard and the snapshot's inputs, keeping only the options in `V2ScanPartitionPackingInfo`:
- the query above plans 0 times while planning and once in total, AQE on and off;
- 274 of the 279 tests in the packing suites and the three packing re-runs pass;
- the 5 others check what the guard and the snapshot do. 3 expect no packing on a scan that can't merge anything, or the same input instance across copies. 2 read a claim on a scan nothing consumes ("non-clustered distribution: single partition", "SPARK-59995: a scan's output ordering drops sort orders that hold a partition transform"), like the tests this PR already adjusts with `copy(partitionPacking = None)`.
The cost is an explain line, and withdrawn claims nothing reads on an eligible scan that doesn't merge.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
Review Comment:
**Finding 11.** `FilePartition` doesn't implement `HasPartitionStatistics`, so a V2 file scan always takes the count fallback in `pack` (`V2ScanPartitionPacking.scala:47`). A session that sets `maxPartitionNum` for an unsized connector then also re-chunks its Parquet and ORC scans by count. With `spark.sql.sources.useV1SourceList` empty, a Parquet scan of 8 files planned as 8 `FilePartition`s runs as 2 tasks of 40,000 rows with `maxPartitionNum=2`, ignoring `spark.sql.files.maxPartitionBytes`. `spark.sql.files.*` already sizes those scans, as it does V1 file scans, which this option leaves alone. Leaving `FileScan` out keeps them that way:
```suggestion
scan.partitionPacking.isEmpty && !scan.scan.isInstanceOf[FileScan] &&
```
with `FileScan` in the `datasources.v2` import. The same scan then runs 8 tasks.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala:
##########
@@ -425,16 +426,36 @@ class QueryExecution(
!hasShuffle(executedPlan)) {
this
} else {
- val session = SparkSession.getOrCloneSessionWithConfigsOff(
- sparkSession, Seq(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED))
- new QueryExecution(session, commandExecuted, mode = mode,
- shuffleCleanupModeOpt = shuffleCleanupModeOpt,
- refreshPhaseEnabled = refreshPhaseEnabled, analyzerOpt = Some(analyzer))
+ withConfigsOff(Seq(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED))
}
}
private[sql] def withRegularShuffle: QueryExecution = lazyRegularShuffle.get
+ /**
+ * A checkpoint reports its plan's output partitioning to the queries that read it later. Its
+ * root has no consumer when it is planned, so scan packing would withdraw a keyed partitioning
+ * those queries could use. Plan it with packing off, as well as with regular shuffles.
+ */
+ private val lazyForCheckpoint = LazyTry {
+ if (!sparkSession.sessionState.conf.v2ScanPartitionPackingEnabled) {
Review Comment:
**Finding 10.** With packing on, this builds a second `QueryExecution` for every checkpoint, also when no scan in the plan gets packed, e.g. for `spark.range(10).toDF()`. `withRegularShuffle` re-plans only when it has to, and this path has no such check.
The second execution also runs its own refresh phase (`lazyTableVersionsRefreshed`, `:296`). So when a Dataset has already run, its checkpoint reloads versioned tables at their latest version and can hold other rows than the ones the Dataset returned. That part is from reading the code, since the in-memory test catalog doesn't pin versions.
Re-planning only when a scan was packed keeps every other checkpoint on this execution, as on master. It plans this execution first, which a checkpoint on master does anyway:
```suggestion
def hasPackedScan(plan: SparkPlan): Boolean = plan match {
case s: BatchScanExec => s.partitionPacking.isDefined
case a: AdaptiveSparkPlanExec => hasPackedScan(a.executedPlan)
case q: QueryStageExec => hasPackedScan(q.plan)
case other => other.children.exists(hasPackedScan)
}
if (!sparkSession.sessionState.conf.v2ScanPartitionPackingEnabled ||
!hasPackedScan(executedPlan)) {
```
It also needs `BatchScanExec` in the `datasources.v2` import. With it, `PackV2ScanPartitionsPlanSuite` and the 9 `DatasetSuite` checkpoint tests pass, including "checkpointed keyed scans keep their layout for later joins", which still re-plans.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -2644,6 +2644,61 @@ object SQLConf {
.booleanConf
.createWithDefault(true)
+ val V2_SCAN_PARTITION_PACKING_ENABLED =
Review Comment:
**Finding 12.** These five entries sit between `V2_BUCKETING_ENABLED` and `V2_BUCKETING_PUSH_PART_VALUES_ENABLED`, in the middle of the twelve `spark.sql.sources.v2.bucketing.*` entries, although their doc says the feature is independent of V2 bucketing. The repo's `AGENTS.md` asks that a new member go with the code it belongs with rather than split a section. After `V2_BUCKETING_PRESERVE_ORDERING_ON_COALESCE_ENABLED` (`:2833`), or next to `FILES_MAX_PARTITION_NUM` (`:3418`), their file-source counterpart, would keep both groups whole.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
Review Comment:
**Finding 13.** This repeats `SparkSession.leafNodeDefaultParallelism` (`classic/SparkSession.scala:913`), which `FilePartition.maxSplitBytes` uses for the same default:
```suggestion
conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
SparkSession.active.leafNodeDefaultParallelism),
```
with `org.apache.spark.sql.classic.SparkSession` imported in place of `org.apache.spark.sql.SparkSession`, and the `SQLConf` import dropped.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2ScanPartitionPacking.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.datasources.v2
+
+import scala.collection.mutable
+
+import org.apache.spark.rdd.{PartitionCoalescer, PartitionGroup, RDD}
+import org.apache.spark.sql.catalyst.plans.physical.KeyedPartitioning
+import org.apache.spark.sql.connector.read.{Batch, HasPartitionStatistics, InputPartition, PartitionReaderFactory, Scan}
+
+/** Immutable sizing policy captured when a scan is prepared, before runtime filtering. */
+case class V2ScanPartitionPacking(
+ maxPartitionBytes: Long,
+ openCostInBytes: Long,
+ minPartitionNum: Int,
+ maxPartitionNum: Option[Int]) {
+
+ /**
+ * Group adjacent inputs by estimated size, keeping an oversized input on its own. Missing,
+ * negative or mixed statistics use the explicit count cap, or leave inputs unchanged.
+ * The cap is only a fallback: it never overrides the size limit for inputs reporting bytes.
+ */
+ def pack(partitions: Seq[InputPartition]): Seq[Seq[Int]] = {
+ if (partitions.isEmpty) return Seq.empty
+ val costs = partitions.map {
+ case p: HasPartitionStatistics =>
+ val bytes = p.sizeInBytes()
+ Option.when(bytes.isPresent && bytes.getAsLong >= 0)(
+ add(bytes.getAsLong, openCostInBytes))
+ case _ => None
+ }
+ if (costs.exists(_.isEmpty)) {
+ val count = maxPartitionNum.getOrElse(partitions.size).min(partitions.size)
+ // Balanced consecutive ranges, without integer overflow or empty groups.
+ (0 until count).map { index =>
+ val start = (index.toLong * partitions.size / count).toInt
+ val end = ((index.toLong + 1) * partitions.size / count).toInt
+ start until end
+ }
+ } else {
+ val sizes = costs.map(_.get)
+ val total = sizes.foldLeft(0L)(add)
+ val bytesPerTask = total / minPartitionNum + (if (total % minPartitionNum == 0) 0 else 1)
+ val target = math.min(maxPartitionBytes, math.max(openCostInBytes, bytesPerTask))
+ val groups = mutable.ArrayBuffer.empty[Seq[Int]]
+ val current = mutable.ArrayBuffer.empty[Int]
+ var currentBytes = 0L
+ def finish(): Unit = {
+ if (current.nonEmpty) {
+ groups += current.toVector
+ current.clear()
+ currentBytes = 0L
+ }
+ }
+ sizes.zipWithIndex.foreach { case (size, index) =>
+ if (current.nonEmpty && (size > target || currentBytes > target - size)) finish()
+ current += index
+ currentBytes = add(currentBytes, size)
+ if (size >= target && size > 0) finish()
+ }
+ finish()
+ groups.toSeq
+ }
+ }
+
+ private def add(left: Long, right: Long): Long =
+ if (left > Long.MaxValue - right) Long.MaxValue else left + right
+}
+
+/**
+ * Driver-side snapshot of a scan that has already planned its inputs. Adding task sizing reuses
+ * this metadata and factory. Only the sizing policy contributes to scan equality and display.
+ */
+class V2ScanPartitionPackingInfo(
+ val options: V2ScanPartitionPacking,
+ @transient val scan: Scan,
+ @transient val batch: Batch,
+ @transient val inputPartitions: Seq[InputPartition],
+ @transient val readerFactory: PartitionReaderFactory,
+ @transient val keyedPartitioning: Option[KeyedPartitioning]) extends Serializable {
+ override def toString: String = options.toString
+}
+
+/** Use the size planner's groups rather than the RDD coalescer's count-based grouping. */
+private[v2] class V2ScanPartitionCoalescer(@transient groups: Seq[Seq[Int]])
Review Comment:
**Finding 14.** `GroupedPartitionCoalescer` (`GroupPartitionsExec.scala:869`), in the same package, already coalesces an RDD into given `Seq[Seq[Int]]` groups, with the most common preferred host of each group. This class differs only in how it breaks ties across groups, which `PackV2ScanPartitionsReadSuite` pins (`worker-a`, `worker-b`, `worker-a`, `worker-b`). Adding that tie-break to `GroupedPartitionCoalescer` and using it here would leave one class, and the SPJ groups would get the same balancing.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4498495519
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ *
+ * Like `DisableUnnecessaryBucketedScan`, this is a separate rule that runs after
+ * `EnsureRequirements` has planned every exchange. Under AQE, `requiredDistribution` is the
+ * distribution the final plan must satisfy, the same one `EnsureRequirements` is given.
+ */
+case class PackV2ScanPartitions(
+ requiredDistribution: Option[Distribution] = None) extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ if (!conf.v2ScanPartitionPackingEnabled) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.v2ScanPartitionPackingMaxPartitionBytes,
+ conf.v2ScanPartitionPackingOpenCostInBytes,
+ conf.v2ScanPartitionPackingMinPartitionNum.getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.v2ScanPartitionPackingMaxPartitionNum)
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
+ options.pack(scan.inputPartitions).size < scan.inputPartitions.size =>
Review Comment:
Done in dc626a7c49a: the guard is gone; every eligible scan is marked and `inputRDD` packs the runtime-filtered inputs. The marked scan shares its original's `PlannedScan` (SPARK-60752), so creating the marked copy does not repeat the original's `toBatch`, `planInputPartitions` or `createReaderFactory` calls (counting tests, including your DPP case). Executing a checkpoint's put-back scan with runtime filters separately performs one runtime-filter replan, see #10.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "ulysses-you (via GitHub) via reviews" <re...@spark.apache.org>.
ulysses-you commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6793553408
Thank you @rekbun and @peter-toth .
I don't particularly like this approach, and the reason is structural rather than a matter of implementation detail. V1 already shows where this ends: `FileSourceScanExec` packs files inside the scan and reports `UnknownPartitioning(0)`, and `spark.sql.files.*` has remained a leaf-local size heuristic that is only usable where nothing reads the layout; it never grew distribution-preserving coalescing, the behavior Spark implements for shuffle reads by re-planning at stage boundaries and restating the layout as `CoalescedHashPartitioning` or a fewer-partition `RangePartitioning`. This PR repeats the same placement: it packs inside the leaf and decides the groups in `BatchScanExec.inputRDD` at execution, so the scan must give up its keyed partitioning and ordering and report `Unknown(0)`, and the group count exists only as the runtime RDD's partition count, never as a `Partitioning` value during planning; because the grouping is next-fit over adjacent inputs, it also ignores key bou
ndaries and can split one key's splits across partitions. The result is that no operator consuming partitioning or ordering can sit above a packed scan, so the rule has to prove a whole-plan property, its applicable set shrinks as layout-aware operators spread, and distribution-preserving coalescing, which needs a re-planning point, an expressible coarsened partitioning, and shared boundaries across co-partitioned scans, has nothing to hook into. Adding a coalesced partitioning type or making the grouping key-aware would not fix this on its own, because the missing piece is a plan-time producer of the group count, and that requires moving the decision out of `inputRDD` into a node or a stage boundary.
The other direction is to extend `GroupPartitionsExec` with size-based packing, but that would blur what GPE is for. GPE exists to replace a shuffle: `EnsureRequirements` inserts it on a keyed side so that the keyed layout, rather than an exchange, establishes co-partitioning, and everything about the node, from `plannedPartitioning` and the keyed layout checks to replication and padding, is there to keep the partition-to-key mapping valid. Size packing starts from the opposite premise: it is only legal where nobody reads the keyed layout, so the same node would sometimes report a keyed partitioning and sometimes `Unknown(n)`, with the same name, metrics and neighbors but different guarantees, and the existing consumers are written against the keyed meaning; merging distinct keys breaks that invariant as well. Keeping the keyed contract does require the merged groups to be key-group-aware and shared across the two sides, but that is a well-scoped extension the node can grow into s
tep by step, which is exactly what the current design cannot offer. So this route trades a clearer contract for a mode switch and forces every consumer to reason about which mode it is looking at, but it keeps the door open for the coalescing semantics, while the current design closes it.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "ulysses-you (via GitHub) via reviews" <re...@spark.apache.org>.
ulysses-you commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6816619475
Thanks, @peter-toth. A separate node works for me.
It settles the part of my concern that matters most: the decision leaves `BatchScanExec.inputRDD`, the scan keeps the partitioning and ordering master reports for the operators between it and the node, and the exchange case needs no whole-plan proof. `UnknownPartitioning(0)` is fine for now, because the node only goes where nothing above reads its layout.
Agreed on the framing: the common case is many small splits, often of one key, and unkeyed scans need the same packing. The distribution-preserving coalescing I described, with a plan-time partitioning and shared boundaries across co-partitioned scans, can be a follow-up outside this PR.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7099757586
Thanks @ulysses-you for the placement idea.
I think Plan B leaves one case open. Its list covers every operator on the path, and for a sort aggregate it says that the required ordering comes from a local sort above the node. That holds where `EnsureRequirements` added the sort. It adds none, though, where the scan's ordering already satisfies the requirement. For example:
- A partial `SortAggregateExec`, as for `max` of a string, groups by the column that each split is sorted by, such as the sort column of a bucketed table, with its final aggregate above the shuffle.
- It relies on the scan's ordering through a `Project`, with no sort between them.
- With the node directly above the scan, the operator directly above it is the `Project`, which requires nothing, so the conditions hold.
- The packed input is then not sorted, so the sort aggregate's required ordering is no longer met.
Putting the node directly above the scan in such a plan would need a new local sort, which the plan without packing doesn't have. So the rule has to check an ordering that an operator on the path requires all the way down to the node, not only for the operator directly above it.
I suggested placing the node directly below the shuffle, so that the operators between the node and the scan run unchanged and nothing has to be proven about them. The cost was that they run once per input split. SPARK-61647 is a consequence of that, since each packed task runs one partial aggregate per split. Above the scan, the operators run once per packed task, as over a V1 file scan, so a partial aggregate combines all inputs of the task and keeps one map.
Two things could get most of that benefit without an extra sort:
- Place the node at the lowest safe point, the lowest point where nothing above it, up to the shuffle, relies on the scan's partitioning or ordering. For projects, filters, partial hash aggregates and the streamed side of a broadcast hash join, that is directly above the scan. Where an operator relies on the scan's ordering, the node goes above it, at worst directly below the shuffle as now.
- Let the node k-way merge the inputs it packs by the scan's ordering, as `GroupPartitionsExec` does with `preserveOrderingOnCoalesce`, instead of only concatenating them. It could then report that ordering and stay directly above the scan even where an operator uses it. A merge opens all inputs of a packed task at once, though. That costs the most in the case of many small splits that this PR targets, so I'd merge only where an operator needs the ordering. This could also come later.
In short, the best position depends on what runs between the scan and the shuffle:
- A partial hash aggregate is best above the node, where it combines the inputs of a packed task.
- An operator that relies on the scan's ordering is best below the node, unless the node merges, which has its own cost.
So I don't think one fixed position fits every plan. The lowest safe point picks the best one for each plan, without adding work.
@ulysses-you, @rekbun, what do you think?
On the follow-up, I agree that it should not be solved here. Coalescing keyed groups while keeping the layout is a different problem, so it needs its own ticket. As we discussed earlier, it is also not the problem this PR solves.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4710205978
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,112 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
+
+When every input of a scan reports a non-negative `HasPartitionStatistics.sizeInBytes()`, Spark
+packs consecutive inputs into tasks as it packs files: a file joins the current task unless its size
+would take the task past the target, and an input joins only if all of the files it reports would.
+Each input adds its size plus an opening cost for each file it reports through
+`HasPartitionStatistics.filesCount()`, and at least one. Unlike files, which Spark sorts by size
+before packing, the inputs keep the order the scan reads them in. The suggested minimum count helps
+retain parallelism for small scans. Packing never divides a connector input, however large.
+Reported sizes are estimates, so this is not a bound on runtime memory or CPU. As with
+`spark.sql.files.maxPartitionNum`, when packing by size gives more tasks than
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum`, Spark packs the inputs again with a
+target of the scan's total size divided by that cap, ignoring
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionBytes`. If any input of a scan reports no
+valid size, Spark leaves the scan's inputs as they are, unless
+`spark.sql.sources.v2.scanPartitionPacking.maxPartitionNum` is set. Then it groups all of the scan's
+inputs by count into at most that many tasks, which balances input counts, not bytes. This applies
+to any eligible V2 scan with such an input, such as a scan of a Python data source or of a connector
+whose inputs do not implement `HasPartitionStatistics`, but not to file-based V2 sources.
+
+Spark decides the tasks when the shuffle's map stage runs, from the inputs that runtime filtering,
+such as dynamic partition pruning, leaves. An input that runtime filtering emptied joins the task of
+the input before it, or the first task when no input precedes it, even when Spark leaves the other
+inputs as they are. EXPLAIN shows a `PackScanPartitions` node between the scan and the shuffle, and
+its SQL metrics show the number of input partitions, the number of partitions it packed them into,
+and the largest number of input partitions in one partition. The operators above the node run once
+per packed task, so a partial aggregation there emits its rows per task, and built-in expressions
+there that take the partition index, such as `spark_partition_id()`, see the packed task's index.
+The operators below the node, if any, run as they do without packing, once per input, and
+`spark_partition_id()` there sees the input's index. Code that reads `TaskContext.partitionId()`,
+such as a UDF, sees the packed task's index wherever it runs, and so does the shuffle, so a
+round-robin repartition can place rows differently. Packing can reduce useful parallelism, and fewer
Review Comment:
Added in 7ac900f, to the tuning guide, the DSv2 guide and the doc of `spark.sql.sources.v2.scanPartitionPacking.enabled`, with the tie case as you described. The description lists it under user-facing changes.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional coalescing of V2 scans before required shuffles [spark]
Posted by "peter-toth (via GitHub)" <gi...@apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6426181767
Thanks for reworking this into a coalesce below the shuffle, @rekbun. It is the shape I suggested, and it no longer touches the SPJ plans.
Looking at it again, I'm not sure the key count is the right target, though:
- It restores the task count your connector got before 4.2. That grouping came from the SPJ code, which grouped keyed scans even where nothing used their partitioning.
- It has no relation to the data. A key with 100 GB becomes one task, while 10,000 tiny keys stay 10,000 tasks.
- Too many small splits isn't specific to keyed scans. Any DSv2 scan runs one task per `InputPartition`, and AQE can't help a leaf stage, since it only works from shuffle statistics.
File sources already handle this. `spark.sql.files.maxPartitionBytes` and `spark.sql.files.openCostInBytes` pack files by size, and `spark.sql.files.minPartitionNum` and `spark.sql.files.maxPartitionNum` bound the count. DSv2 has `HasPartitionStatistics.sizeInBytes()` (SPARK-42040) for this kind of decision, but nothing uses it yet. szehon-ho asked about the same thing [there](https://github.com/apache/spark/pull/45314#issuecomment-2021228813).
So I'd rather go for a general option, independent of `KeyedPartitioning`:
- Pack a DSv2 scan's splits by size when they report `sizeInBytes()`, and cap their count otherwise, like the file source configs do.
- Apply it only where nothing uses the scan's partitioning or ordering. That is below a shuffle, or where there is no consumer at all, like a collect, a write or the streamed side of a broadcast join.
- Pack at the scan itself. Then a partial aggregate above it combines the splits again, as it did before 4.2.
Would that work for your connector, and would you be open to doing it in that form? Do its splits report their size, or would a count cap be enough?
@dongjoon-hyun @cloud-fan @viirya @ulysses-you @LuciferYang @pan3793, I'm surprised Spark has no generic answer for small DSv2 splits. Did I miss one, or do you have other ideas?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6778779663
Thanks, @peter-toth. I agree with all three, and following the existing features made the change smaller. Addressed in `1719eba15ea`:
- **16.** The coalescer changes are now SPARK-61279 (#60256). This PR is rebased on it.
- **17.** `maxPartitionNum` now has the files meaning on both paths. With 8 sized inputs and `maxPartitionNum=2`, the scan runs 2 tasks. While comparing it with `FilePartition`, I also found that packing by size differed from files when there is an opening cost: an input's own opening cost counted toward the target, and the minimum-count target rounded up. Packing now uses `getFilePartitions`' rule and `maxSplitBytes`' rounding. A new test runs 307 sets of sizes through both and gets the same groups, with and without the cap.
- **18.** The checkpoint put-back and the streaming `keepsRootLayout` are gone. `Dataset`, `LogicalRDD`, `InsertAdaptiveSparkPlan` and `IncrementalExecution` match master again. `QueryExecution` and `AdaptiveSparkPlanExec` only register the rule, which takes no parameters. As with `DisableUnnecessaryBucketedScan`, the root has no consumer. Cached plans keep their layout, because `CacheManager` turns packing off for them unless `canChangeCachedPlanOutputPartitioning` is set.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "peter-toth (via GitHub) via reviews" <re...@spark.apache.org>.
peter-toth commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6920204560
Thanks for the rework, @rekbun, and for the follow-up PRs!
Let's take them one at a time, so that each review stays focused:
1. #60256 first, since this PR builds on it. I posted a new round there today.
2. Then #60453 and this PR.
3. Then #60501, #60502 and #60503.
I'll pick up the next one once the one before it lands.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Allow optional grouping of V2 scan splits below shuffles [spark]
Posted by "rekbun (via GitHub)" <gi...@apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-6323703811
Thanks for the careful review, Peter, and for the context on Iceberg. That is helpful.
The source where we hit this is an in-house DataSource V2 connector for Hive-format bucketed tables. The tables are partitioned by hour and bucketed by a key, and the reported partitioning contains the bucket key, not the hour. The connector currently emits one input per bucket file to retain its per-file sort order. For example, with one file per bucket in each hourly partition, reading a day produces 24 inputs with the same reported key, and a week produces 168.
Before the refactor, Spark grouped those inputs by key, so these scans ran one task per bucket. After it, in the affected queries that still require a downstream shuffle, each input can execute as a separate scan task. That increased task setup, execution, and scheduling overhead in existing production jobs, with higher driver memory pressure and longer runtimes.
I am not proposing a change to the default. Multiple splits can be an intentional sizing decision, and grouping a large or skewed key into one task can remove useful parallelism. I would like to keep the previous grouping policy reachable as an explicit, default-off compatibility option for users upgrading Spark whose connectors and workloads relied on it. If a legacy name would make that purpose clearer, I am happy to use one.
COALESCE is a valid workaround when placed before an existing shuffle. For restoring the historical task count, the bucket count provides a natural target. The difficulty is applying that workaround across existing queries and choosing suitable parallelism as data volume and skew change. Generic coalescing is not key-aware, and placing it between a scan and a consumer that relies on keyed partitioning can introduce an exchange.
Connector-side packing is also a reasonable direction, and we are investigating bounded packing. Our connector reports per-file ordering, so combining files requires either merging their sorted streams or withdrawing that ordering claim and letting Spark add a sort where needed. Packing can be implemented in the connector. The compatibility argument for Spark is that physical planning knows which partitioning and ordering properties the surrounding plan requires, while the connector does not generally see the final physical plan when choosing its inputs.
Size-aware packing using HasPartitionStatistics.sizeInBytes() is a promising longer-term direction for addressing both small tasks and oversized tasks for large or skewed keys. I would be glad to work on that with you. The opt-in would provide a compatibility option while that is developed.
I take the point about complexity. I’ll narrow the PR to the default-off scan-grouping option, preserve required ordering and existing SPJ behavior, and keep unrelated planning changes separate. The public reproducer shows 48 scan tasks becoming two, with the same results and the required shuffle retained. Would that narrower scope address your concern?
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446975025
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PackV2ScanPartitions.scala:
##########
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.SortOrder
+import org.apache.spark.sql.catalyst.plans.physical.{Distribution, UnspecifiedDistribution}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution._
+import org.apache.spark.sql.execution.aggregate.BaseAggregateExec
+import org.apache.spark.sql.execution.command.DataWritingCommandExec
+import org.apache.spark.sql.execution.datasources.WriteFilesExec
+import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec, V2ScanPartitionPacking, V2TableWriteExec}
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec, BroadcastNestedLoopJoinExec}
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Pack V2 scan inputs after distribution and ordering requirements have been planned.
+ * A shuffle or broadcast exchange consumes neither input property. Otherwise, propagate
+ * consumers' requirements conservatively through known operators, including a broadcast
+ * join's streamed side. Keep unknown operators and explicit coalesces unchanged.
+ *
+ * Packing happens inside BatchScanExec, before partial aggregation and UnsafeRow conversion.
+ * No keyed or ordered output is claimed, and scans used by GroupPartitionsExec stay unchanged.
+ */
+object PackV2ScanPartitions extends Rule[SparkPlan] {
+ override def apply(plan: SparkPlan): SparkPlan = apply(plan, None)
+
+ def apply(plan: SparkPlan, requiredDistribution: Option[Distribution]): SparkPlan = {
+ if (!conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_ENABLED)) {
+ return plan
+ }
+ lazy val options = V2ScanPartitionPacking(
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_BYTES),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_OPEN_COST_IN_BYTES),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MIN_PARTITION_NUM).getOrElse(
+ conf.getConf(SQLConf.LEAF_NODE_DEFAULT_PARALLELISM).getOrElse(
+ SparkSession.active.sparkContext.defaultParallelism)),
+ conf.getConf(SQLConf.V2_SCAN_PARTITION_PACKING_MAX_PARTITION_NUM))
+
+ def rewrite(node: SparkPlan, needsPartitioning: Boolean, needsOrdering: Boolean): SparkPlan = {
+ node match {
+ case scan: BatchScanExec if !needsPartitioning && !needsOrdering &&
+ scan.partitionPacking.isEmpty &&
+ options.pack(scan.inputPartitions.map(Some(_))).size < scan.inputPartitions.size =>
+ scan.withPartitionPacking(options)
+ case _: BatchScanExec => node
+ case _: ShuffleExchangeLike | _: BroadcastExchangeLike =>
+ node.withNewChildren(node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ node.requiredChildOrdering(i).nonEmpty)
+ })
+ case sort: SortExec =>
+ // Keep a scan ordering that makes this sort redundant. Otherwise the existing sort
+ // establishes ordering itself, so packing cannot add a new sort or lose its output order.
+ val redundant = SortOrder.orderingSatisfies(sort.child.outputOrdering, sort.sortOrder)
+ sort.withNewChildren(Seq(rewrite(sort.child,
+ needsPartitioning || sort.requiredChildDistribution.head != UnspecifiedDistribution,
+ redundant)))
+ case _: ProjectExec | _: FilterExec | _: BaseAggregateExec |
+ _: BroadcastHashJoinExec | _: BroadcastNestedLoopJoinExec |
+ _: V2TableWriteExec | _: DataWritingCommandExec | _: WriteFilesExec =>
+ val children = node.children.zipWithIndex.map { case (child, i) =>
+ rewrite(child,
+ needsPartitioning || node.requiredChildDistribution(i) != UnspecifiedDistribution,
+ needsOrdering || node.requiredChildOrdering(i).nonEmpty)
+ }
+ node.withNewChildren(children)
+ case _ =>
+ // Includes GroupPartitionsExec, UnionExec, windows, explicit coalesces and extensions.
+ // An exchange further down can still isolate a scan from these consumers.
+ node.mapChildren(rewrite(_, needsPartitioning = true, needsOrdering = true))
+ }
+ }
+
+ rewrite(plan, requiredDistribution.exists(_ != UnspecifiedDistribution), needsOrdering = false)
Review Comment:
Done in 3231cced and 67187986: packing is turned off for cached plans in `CacheManager` (unless `canChangeCachedPlanOutputPartitioning` is set), and checkpoints plan through `QueryExecution.forCheckpoint` with packing off. Tests added for both.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4446990151
##########
docs/sql-migration-guide.md:
##########
@@ -106,6 +106,8 @@ license: |
## Upgrading from Spark SQL 4.1 to 4.2
+- Since Spark 4.2, V2 scans no longer unconditionally group input splits sharing a reported partition key into one task (SPARK-55092). Spark still groups splits when needed to satisfy a downstream distribution, such as for a storage-partitioned join. Other scans can execute one task per split, increasing overhead for connectors with many small splits per key. Before 4.2, grouping multiple splits also discarded their reported ordering. Spark 4.4 introduces the default-off `spark.sql.sources.v2.scanPartitionPacking.enabled` option to pack eligible batch V2 scan inputs by estimated size, with an explicit count fallback when sizes are unavailable. This policy is independent of partition keys and does not restore unconditional per-key grouping. See [DataSource V2 Scan Task Sizing](sql-performance-tuning.html#datasource-v2-scan-task-sizing) for its scope and tradeoffs.
Review Comment:
Done: removed here and moved to #59970 (SPARK-60763).
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on code in PR #59522:
URL: https://github.com/apache/spark/pull/59522#discussion_r4745843574
##########
docs/sql-performance-tuning.md:
##########
@@ -694,6 +694,114 @@ You can control the details of how AQE works by providing your own cost evaluato
</tr>
</table>
+## DataSource V2 Scan Partition Packing
+
+A DataSource V2 batch scan runs one task per input partition the connector plans, and AQE cannot
+resize a scan stage, since it works from shuffle statistics. With
+`spark.sql.sources.v2.scanPartitionPacking.enabled`, Spark packs adjacent inputs of a scan into
+fewer tasks, by the sizes they report, where a shuffle reads the scan through projections, filters,
+sorts, partial aggregations or the streamed side of a broadcast hash join. It applies to keyed and
+unkeyed scans, with or without V2 bucketing. Other scans are left unchanged, for example: a scan
+that no shuffle reads, such as one that is collected, written, cached or checkpointed; a scan that a
+storage-partitioned join or an aggregation on its keys uses; a scan that reaches the shuffle through
+another operator, such as a union, a coalesce, the build side of a broadcast hash join, or an
+expand; and scans of file-based V2 sources, which `spark.sql.files.*` already sizes. Spark packs at
+the lowest point between the scan and the shuffle where no operator above relies on the scan's
+partitioning or ordering. That is directly above the scan, unless an operator relies on the order
+the scan reports, such as a sort aggregation with no sort of its own. Spark then packs above that
+operator.
Review Comment:
Fixed in 5a14c00: the summary in the tuning guide and the class doc of `PackV2ScanPartitions` now name the partitioning case, with a global sort that a keyed scan's layout satisfies as the example. The description lists it under "Where the node goes", and says that a packed task reads its inputs one after another and that merging them by the scan's ordering is out of scope.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7292614178
Thanks @peter-toth. 22 to 26 were in 5a14c00, as you found, after a rebase on master that conflicted only in the imports of `PythonDataSourceSuite`. A mutation pass over the rest also added tests for the opening cost as the floor of the first target, count ranges without integer overflow, and the largest-group metric.
Fixed in d3f0274:
- **27.** Documented it, as you suggested, in the `maxPartitionNum` doc, the `DataSourceReader.partitions` docstring and the tuning guide: with `spark.python.worker.reuse` set to false, such a task keeps a Python worker for each of its partitions until it ends. The description lists it under the user-facing changes. I kept these scans packable with reuse off: packing them already needs `maxPartitionNum`, and `coalesce()` over a Python data source scan takes the same path today.
- **28.** The three tests now pin `spark.sql.execution.replaceHashWithSortAgg`. I then ran the packing suites with other defaults. Four more tests depended on one: the storage filter test on whole-stage codegen, which the checked column needs; the global-sort test on the object hash aggregate; and the two `RemoveRedundantSorts` tests on that rule. They pin them now. With AQE or automatic broadcast joins off, and with the scheduled jobs' non-ANSI, JDK codegen, RocksDB UI and UDS settings, the suites pass as they are.
Thanks for the approval.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7195803224
Thanks @ulysses-you. Actions had been disabled on my fork; it's enabled again, and 7ac900f is building. Addressed in 7ac900f:
- The local-read test: the SPARK-59671 query test stays for its answer, with the comment corrected, and a new test, "a local read over a packed shuffle reports no keyed layout", packs a grouped keyed scan into two mappers read through two reducers, so the local read reads one mapper per task. It fails if `PackScanPartitionsExec` passes the scan's layout up: AQE then keeps a local read over the keyed side.
- New tests for `spark_partition_id()` below the node, where it sees the input's partition while a UDF reading `TaskContext.partitionId()` sees the packed task's; for the node above a broadcast hash join whose streamed side's ordering a sort aggregate above it reads; and for the node above a global sort that a keyed scan's layout satisfies. That sort survives only with `spark.sql.execution.removeRedundantSorts` off, since the grouped scan reports the key ordering too.
- `V2ScanPartitionPacking` now has the four `require` guards.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
Re: [PR] [SPARK-60265][SQL] Add optional size-based packing for V2 batch scans [spark]
Posted by "rekbun (via GitHub) via reviews" <re...@spark.apache.org>.
rekbun commented on PR #59522:
URL: https://github.com/apache/spark/pull/59522#issuecomment-7195790647
Thanks @peter-toth. Fixed in 1879923:
- **19.** The second pass keeps the first target as a floor: `math.max(target, ceilDiv(total, cap))`. Your example is now a unit case: 20 tasks without a cap and for caps 17 to 19, and 15 for a cap of 15. The parity test's comment and the docs say that files don't keep this floor. The files side can follow in its own ticket, as you suggested.
- **20.** The `maxPartitionNum` doc and the DSv2 guide now say that partitions that runtime filtering emptied still join a neighboring task.
- **21.** Dropped the sentence from the tuning guide. The code comments and the PR description still cover the pipelined shuffle.
--
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: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org