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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to