rekbun commented on code in PR #60256:
URL: https://github.com/apache/spark/pull/60256#discussion_r4603461405


##########
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:
   Done in 114d73e0790, as you proposed: a group names a host only when one is 
strictly ahead, and the `assigned` map is gone. The first test now expects no 
location for the tied groups, and checks that the scheduler then offers the 
first input's locations, as in your second row.
   



##########
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:
   Done in 114d73e0790. The persisted test now coalesces both the cached RDD 
itself and `cached.map(identity).map(identity)`, so it fails if the check drops 
the parent or walks only one level.
   



-- 
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