peter-toth commented on code in PR #60256:
URL: https://github.com/apache/spark/pull/60256#discussion_r4587345605
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,30 +865,33 @@ 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. Each group prefers the host
that most of its
+ * partitions prefer.
*
* @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(
- val groupedPartitions: Seq[Seq[Int]]
+ @transient val groupedPartitions: Seq[Seq[Int]]
) extends PartitionCoalescer with Serializable {
override def coalesce(maxPartitions: Int, parent: RDD[_]):
Array[PartitionGroup] = {
+ require(groupedPartitions.size == maxPartitions,
s"GroupedPartitionCoalescer has " +
+ s"${groupedPartitions.size} groups but was asked for $maxPartitions
partitions")
+ val assigned = mutable.Map.empty[String, Int].withDefaultValue(0)
groupedPartitions.map { partitionIndices =>
- val partitions = new ArrayBuffer[Partition](partitionIndices.size)
- val preferredLocations = new ArrayBuffer[String](partitionIndices.size)
- partitionIndices.foreach { partitionIndex =>
- val partition = parent.partitions(partitionIndex)
- partitions += partition
- preferredLocations ++= parent.preferredLocations(partition)
- }
- // Select the most common location as the preferred location
- val preferredLocation = preferredLocations
- .groupBy(identity)
- .view.mapValues(_.size)
- .maxByOption(_._2)
+ val partitions = partitionIndices.map(parent.partitions(_))
+ // Prefer the host that the largest number of the group's partitions
prefer, and spread ties
+ // across groups rather than sending them all to one host. As in
`DefaultPartitionCoalescer`,
+ // a partition's hosts are the ones the scheduler would use for it,
found through the
+ // parent's lineage, since a parent such as a scan's mapped RDD reports
none of its own.
+ val preferredLocation = partitionIndices
+ .flatMap(parent.context.getPreferredLocs(parent,
_).map(_.host).distinct)
Review Comment:
**Finding 6.** `getPreferredLocs` walks the lineage once per (group, input)
entry, and each walk calls the connector's `preferredLocations()` again. Under
`REPLICATED_FOR_JOIN` every slot of a key has the same inputs, so the same
walks repeat once per slot. A map per input index removes the repeats:
```scala
val locationsOf = mutable.HashMap.empty[Int, Seq[TaskLocation]]
```
and in the vote:
```scala
val locations = partitionIndices.map(i =>
locationsOf.getOrElseUpdate(i,
parent.context.getPreferredLocs(parent, i)))
```
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,30 +865,33 @@ 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. Each group prefers the host
that most of its
+ * partitions prefer.
*
* @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(
- val groupedPartitions: Seq[Seq[Int]]
+ @transient val groupedPartitions: Seq[Seq[Int]]
) extends PartitionCoalescer with Serializable {
override def coalesce(maxPartitions: Int, parent: RDD[_]):
Array[PartitionGroup] = {
+ require(groupedPartitions.size == maxPartitions,
s"GroupedPartitionCoalescer has " +
+ s"${groupedPartitions.size} groups but was asked for $maxPartitions
partitions")
+ val assigned = mutable.Map.empty[String, Int].withDefaultValue(0)
groupedPartitions.map { partitionIndices =>
- val partitions = new ArrayBuffer[Partition](partitionIndices.size)
- val preferredLocations = new ArrayBuffer[String](partitionIndices.size)
- partitionIndices.foreach { partitionIndex =>
- val partition = parent.partitions(partitionIndex)
- partitions += partition
- preferredLocations ++= parent.preferredLocations(partition)
- }
- // Select the most common location as the preferred location
- val preferredLocation = preferredLocations
- .groupBy(identity)
- .view.mapValues(_.size)
- .maxByOption(_._2)
+ val partitions = partitionIndices.map(parent.partitions(_))
+ // Prefer the host that the largest number of the group's partitions
prefer, and spread ties
+ // across groups rather than sending them all to one host. As in
`DefaultPartitionCoalescer`,
+ // a partition's hosts are the ones the scheduler would use for it,
found through the
+ // parent's lineage, since a parent such as a scan's mapped RDD reports
none of its own.
+ val preferredLocation = partitionIndices
Review Comment:
**Finding 5.** A group now fixes one host when `getPartitions` runs, and the
scheduler stops there. Over a mapped parent master named none, so the scheduler
resolved the inputs' locations itself at each stage submission.
I ran each case with `sc.getPreferredLocs` on the coalesced RDD, in local
mode, at this head and with master's coalescer:
| case | master | this head |
|---|---|---|
| a cached parent: `cache()`, `count()`, then a job on the grouped RDD |
`executor_<driver>` (the cached block) | `h1` (the source's host) |
| the grouped partitions computed before the cache exists, then two jobs |
`executor_<driver>` | `h1` |
| a group of one over `executor_h9_7`, and one over `hdfs_cache_h8` |
`executor_h9_7`, `hdfs_cache_h8` | `h9`, `h8` |
| groups of one, each input on h1, h2, h3 | h1, h2, h3 for each | h1; h2; h3
|
- The first two rows come from timing. `coalesce` runs on the submitting
thread, in `DAGScheduler.submitJob`'s `rdd.partitions`, before
`handleJobSubmitted` clears the scheduler's cache-location map.
`SparkPlan.executeRDD` also keeps the RDD across actions. So the vote reads the
map from before the block existed and falls through to the source. A
`GroupPartitionsExec` can sit right over an `InMemoryTableScanExec`, which
keeps the cached plan's partitioning.
- The third row comes from `.map(_.host)`. With only a host, a task is
`NODE_LOCAL` at best, and with several executors on a host it can miss the one
that holds the block.
- The fourth row narrows a group of one from all of its input's replicas to
one. Under `SPLIT_FOR_JOIN` every split is a group of one. When that host is
busy, the task waits out `spark.locality.wait`.
All of them come from what I asked for in round 1. Master's result comes
back if the coalescer leaves to the scheduler what only it decides well:
```scala
// The scheduler looks cached blocks up per stage, so over persisted
data the groups leave
// their locations to it.
val voting = !GroupedPartitionCoalescer.persistedLineage(parent)
val assigned = mutable.Map.empty[String, Int].withDefaultValue(0)
groupedPartitions.map { partitionIndices =>
val partitions = partitionIndices.map(parent.partitions(_))
// A group of one leaves its location to the scheduler too, which then
offers every location
// of its partition. A larger group prefers the host that the largest
number of its
// partitions prefer, found through the parent's lineage, and spreads
ties across groups.
val preferredLocation = if (!voting || partitionIndices.size == 1)
None else {
val locations =
partitionIndices.map(parent.context.getPreferredLocs(parent, _))
val host = locations.flatMap(_.map(_.host).distinct)
.groupBy(identity).view.mapValues(_.size)
.minByOption { case (h, count) => (-count, assigned(h), h) }
.map(_._1)
host.foreach(h => assigned(h) += 1)
// An executor or HDFS-cache location is kept when every input on
the host names it.
host.map { h =>
locations.flatten.filter(_.host == h).map(_.toString).distinct
match {
case Seq(location) => location
case _ => h
}
}
}
```
and, next to the class:
```scala
private object GroupedPartitionCoalescer {
/** Whether `rdd`, or an RDD its narrow dependencies reach, is persisted.
*/
def persistedLineage(rdd: RDD[_]): Boolean =
rdd.getStorageLevel != StorageLevel.NONE || rdd.dependencies.exists {
case n: NarrowDependency[_] => persistedLineage(n.rdd)
case _ => false
}
}
```
With it all four rows give master's result. A group of two on
`executor_h9_7` keeps that location, and one with an `executor_h9_7` and an
`h9` input gets `h9`. A larger group still gets a majority host, which
`PackScanPartitionsExec` in #59522 needs. The other 38 tests in
`GroupPartitionsExecSuite` pass. The three new tests fail only where they pin a
host for a group of one. They would check `sc.getPreferredLocs` there instead,
and expect all of the input's hosts.
The cost is the case [finding
2](https://github.com/apache/spark/pull/60256#discussion_r4538351696) was
about: in a zip, a group of one drops out of the locations when the other
side's group names a host. I think that is the smaller cost. Finding 7 avoids
it.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,30 +865,33 @@ 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. Each group prefers the host
that most of its
+ * partitions prefer.
*
* @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(
- val groupedPartitions: Seq[Seq[Int]]
+ @transient val groupedPartitions: Seq[Seq[Int]]
) extends PartitionCoalescer with Serializable {
override def coalesce(maxPartitions: Int, parent: RDD[_]):
Array[PartitionGroup] = {
Review Comment:
**Finding 7.** Finding 5's rows share one cause: the vote fixes a single
host when the partitions are computed. A vote that runs when the scheduler asks
avoids that. `GroupPartitionsExec` and `PackScanPartitionsExec` would build a
small `CoalescedRDD` subclass, and `getPreferredLocations` would run the vote
over `context.getPreferredLocs` for the group's inputs and return every
location on the top host or hosts:
```scala
private[sql] class GroupedCoalescedRDD[T: ClassTag](
parent: RDD[T], numGroups: Int, coalescer: PartitionCoalescer)
extends CoalescedRDD[T](parent, numGroups, Some(coalescer)) {
override def getPreferredLocations(partition: Partition): Seq[String] = {
val inputs =
partition.asInstanceOf[CoalescedRDDPartition].parentsIndices.toSeq
val locations = inputs.map(context.getPreferredLocs(firstParent[T], _))
val counts =
locations.flatMap(_.map(_.host).distinct).groupBy(identity).view.mapValues(_.size)
if (counts.isEmpty) Nil else {
val top = counts.values.max
val hosts = counts.filter(_._2 == top).keySet
locations.flatten.filter(l =>
hosts.contains(l.host)).map(_.toString).distinct
}
}
}
```
- The coalescer would then only group, with no vote and no `assigned` map.
- Ties would need no spreading, since the scheduler sees every tied host and
picks one with a free slot.
- A group of one would get all of its input's locations, and a zip of a
group on h1, h2 with one on h1, h3 would get h1, the intersection.
The costs:
- `SortedMergeCoalescedRDD` needs the same override.
- The vote runs at every stage submission, not once.
- A zip still copies its sides' locations when it computes its own
partitions, so a zip over a just-cached side can still read the old map.
--
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]