peter-toth commented on code in PR #60256:
URL: https://github.com/apache/spark/pull/60256#discussion_r4601357422
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,37 +867,73 @@ 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. A group of several partitions
prefers the host that
+ * most of them prefer. A group of one partition, and every group over
persisted data, leaves its
+ * location to the scheduler.
*
* @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")
+ // The scheduler looks cached blocks up when it submits each stage, while
the groups get their
+ // locations once, when the partitions are computed. So over persisted
data the groups leave
+ // their locations to the scheduler.
+ val voting = !GroupedPartitionCoalescer.persistedLineage(parent)
+ val assigned = mutable.Map.empty[String, Int].withDefaultValue(0)
+ // Groups can share partitions, as the slots of a key under
`REPLICATED_FOR_JOIN` do, so each
+ // partition's locations are looked up once.
+ val locationsOf = mutable.HashMap.empty[Int, Seq[TaskLocation]]
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)
+ 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, and spreads ties across groups rather than sending
them all to one
+ // host. As in `DefaultPartitionCoalescer`, a partition's locations 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 = if (!voting || partitionIndices.size == 1) None
else {
+ val locations = partitionIndices.map(i =>
+ locationsOf.getOrElseUpdate(i,
parent.context.getPreferredLocs(parent, i)))
+ val host = locations.flatMap(_.map(_.host).distinct)
+ .groupBy(identity).view.mapValues(_.size)
+ .minByOption { case (h, count) => (-count, assigned(h), h) }
Review Comment:
**Finding 8.** When no host is ahead, the vote still names one, and that
only narrows what master offered. Over a scan master named no host for a group,
so the scheduler offered the first input's locations. Here a tie picks one host
by `assigned`, then by name.
What I ran: `sc.getPreferredLocs` on the coalesced RDD over
`source.map(identity)`, with master's coalescer and at this head:
| group of two inputs | master | this head |
|---|---|---|
| both on h1, h2, h3 | h1, h2, h3 | h1 |
| one on a, b, c, one on d, e, f | a, b, c | a |
The named host holds no more of the group than each host master offered. So
when it is busy, the task waits out `spark.locality.wait`, where master could
take a free replica. I read that wait from `TaskSetManager` and did not measure
it, since local mode has one host.
The second row is the common one. In a simulation of this vote with 100
hosts and 3 random replicas per input, about 91% of two-input groups have every
host on a single input. The tie-break by name also starts again in every
coalescer, so the first tied groups of each RDD go to the lowest-sorting hosts.
With 20 two-input groups per RDD, about 32% of the preferences land on the
first tenth of the hosts and under 1% on the last tenth. On master it is 10%
each.
Naming a host only when one is strictly ahead gives master's offer back for
every tie, and it needs no `assigned` map:
```scala
val counts =
locations.flatMap(_.map(_.host).distinct).groupBy(identity).view
.mapValues(_.size).toSeq
val top = counts.map(_._2).maxOption
val host = counts.collect { case (h, c) if top.contains(c) => h }
match {
case Seq(h) => Some(h)
case _ => None
}
```
With it, both rows give master's result, and a group with a host ahead still
gets that host. In a partially clustered join whose replicated inputs tie, the
zipped task gets master's locations again. `GroupPartitionsExecSuite` passes 44
of 44 once two expectations that pin tie-spreading expect no location: the tied
groups in the first new test, and h1, h2, h1 in the lookup test.
This undoes the tie-spreading I kept in finding 5's suggestion. Finding 7
would offer every tied host instead.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,37 +867,73 @@ 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. A group of several partitions
prefers the host that
+ * most of them prefer. A group of one partition, and every group over
persisted data, leaves its
+ * location to the scheduler.
*
* @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")
+ // The scheduler looks cached blocks up when it submits each stage, while
the groups get their
+ // locations once, when the partitions are computed. So over persisted
data the groups leave
+ // their locations to the scheduler.
+ val voting = !GroupedPartitionCoalescer.persistedLineage(parent)
+ val assigned = mutable.Map.empty[String, Int].withDefaultValue(0)
+ // Groups can share partitions, as the slots of a key under
`REPLICATED_FOR_JOIN` do, so each
+ // partition's locations are looked up once.
+ val locationsOf = mutable.HashMap.empty[Int, Seq[TaskLocation]]
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)
+ 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, and spreads ties across groups rather than sending
them all to one
+ // host. As in `DefaultPartitionCoalescer`, a partition's locations 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 = if (!voting || partitionIndices.size == 1) None
else {
+ val locations = partitionIndices.map(i =>
+ locationsOf.getOrElseUpdate(i,
parent.context.getPreferredLocs(parent, i)))
+ 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
+ }
+ }
}
- // Select the most common location as the preferred location
- val preferredLocation = preferredLocations
- .groupBy(identity)
- .view.mapValues(_.size)
- .maxByOption(_._2)
- .map(_._1)
val partitionGroup = new PartitionGroup(preferredLocation)
partitionGroup.partitions ++= partitions
partitionGroup
}.toArray
}
}
+private object GroupedPartitionCoalescer {
Review Comment:
**Finding 11.** `RDD.getNarrowAncestors` (`RDD.scala:347`, `private[spark]`)
already walks the narrow lineage, so this object and the `NarrowDependency`
import can go. A `lazy val` also skips the walk when every group has one
partition, as on the split side under `SPLIT_FOR_JOIN`:
```scala
lazy val voting =
!(parent +: parent.getNarrowAncestors).exists(_.getStorageLevel !=
StorageLevel.NONE)
```
with `if (partitionIndices.size == 1 || !voting)` below.
`GroupPartitionsExecSuite` passes 44 of 44 with it, finding 9's change included.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala:
##########
@@ -863,37 +867,73 @@ 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. A group of several partitions
prefers the host that
+ * most of them prefer. A group of one partition, and every group over
persisted data, leaves its
+ * location to the scheduler.
*
* @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")
+ // The scheduler looks cached blocks up when it submits each stage, while
the groups get their
+ // locations once, when the partitions are computed. So over persisted
data the groups leave
+ // their locations to the scheduler.
+ val voting = !GroupedPartitionCoalescer.persistedLineage(parent)
Review Comment:
**Finding 10.** Over persisted data the groups leave their location to the
scheduler. In a storage-partitioned join, though, the scheduler gets no choice
when the other side votes. `ZippedPartitionsBaseRDD` copies each side's own
location when it computes its partitions (`ZippedPartitionsRDD.scala:61-64`).
So the voted host becomes the zipped task's only location, and the scheduler
never walks to the cached block.
What I ran: a cached side and a scan side, each with two groups of two
inputs. The scan side's groups sit on s0 and s1. Then `sc.getPreferredLocs` on
the zipped RDD, with master's coalescer and at this head:
| | master | this head |
|---|---|---|
| cached side left | `executor_<driver>`, the cached block, for each task |
s0; s1 |
| cached side right | s0; s1 | s0; s1 |
With the cached side on the left, the tasks move from the executor that
holds the block to the scan's host, and read the block remotely. Finding 8
makes this rarer, since the other side then names a host only when one is
strictly ahead. Finding 7 would not change it, since the zip copies the
locations either way.
I raised the group-of-one version of this in finding 5 and judged it the
smaller cost, and I still think so. But the description's list of cases where
"the scheduler finds the locations itself" should say that it does not in a
join whose other side names a host. A cached side in the zip test could pin it.
##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala:
##########
@@ -942,6 +945,115 @@ class GroupPartitionsExecSuite extends SharedSparkSession
{
assert(diverged.withKeyPositionsFor(swapped).isEmpty,
"there is nothing to move the positions into once the child reports
another partitioning")
}
+
+ test("SPARK-61279: the grouped coalescer prefers majority hosts and spreads
ties") {
+ val parent = spark.sparkContext.makeRDD((0 until 6).map(i => (i,
Seq("host-a", "host-b"))))
+ val coalescer = new GroupedPartitionCoalescer(Seq(Seq(0, 1), Seq(2),
Seq(3, 4), Seq(5)))
+ // Groups whose partitions all prefer both hosts alternate between them. A
group of one names
+ // no location: the scheduler offers every location of its partition.
+ assert(coalescer.coalesce(4, parent).map(_.prefLoc).toSeq ===
+ Seq(Some("host-a"), None, Some("host-b"), None))
+ // A caller sizes the coalesced RDD by the groups, so another count is a
bug.
+ intercept[IllegalArgumentException](coalescer.coalesce(3, parent))
+ // A host that the largest number of a group's partitions prefer wins over
balancing.
+ val majority = spark.sparkContext.makeRDD((0 until 5).map { i =>
+ (i, Seq(if (i < 4) "host-a" else "host-b"))
+ })
+ assert(new GroupedPartitionCoalescer(Seq(Seq(0, 1), Seq(2, 3,
4))).coalesce(2, majority)
+ .map(_.prefLoc).toSeq === Seq(Some("host-a"), Some("host-a")))
+ // A partition counts once for each host it prefers, however often it
lists that host.
+ val repeated = spark.sparkContext.makeRDD(Seq(
+ (0, Seq("host-a", "host-a", "host-a")), (1, Seq("host-b")), (2,
Seq("host-b"))))
+ assert(new GroupedPartitionCoalescer(Seq(Seq(0, 1, 2))).coalesce(1,
repeated)
+ .map(_.prefLoc).toSeq === Seq(Some("host-b")))
+ // A null host is not a location, as for the scheduler.
+ val withNull =
+ spark.sparkContext.makeRDD(Seq((0, Seq(null, "host-a")), (1, Seq(null,
"host-a"))))
+ assert(new GroupedPartitionCoalescer(Seq(Seq(0, 1))).coalesce(1, withNull)
+ .map(_.prefLoc).toSeq === Seq(Some("host-a")))
+ // Only the driver reads the groups, so tasks do not carry them.
+ val serializer = new JavaSerializer(new SparkConf()).newInstance()
+ val copy =
serializer.deserialize[GroupedPartitionCoalescer](serializer.serialize(coalescer))
+ assert(copy.groupedPartitions == null)
+ }
+
+ test("SPARK-61279: groups over a mapped parent prefer the hosts of its
lineage") {
+ // As over a scan: `GroupPartitionsExec` coalesces the scan's mapped RDD,
which reports no
+ // locations of its own, so the vote reads the hosts the scheduler finds
through the lineage.
+ val source = spark.sparkContext.makeRDD(Seq(
+ (0, Seq("h2")), (1, Seq("h1")), (2, Seq("h1")), (3, Seq("h3"))))
+ val mapped = source.map(identity)
+ val coalesced = mapped.coalesce(2, shuffle = false,
+ Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1, 2), Seq(3)))))
+ assert(coalesced.partitions.map(coalesced.preferredLocations).toSeq ===
Seq(Seq("h1"), Nil))
+ // The group of one leaves its location to the scheduler, which finds it
through the lineage.
+ assert(spark.sparkContext.getPreferredLocs(coalesced, 1).map(_.host) ===
Seq("h3"))
+ // With no host anywhere in the lineage, a group names none, as before.
+ val unplaced = spark.sparkContext.makeRDD(0 until 4,
4).map(identity).coalesce(2,
+ shuffle = false, Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1),
Seq(2, 3)))))
+
assert(unplaced.partitions.map(unplaced.preferredLocations).forall(_.isEmpty))
+ }
+
+ test("SPARK-61279: a zipped group of one leaves its location to the other
side") {
+ // A group of one names no location, so the scheduler offers all of its
input's locations. A
+ // zip reads each side's own location, though, so a zipped task gets only
the other side's.
+ val single = spark.sparkContext.makeRDD(Seq((0, Seq("h1", "h2"))))
+ .coalesce(1, shuffle = false, Some(new
GroupedPartitionCoalescer(Seq(Seq(0)))))
+ val pair = spark.sparkContext.makeRDD(Seq((0, Seq("h3")), (1, Seq("h3"))))
+ .coalesce(1, shuffle = false, Some(new
GroupedPartitionCoalescer(Seq(Seq(0, 1)))))
+ assert(spark.sparkContext.getPreferredLocs(single, 0).map(_.host).toSet
=== Set("h1", "h2"))
+ val zipped = single.zipPartitions(pair)((left, right) => left ++ right)
+ assert(zipped.preferredLocations(zipped.partitions.head) === Seq("h3"))
+ }
+
+ test("SPARK-61279: groups over persisted data leave their locations to the
scheduler") {
+ // As a `GroupPartitionsExec` right over an `InMemoryTableScanExec`. A job
computes the groups
+ // when it is submitted, before the scheduler looks the cached blocks up,
so a host fixed then
+ // would be the source's rather than the executor's that holds the block.
+ val sc = spark.sparkContext
+ val cached = sc.makeRDD(Seq((0, Seq("h1")), (1,
Seq("h1")))).map(identity).cache()
+ try {
+ val coalesced = cached.coalesce(1, shuffle = false,
Review Comment:
**Finding 9.** This test's parent is the cached RDD itself. So
`persistedLineage` returns at its first check, and its walk over narrow
dependencies never runs. Over an `InMemoryTableScanExec`, which the comment
above names, the cached RDD sits under the scan's `mapPartitionsInternal`, and
only the walk keeps the vote off.
What I ran: with the walk disabled (`r.dependencies.exists` short-circuited
to `false`), all six new tests still pass. With the change below, this test
passes at this head and fails with the walk disabled, with
`ArraySeq(Some("h1")) did not equal List(None)`. Its later assertion still
holds, since the scheduler walks through the map to the cached block.
```suggestion
val coalesced = cached.map(identity).coalesce(1, shuffle = false,
```
--
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]