From 95b01904d1d34c87a93ca3e85329c7349bc0e62b Mon Sep 17 00:00:00 2001 From: Rakesh <885717+rekbun@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:01:40 +0100 Subject: [PATCH] [SPARK-61279][SQL] Keep GroupedPartitionCoalescer's groups out of tasks and improve its location choice This PR changes `GroupedPartitionCoalescer`, which `GroupPartitionsExec` uses to coalesce partitions for storage-partitioned operations: - It marks its groups `transient`. `CoalescedRDD`, and `SortedMergeCoalescedRDD` for a k-way merge, keep the coalescer, so its groups were serialized into every task binary, although only `getPartitions` on the driver reads them. - It checks, with a message, that it is asked for as many partitions as it has groups, since a caller sizes the coalesced RDD by its groups. - A group of several partitions prefers a host only when more of its partitions prefer it than any other host. It finds each partition's locations through the parent's lineage with `SparkContext.getPreferredLocs`, as `DefaultPartitionCoalescer` does. Before, it read only the parent's own `preferredLocations` and took the most common entry, the first in a hash map's order on a tie. Over a scan, `GroupPartitionsExec` coalesces the scan's mapped RDD, which reports no locations of its own, so no group named one. - A partition counts once for each host, however often and in whatever form it names that host, and a null host is ignored. - When the only location that the group's partitions name on the chosen host is an executor or an HDFS cache, the group keeps that location instead of the host. - Other groups name no location: a group of one partition, a group with no host ahead, a group that shares partitions with another group, as the slots of a key do under `REPLICATED_FOR_JOIN`, and any group when the parent, or an RDD that its narrow dependencies reach, is persisted. The scheduler then finds the locations itself when it submits each stage, as it did on master over a scan. It offers every location of a group of one's partition, the locations of a group's first partition that has any, and the executor that holds a cached block. Large groupings no longer add to the task binary of every task. Groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer that host. Before, they named none, and the scheduler offered the locations of the group's first input that had any. A group gets one location, once, when the coalesced RDD's partitions are computed, while the scheduler looks cached blocks up at each stage submission and can offer several locations. So the coalescer leaves the choice to the scheduler where its one location would be worse: - over persisted data, where only the scheduler sees the cached blocks; - for a group of one, where the scheduler offers every location of its partition; - where no host is ahead, since naming one tied host would mostly narrow the scheduler's offer of the first input's locations; - for groups that share partitions, since a zip would copy their one host into every task of the key in a partially clustered join. Left to the scheduler, each task gets master's locations: its own split's when the split side comes first in the zip, and every location of the first replicated input otherwise. SPARK-60265 (#59522) reuses this coalescer for V2 scan partition packing. There is no API change. Storage-partitioned groups of several partitions over a scan, where more of the inputs prefer one host than any other, now prefer one location: that host, or the only location that the group's inputs name on it, such as an executor. Before, no group named a location. Over a parent that reports locations of its own, a group named its partitions' most common location before, and it now follows the same rules. As with `DefaultPartitionCoalescer`, a group gets its location when the coalesced RDD's partitions are computed, and the partitions of a group that votes have their locations looked up once more for that. Otherwise the scheduler finds the locations itself, as on master over a scan: - for a group of one partition; - for a group with no host ahead; - for groups that share partitions, as the slots of a key do in a partially clustered join; - for groups whose parent's narrow lineage is persisted, such as a `GroupPartitionsExec` over an `InMemoryTableScanExec`; - where no input reports a location, as with the in-memory test connectors. The exception is a join that zips the grouped RDDs directly: a row-based `GroupPartitionsExec` right under a shuffled hash join, or under a sort-merge join that needs no sort. `ZippedPartitionsRDD` copies each side's own location when it computes its partitions. So when one side's group names a location, the other side adds none if its group names none, as a group of one, a group with no host ahead or a group over cached data does, and the task prefers that one location. Over cached data, the task then reads the block remotely. On master over a scan, such a task got the locations of the first input that had any on the zip's first side (the streamed side under whole-stage codegen), or the executor that holds that side's cached block. Where a `ColumnarToRowExec` or a `SortExec` sits between the grouping and the join, as over a vectorized scan, the zip has no locations of its own, and the scheduler finds them as on master. A host that holds a replica of every input also narrows the offer. That happens when a single writer on a datanode loaded the table, since HDFS puts the first replica of each block on the writer's node. The host is then ahead in every group of several partitions, so each of those groups names it alone and their tasks all prefer it. The tasks that do not fit there wait for the locality timeout and then read remotely, where on master they could start node-local to their first input on another replica. A weak plurality narrows a single group the same way: with ten inputs where one host holds two and every other host one, the group names that host, where master offered its first input's replicas. Returning several locations for a group, such as the leading host plus the first input's replicas, would remove this; that is left for the follow-up on an alternative design. Six tests in `GroupPartitionsExecSuite`: - A group names no location when no host is ahead, and the scheduler then offers its first input's locations. A group of one names none either. It also covers the partition-count check in both directions, a host ahead with and without a majority, a host counted once per partition however it is named, null hosts, and that tasks do not carry the groups. - Groups over a mapped parent, as over a scan, prefer the hosts found through its lineage. The scheduler finds a group of one's location through the lineage, and a group names none when nothing in the lineage has a host. - In a zip, a side over a map, as over a scan, whose group names a host decides the task's location, both against a group of one and against a group over cached data, for which the scheduler alone would offer the executor that holds the block. - Groups over a persisted parent, and over one two maps down, as over an `InMemoryTableScanExec`, name no location, so once the data is cached the scheduler offers the executor that holds the block. - A group of several partitions keeps an executor or HDFS-cache location that is the only one its inputs name on the host, also next to an input on another host, and gets the host otherwise. For groups of one, the scheduler offers an executor location, an HDFS-cache location, and all three hosts of a replicated input. - Groups that share partitions, as the slots of a split key in a partially clustered join, name no location and look none up, while an unshared group next to them still votes, looking each input up once. Zipped with the split side's groups of one, the tasks get master's locations in both zip orders: their own split's when the split side comes first, and every location of the first replicated input otherwise. Locally, with JDK 21: - `GroupPartitionsExecSuite`, `KeyGroupedPartitioningSuite` and its three runtime-filter variants, `EnsureRequirementsSuite`, the six `DynamicPartitionPruningV2*` suites and the `DataSourceV2FileSourceDPPSuite` variants: 711 tests in 14 suites passed (9 ignored when AQE is on, as on master). - SQL scalastyle (main and test) and `sql/mimaReportBinaryIssues` passed. ```bash build/sbt \ 'sql/testOnly org.apache.spark.sql.execution.datasources.v2.GroupPartitionsExecSuite org.apache.spark.sql.connector.KeyGroupedPartitioning* org.apache.spark.sql.execution.exchange.EnsureRequirementsSuite org.apache.spark.sql.DynamicPartitionPruningV2* org.apache.spark.sql.connector.DataSourceV2FileSourceDPPSuite*' \ 'sql/scalastyle' 'sql/Test/scalastyle' 'sql/mimaReportBinaryIssues' ``` Generated-by: Claude Code (Claude Opus 5.5) Closes #60256 from rekbun/SPARK-61279. Authored-by: Rakesh Signed-off-by: Peter Toth skip-checks: true --- .../datasources/v2/GroupPartitionsExec.scala | 79 ++++++-- .../v2/GroupPartitionsExecSuite.scala | 183 +++++++++++++++++- 2 files changed, 240 insertions(+), 22 deletions(-) diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala index b9f91984f666f..5159516fdad4e 100644 --- a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala +++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExec.scala @@ -20,7 +20,7 @@ package org.apache.spark.sql.execution.datasources.v2 import scala.collection.mutable.ArrayBuffer -import org.apache.spark.{Partition, SparkException} +import org.apache.spark.SparkException import org.apache.spark.rdd.{CoalescedRDD, PartitionCoalescer, PartitionGroup, RDD, SortedMergeCoalescedRDD} import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions._ @@ -30,6 +30,7 @@ import org.apache.spark.sql.catalyst.util.{truncatedString, InternalRowComparabl import org.apache.spark.sql.execution.{SafeForKWayMerge, SparkPlan, SQLExecution, UnaryExecNode} import org.apache.spark.sql.execution.metric.{SQLMetric, SQLMetrics} import org.apache.spark.sql.vectorized.ColumnarBatch +import org.apache.spark.storage.StorageLevel /** * Physical operator that groups input partitions by their partition keys. @@ -39,9 +40,10 @@ import org.apache.spark.sql.vectorized.ColumnarBatch * storage-partitioned joins to align partitions from different sides of the join. * * Everything that says how the node was decided is `@transient`, since only the driver plans and - * the executors read the groups through [[GroupedPartitionCoalescer]] rather than through this - * node. The two partitionings are not, matching `ShuffleExchangeExec`'s, since they are what the - * node claims rather than how it arrived at the claim. + * groups the partitions, through [[GroupedPartitionCoalescer]], and the executors read the + * coalesced partitions rather than this node. The two partitionings are not, matching + * `ShuffleExchangeExec`'s, since they are what the node claims rather than how it arrived at the + * claim. * * @param child The child plan providing bucketed/partitioned input * @param grouping What this node does to the child's partitions, derived once at planning time by @@ -865,35 +867,70 @@ 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. When nothing in the parent's narrow lineage is + * persisted, a group names a location if it has several partitions, shares none of them with + * another group, and more of its partitions prefer one host than any other host. Every other + * group 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") + // Groups that share partitions, as the slots of a key under `REPLICATED_FOR_JOIN` do, would all + // name the same host when one is ahead, and a zip copies it into every task of the key. Left to + // the scheduler, each task gets the locations of the zip's first side that has any, as on + // master: its own split's when the split side comes first. + lazy val shared = + groupedPartitions.flatten.groupMapReduce(identity)(_ => 1)(_ + _).filter(_._2 > 1).keySet + // The scheduler looks cached blocks up when it submits each stage, while a group gets its + // location once, when the partitions are computed. + lazy val persisted = + (parent +: parent.getNarrowAncestors).exists(_.getStorageLevel != StorageLevel.NONE) 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) - .map(_._1) - val partitionGroup = new PartitionGroup(preferredLocation) + // Read the partitions before the vote: otherwise the scheduler would compute them while it + // holds its cache-location map, against the lock order that `DAGScheduler` documents. + val partitions = partitionIndices.map(parent.partitions(_)) + // A group of one leaves its location to the scheduler, which then offers every location of + // its partition. The checks above run only for groups of several partitions. + val votes = partitionIndices.size > 1 && !partitionIndices.exists(shared) && !persisted + val partitionGroup = + new PartitionGroup(if (votes) preferredLocation(parent, partitionIndices) else None) partitionGroup.partitions ++= partitions partitionGroup }.toArray } + + /** + * The host that more of the given partitions prefer than any other host, or the only location + * that they name on it, such as an executor. With no host ahead it is None, and the scheduler + * offers the locations of the first partition that has any. Naming a tied host would mostly + * narrow that offer, though in a group of three or more that partition can miss them. 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. + */ + private def preferredLocation(parent: RDD[_], partitionIndices: Seq[Int]): Option[String] = { + val locations = partitionIndices.map(parent.context.getPreferredLocs(parent, _)) + // A partition counts once for each host, however it names the host. + val counts = locations.flatMap(_.map(_.host).distinct).groupBy(identity).view + .mapValues(_.size).toSeq + val top = counts.map(_._2).maxOption + counts.collect { case (host, count) if top.contains(count) => host } match { + case Seq(host) => + locations.flatten.filter(_.host == host).map(_.toString).distinct match { + case Seq(location) => Some(location) + case _ => Some(host) + } + case _ => None + } + } } /** diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala index ba878f44b8e1b..0cc7bc39ac8cc 100644 --- a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala +++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/GroupPartitionsExecSuite.scala @@ -17,8 +17,11 @@ package org.apache.spark.sql.execution.datasources.v2 -import org.apache.spark.{SparkConf, SparkContext, SparkException} +import java.util.concurrent.atomic.AtomicInteger + +import org.apache.spark.{Partition, SparkConf, SparkContext, SparkException, TaskContext} import org.apache.spark.rdd.RDD +import org.apache.spark.scheduler.ExecutorCacheTaskLocation import org.apache.spark.serializer.JavaSerializer import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{Ascending, Attribute, AttributeReference, CodegenObjectFactoryMode, SortOrder, TransformExpression} @@ -944,6 +947,171 @@ 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 a host only when one is ahead") { + val sc = spark.sparkContext + val parent = sc.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))) + // With no host ahead, a group names no location, and neither does a group of one. + assert(coalescer.coalesce(4, parent).map(_.prefLoc).toSeq === Seq(None, None, None, None)) + // The scheduler then offers the locations of the group's first partition that has any. + val disjoint = sc.makeRDD(Seq((0, Seq("a", "b", "c")), (1, Seq("d", "e", "f")))).map(identity) + .coalesce(1, shuffle = false, Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1))))) + assert(disjoint.partitions.map(disjoint.preferredLocations).toSeq === Seq(Nil)) + assert(sc.getPreferredLocs(disjoint, 0).map(_.host).sorted === Seq("a", "b", "c")) + // A caller sizes the coalesced RDD by the groups, so another count is a bug. + intercept[IllegalArgumentException](coalescer.coalesce(3, parent)) + intercept[IllegalArgumentException](coalescer.coalesce(5, parent)) + // A host that more of a group's partitions prefer than any other host wins. + val majority = sc.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"))) + // It need not be preferred by most of them. + val plurality = sc.makeRDD(Seq( + (0, Seq("host-a")), (1, Seq("host-a")), (2, Seq("host-b")), (3, Seq("host-c")))) + assert(new GroupedPartitionCoalescer(Seq(Seq(0, 1, 2, 3))).coalesce(1, plurality) + .map(_.prefLoc).toSeq === Seq(Some("host-a"))) + // A partition counts once for each host it prefers, however often it lists that host. + val repeated = sc.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"))) + // That holds when a partition names a host in two forms too. + val twoForms = sc.makeRDD(Seq( + (0, Seq("executor_host-a_1", "host-a")), (1, Seq("host-b")), (2, Seq("host-b")))) + assert(new GroupedPartitionCoalescer(Seq(Seq(0, 1, 2))).coalesce(1, twoForms) + .map(_.prefLoc).toSeq === Seq(Some("host-b"))) + // A null host is not a location, as for the scheduler. + val withNull = sc.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 sc = spark.sparkContext + val source = sc.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(sc.getPreferredLocs(coalesced, 1).map(_.host) === Seq("h3")) + // With no host anywhere in the lineage, a group names no location. + val unplaced = sc.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 side that names no location leaves the task to the other side") { + // A zip copies each side's own location, so a side whose groups leave their locations to the + // scheduler drops out of the zipped task's locations when the other side names a host. + val sc = spark.sparkContext + // The other side is over a map, as over a scan, and names h3. + val pair = sc.makeRDD(Seq((0, Seq("h3")), (1, Seq("h3")))).map(identity) + .coalesce(1, shuffle = false, Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1))))) + // A group of one: the scheduler would offer both of its input's hosts. + val single = sc.makeRDD(Seq((0, Seq("h1", "h2")))) + .coalesce(1, shuffle = false, Some(new GroupedPartitionCoalescer(Seq(Seq(0))))) + assert(sc.getPreferredLocs(single, 0).map(_.host).toSet === Set("h1", "h2")) + val zipped = single.zipPartitions(pair)((left, right) => left ++ right) + assert(sc.getPreferredLocs(zipped, 0).map(_.host) === Seq("h3")) + // Groups over persisted data: the task leaves the executor that holds the cached block. + val cached = sc.makeRDD(Seq((0, Seq("h1")), (1, Seq("h1")))).map(identity).cache() + try { + val cachedSide = cached.map(identity) + .coalesce(1, shuffle = false, Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1))))) + cached.count() + // The scheduler looks the cached blocks up again when the next job is submitted. + cachedSide.count() + val cachedLocations = sc.getPreferredLocs(cachedSide, 0) + assert(cachedLocations.nonEmpty && + cachedLocations.forall(_.isInstanceOf[ExecutorCacheTaskLocation]), cachedLocations) + val zippedCached = cachedSide.zipPartitions(pair)((left, right) => left ++ right) + assert(sc.getPreferredLocs(zippedCached, 0).map(_.toString) === Seq("h3")) + } finally { + cached.unpersist() + } + } + + test("SPARK-61279: groups over persisted data leave their locations to the scheduler") { + // As a `GroupPartitionsExec` over an `InMemoryTableScanExec`, whose cached RDD sits under maps. + // 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 direct = cached.coalesce(1, shuffle = false, + Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1))))) + assert(direct.partitions.map(direct.preferredLocations).toSeq === Seq(Nil)) + val coalesced = cached.map(identity).map(identity).coalesce(1, shuffle = false, + Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1))))) + assert(coalesced.partitions.map(coalesced.preferredLocations).toSeq === Seq(Nil)) + cached.count() + // The scheduler looks the cached blocks up again when the next job is submitted. + coalesced.count() + val locations = sc.getPreferredLocs(coalesced, 0) + assert(locations.nonEmpty && locations.forall(_.isInstanceOf[ExecutorCacheTaskLocation]), + locations) + } finally { + cached.unpersist() + } + } + + test("SPARK-61279: a group keeps an executor or HDFS-cache location that is the only one on " + + "its host, and the scheduler offers every location of a group of one") { + val sc = spark.sparkContext + val source = sc.makeRDD(Seq( + (0, Seq("executor_h9_7")), (1, Seq("hdfs_cache_h8")), (2, Seq("h1", "h2", "h3")), + (3, Seq("executor_h9_7")), (4, Seq("executor_h9_7")), + (5, Seq("executor_h9_7")), (6, Seq("h9")), (7, Seq("executor_h1_3")), + (8, Seq("hdfs_cache_h8")), (9, Seq("hdfs_cache_h8")))) + val groups = Seq(Seq(0), Seq(1), Seq(2), Seq(3, 4, 7), Seq(5, 6), Seq(8, 9)) + val coalesced = source.map(identity) + .coalesce(groups.size, shuffle = false, Some(new GroupedPartitionCoalescer(groups))) + // A group of one names no location, so the scheduler offers every location of its input. + assert((0 until 3).map(sc.getPreferredLocs(coalesced, _).map(_.toString).sorted) === Seq( + Seq("executor_h9_7"), Seq("hdfs_cache_h8"), Seq("h1", "h2", "h3"))) + // A larger group keeps a location that is the only one its inputs name on the host, whatever + // they name on other hosts, and the host otherwise. + assert(coalesced.partitions.drop(3).map(coalesced.preferredLocations).toSeq === + Seq(Seq("executor_h9_7"), Seq("h9"), Seq("hdfs_cache_h8"))) + } + + test("SPARK-61279: groups that share partitions leave their locations to the scheduler") { + // As in a partially clustered join: under `REPLICATED_FOR_JOIN` every slot of a split key holds + // the key's whole group, and on the other side each split is a group of one. + val sc = spark.sparkContext + val source = new LocationCountingRDD(sc, Seq(Seq("h1"), Seq("h1", "h2"), Seq("h5"), Seq("h5"))) + // A key split in two and a key that is not split: only the first one's slots share partitions. + val mixed = source.map(identity).coalesce(3, shuffle = false, + Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1), Seq(0, 1), Seq(2, 3))))) + assert(mixed.partitions.map(mixed.preferredLocations).toSeq === Seq(Nil, Nil, Seq("h5"))) + // Only the group that votes looks its partitions' locations up, once each. + assert(source.lookups.get() === 2) + // Zipped with the split side's groups of one, the tasks get master's locations: their own + // split's when the split side comes first, and the first replicated partition's otherwise. + val replicated = sc.makeRDD(Seq((0, Seq("h1", "x1")), (1, Seq("h1", "y1")))).map(identity) + .coalesce(3, shuffle = false, + Some(new GroupedPartitionCoalescer(Seq(Seq(0, 1), Seq(0, 1), Seq(0, 1))))) + val split = sc.makeRDD(Seq((0, Seq("a")), (1, Seq("b")), (2, Seq("c")))).map(identity) + .coalesce(3, shuffle = false, + Some(new GroupedPartitionCoalescer(Seq(Seq(0), Seq(1), Seq(2))))) + val splitFirst = split.zipPartitions(replicated)((left, right) => left ++ right) + assert((0 until 3).map(sc.getPreferredLocs(splitFirst, _).map(_.host)) === + Seq(Seq("a"), Seq("b"), Seq("c"))) + val replicatedFirst = replicated.zipPartitions(split)((left, right) => left ++ right) + assert((0 until 3).map(sc.getPreferredLocs(replicatedFirst, _).map(_.host).sorted) === + Seq.fill(3)(Seq("h1", "x1"))) + } } private case class DummyLeafSparkPlan( @@ -987,3 +1155,16 @@ private case class ExecutableKeyedLeaf(kp: KeyedPartitioning) SparkContext.getActive.get.parallelize(0 until n, n).map(i => InternalRow(i)) } } + +/** An RDD that counts how often its preferred locations are looked up. */ +private class LocationCountingRDD(sc: SparkContext, locations: Seq[Seq[String]]) + extends RDD[Int](sc, Nil) { + val lookups = new AtomicInteger() + override def compute(split: Partition, context: TaskContext): Iterator[Int] = Iterator.empty + override protected def getPartitions: Array[Partition] = + locations.indices.map(i => new Partition { override def index: Int = i }).toArray + override protected def getPreferredLocations(split: Partition): Seq[String] = { + lookups.incrementAndGet() + locations(split.index) + } +}