This is an automated email from the ASF dual-hosted git repository.
HeartSaVioR pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 373cfbbe3cd4 [SPARK-61387][SS] Use the reduce partition as the RTM
streaming shuffle reader id
373cfbbe3cd4 is described below
commit 373cfbbe3cd4697f82385dde74571284c157a4c8
Author: Zerui Bao <[email protected]>
AuthorDate: Fri Nov 13 12:01:16 2026 +0900
[SPARK-61387][SS] Use the reduce partition as the RTM streaming shuffle
reader id
### What changes were proposed in this pull request?
A streaming shuffle reader connects to each writer and identifies itself
with a `shuffleReaderId`. The writer uses that id as the index of the shard it
routes to the reader (`StreamingShuffleServerHandler.receive` does
`futureClients(shuffleReaderId)`), so the id must be the reduce partition the
reader reads. The reader sent its task partition (`context.partitionId()`)
instead, and `StreamingShuffleManager.getReader` ignored the reduce partition
range that `ShuffledRowRDD` passes in.
This PR:
- Adds a required `reducePartitionId` to `StreamingShuffleReader` and uses
it as the `shuffleReaderId` when connecting to writers. The reader's thread
names use it too, so they match the writers' shard ids.
- Makes `StreamingShuffleManager.getReader` pass `startPartition` as the
reduce partition, and fail with an internal error when asked for more than one
reduce partition, because a reader can only claim one shard. Real-Time Mode
runs without AQE, so `ShuffledRowRDD` always asks for `[i, i + 1)`.
The writer side is unaffected: a shuffle map stage's RDD is the shuffle
dependency's RDD, so its task partition is its map index.
### Why are the changes needed?
The task partition and the reduce partition differ whenever the reduce
stage computes other partitions before the shuffle's. For example, in
`s1.union(s2.repartition(2))` where `s1` has one partition, the Union stage
runs the shuffle's reduce partitions 0 and 1 as tasks 1 and 2:
- The reader at task 1 connects as reader 1 and receives reduce partition
1's data.
- The reader at task 2 connects as reader 2, and the writer fails with
`ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2`.
- Nobody claims reduce partition 0.
Every reader is shifted by the same offset, so the last readers always go
out of bounds and the query fails.
### Does this PR introduce _any_ user-facing change?
Yes. A Real-Time Mode query whose Union reads a pipelined shuffle that is
not its first child, such as the example above, used to fail with
`ArrayIndexOutOfBoundsException` on the shuffle writer. It now runs and returns
all rows.
### How was this patch tested?
- `StreamingShuffleSuite`: new test where the readers of reduce partitions
0 and 1 run at task partitions 1 and 2 and must receive their own partitions'
data. `ShuffleGroup` gained a reader task partition offset for this.
- `StreamingShuffleReaderSuite`: the `getReader` routing test now reads
reduce partition 1 from task partition 2 and checks the reader's reduce
partition. New test that `getReader` rejects a range of two reduce partitions.
- `StreamRealTimeModeSuite`: new end-to-end test that unions a
single-partition stream with a repartitioned stream and checks that all rows
arrive, with plan checks that the pipelined shuffle is under the Union's second
child.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Cursor with Claude Opus 5.5
Closes #60424 from zeruibao/SPARK-61387-rtm-reduce-partition.
Authored-by: Zerui Bao <[email protected]>
Signed-off-by: Jungtaek Lim <[email protected]>
skip-checks: true
---
.../streaming/StreamingShuffleManager.scala | 13 +++++++--
.../shuffle/streaming/StreamingShuffleReader.scala | 12 +++++---
.../streaming/StreamingShuffleReaderSuite.scala | 31 ++++++++++++++++----
.../shuffle/streaming/StreamingShuffleSuite.scala | 33 +++++++++++++++++++---
.../sql/streaming/StreamRealTimeModeSuite.scala | 24 ++++++++++++++++
5 files changed, 96 insertions(+), 17 deletions(-)
diff --git
a/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleManager.scala
b/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleManager.scala
index 5ff9f6339425..dddc87687b6e 100644
---
a/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleManager.scala
+++
b/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleManager.scala
@@ -110,8 +110,9 @@ private[spark] class StreamingShuffleManager extends
PipelinedShuffleManager wit
}
/**
- * For the streaming shuffle, the startMapIndex, endMapIndex,
startPartition, and endPartition
- * arguments are not relevant.
+ * For the streaming shuffle, startMapIndex and endMapIndex are not relevant
because a reader
+ * reads from all writers, and the range of reduce partitions must be
exactly one partition,
+ * startPartition. That partition can differ from the reduce task's
partition.
*/
override def getReader[K, C](
handle: ShuffleHandle,
@@ -121,8 +122,14 @@ private[spark] class StreamingShuffleManager extends
PipelinedShuffleManager wit
endPartition: Int,
context: TaskContext,
metrics: ShuffleReadMetricsReporter): ShuffleReader[K, C] = {
+ if (endPartition != startPartition + 1) {
+ throw SparkException.internalError(
+ s"Streaming shuffle ${handle.shuffleId} must be read one reduce
partition at a time, " +
+ s"but got reduce partitions [$startPartition, $endPartition)")
+ }
val streamingShuffleHandle = handle.asInstanceOf[StreamingShuffleHandle[K,
_, C]]
- new StreamingShuffleReader[K, C](streamingShuffleHandle, context)
+ new StreamingShuffleReader[K, C](
+ streamingShuffleHandle, context, reducePartitionId = startPartition)
}
override def unregisterShuffle(shuffleId: Int): Boolean = {
diff --git
a/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReader.scala
b/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReader.scala
index 160a01794d32..c324bbfeb741 100644
---
a/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReader.scala
+++
b/core/src/main/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReader.scala
@@ -80,6 +80,10 @@ class StreamingShuffleReaderIteratorFactory {
class StreamingShuffleReader[K, C](
handle: ShuffleHandle,
val context: TaskContext,
+ // The reduce partition this reader reads, which writers use to route data
to it. It differs
+ // from the task's partition when the reduce stage computes other
partitions before this
+ // shuffle's, e.g. a Union whose shuffled child is not its first child.
+ private[streaming] val reducePartitionId: Int,
clientHandler: Option[StreamingShuffleClientHandler] = None,
private[streaming] val errorNotifier: ErrorNotifier = new ErrorNotifier())
extends ShuffleReader[K, C] with TaskContextAwareLogging {
@@ -101,14 +105,14 @@ class StreamingShuffleReader[K, C](
private val clientConf = SparkTransportConf.fromSparkConf(
conf,
-
s"streaming-shuffle-reader-${streamingShuffleHandle.shuffleId}-${context.partitionId()}",
+
s"streaming-shuffle-reader-${streamingShuffleHandle.shuffleId}-$reducePartitionId",
1, // a client should only need to use 1 thread
role)
private[spark] val taskDiscoveryExecutor =
ThreadUtils.newDaemonSingleThreadExecutor(
s"streaming-shuffle-task-discovery-thread-" +
- s"${streamingShuffleHandle.shuffleId}-${context.partitionId()}")
+ s"${streamingShuffleHandle.shuffleId}-$reducePartitionId")
private val totalNumShuffleWriters: AtomicInteger = new AtomicInteger(-1)
private var perWriterByteLimit: Long = 1
@@ -140,7 +144,7 @@ class StreamingShuffleReader[K, C](
// thread pool used to perform client creation in parallel
private[spark] val clientCreationExecutor =
ThreadUtils.newDaemonFixedThreadPool(
Runtime.getRuntime.availableProcessors,
- s"streaming-shuffle-async-client-creation-${context.partitionId()}")
+ s"streaming-shuffle-async-client-creation-$reducePartitionId")
// Signals to other threads that task discovery should stop. For example, we
may receive all
// the termination messages before we actually put the clients in the client
map. In that
@@ -381,7 +385,7 @@ class StreamingShuffleReader[K, C](
protected def createClient(mapId: Int, remoteHost: String, remotePort: Int):
TransportClient = {
val handler = clientHandler.getOrElse(new StreamingShuffleClientHandler(
mapId,
- context.partitionId(),
+ reducePartitionId,
messageQueue,
streamingShuffleHandle.shuffleId,
perWriterByteLimit,
diff --git
a/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReaderSuite.scala
b/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReaderSuite.scala
index 2d8820ab6181..efe0a83adc2c 100644
---
a/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReaderSuite.scala
+++
b/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleReaderSuite.scala
@@ -30,6 +30,7 @@ import
org.apache.spark.internal.config.SHUFFLE_MANAGER_INCREMENTAL
import org.apache.spark.memory.{TaskMemoryManager, TestMemoryManager}
import org.apache.spark.metrics.MetricsSystem
import org.apache.spark.network.shuffle.streaming.{DataMessage,
StreamingShuffleMessage, TerminationControlMessage}
+import org.apache.spark.shuffle.ShuffleHandle
import
org.apache.spark.shuffle.streaming.StreamingShuffleManager.QUERY_ID_PROPERTY_KEY
/**
@@ -140,25 +141,29 @@ class StreamingShuffleReaderSuite
dataHandled should be(false)
}
- test("getReader routes to a StreamingShuffleReader wired with the given
context") {
+ test("getReader routes to a StreamingShuffleReader wired with the given
context and reduce " +
+ "partition") {
// A construction/routing smoke test: the manager must dispatch to the
streaming reader (not a
// fallback shuffle reader), the reader must construct successfully (its
constructor asserts the
// output tracker, starts the task-discovery and client-creation
executors, and registers the
- // task-completion listener), and it must be wired with the context we
passed in.
+ // task-completion listener), and it must be wired with the context we
passed in. The task runs
+ // at partition 2 but reads reduce partition 1, as in a Union stage whose
shuffled child is not
+ // its first child, so the reader must take its reduce partition from
getReader.
withSpark(new SparkContext("local", "StreamingShuffleReaderSuite",
newConf())) { sc =>
SparkEnv.get.streamingShuffleOutputTracker.get
.asInstanceOf[StreamingShuffleOutputTrackerMaster]
- .registerShuffle(shuffleId = 0, numMaps = 1, numReduces = 1, jobId = 0)
+ .registerShuffle(shuffleId = 0, numMaps = 1, numReduces = 2, jobId = 0)
val rdd = sc.parallelize(1 to 4).map(x => (x, x))
- val dep = new ShuffleDependency[Int, Int, Int](rdd, new
HashPartitioner(1))
+ val dep = new ShuffleDependency[Int, Int, Int](rdd, new
HashPartitioner(2))
val handle = new StreamingShuffleHandle(0, dep)
- val context = createTaskContext(sc.conf, 0)
+ val context = createTaskContext(sc.conf, 2)
try {
val reader = new StreamingShuffleManager()
- .getReader[Int, Int](handle, 0, 1, 0, 1, context, null)
+ .getReader[Int, Int](handle, 0, 1, 1, 2, context, null)
reader shouldBe a[StreamingShuffleReader[_, _]]
val streamingReader = reader.asInstanceOf[StreamingShuffleReader[_, _]]
streamingReader.context should be theSameInstanceAs context
+ streamingReader.reducePartitionId should be(1)
} finally {
// Constructing the reader starts a background task-discovery thread;
the task-completion
// listener (cleanupResources) shuts it down.
@@ -166,4 +171,18 @@ class StreamingShuffleReaderSuite
}
}
}
+
+ test("getReader rejects a range of more than one reduce partition") {
+ // A reader connects to the writers as a single reduce partition, so it
cannot serve a range.
+ // The check runs before the reader is constructed, so no SparkEnv is
needed.
+ val handle = new ShuffleHandle(0) {}
+ val e = intercept[SparkException] {
+ new StreamingShuffleManager().getReader[Int, Int](handle, 0, 1, 0, 2,
null, null)
+ }
+ checkError(
+ e,
+ condition = "INTERNAL_ERROR",
+ parameters = Map("message" -> ("Streaming shuffle 0 must be read one
reduce partition at a " +
+ "time, but got reduce partitions [0, 2)")))
+ }
}
diff --git
a/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleSuite.scala
b/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleSuite.scala
index 95571466e5ab..c6a910c0dc36 100644
---
a/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleSuite.scala
+++
b/core/src/test/scala/org/apache/spark/shuffle/streaming/StreamingShuffleSuite.scala
@@ -127,9 +127,18 @@ class StreamingShuffleSuite
context: TaskContext,
clientHandler: Option[StreamingShuffleClientHandler] = None,
errorNotifier: ErrorNotifier = new ErrorNotifier())
- extends StreamingShuffleReader[K, C](handle, context, clientHandler,
errorNotifier)
+ extends StreamingShuffleReader[K, C](
+ handle, context, context.partitionId(), clientHandler, errorNotifier)
- private class ShuffleGroup[T: ClassTag](sc: SparkContext, mappers: Int,
reducers: Int) {
+ /**
+ * Writers and readers of one shuffle. Reader `i` reads reduce partition `i`
from a task at
+ * partition `i + readerTaskPartitionOffset`.
+ */
+ private class ShuffleGroup[T: ClassTag](
+ sc: SparkContext,
+ mappers: Int,
+ reducers: Int,
+ readerTaskPartitionOffset: Int = 0) {
assert(SparkEnv.get.pipelinedShuffleManager.isInstanceOf[StreamingShuffleManager])
assert(SparkEnv.get.streamingShuffleOutputTracker.isDefined)
SparkEnv.get.streamingShuffleOutputTracker.get
@@ -166,8 +175,8 @@ class StreamingShuffleSuite
}
}
val readers: Array[StreamingShuffleReader[T, T]] =
Array.tabulate(reducers) { i =>
- val taskContext = createTaskContext(sc.conf, i)
- new StreamingShuffleReader[T, T](handle, taskContext) {
+ val taskContext = createTaskContext(sc.conf, i +
readerTaskPartitionOffset)
+ new StreamingShuffleReader[T, T](handle, taskContext, reducePartitionId
= i) {
override def read(): Iterator[Product2[T, T]] = {
val it = super.read()
@@ -283,6 +292,22 @@ class StreamingShuffleSuite
}
}
+ test("readers read their reduce partition when it differs from their task
partition") {
+ // Models a Union stage whose first child has one partition: its shuffled
child's reduce
+ // partitions 0 and 1 run as tasks 1 and 2. Connecting as task 2 would
address a reader that the
+ // writers, which have one shard per reduce partition, do not have.
+ withSpark(new SparkContext("local", "StreamingShuffleSuite", sparkConf)) {
sc =>
+ val g = new ShuffleGroup[Int](sc, 2, 2, readerTaskPartitionOffset = 1)
+ g.readers.map(_.context.partitionId()).toSeq should be(Seq(1, 2))
+
+ g.writers(0).write(Iterator((1, 1), (2, 2)))
+ g.writers(1).write(Iterator((3, 3), (4, 4)))
+
+ await(g.read(0)._2) should be(Set((2, 2), (4, 4)))
+ await(g.read(1)._2) should be(Set((1, 1), (3, 3)))
+ }
+ }
+
test("reader handles concurrent client creation and reader termination") {
withSpark(new SparkContext("local", "StreamingShuffleSuite", sparkConf)) {
sc =>
val g = new ShuffleGroup[Int](sc, 2, 1)
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
index 20bf264d1950..7f6e2daf2814 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
@@ -28,6 +28,7 @@ import org.scalatest.concurrent.PatienceConfiguration.Timeout
import org.apache.spark.{SparkException, SparkIllegalArgumentException,
SparkIllegalStateException, TaskContext}
import org.apache.spark.scheduler.{SparkListener, SparkListenerJobStart,
SparkListenerStageCompleted, SparkListenerStageSubmitted}
+import org.apache.spark.sql.execution.UnionExec
import org.apache.spark.sql.execution.datasources.v2.RealTimeStreamScanExec
import org.apache.spark.sql.execution.exchange.{ReusedExchangeExec,
ShuffleExchangeExec}
import org.apache.spark.sql.execution.streaming.RealTimeTrigger
@@ -260,6 +261,29 @@ class StreamRealTimeModeSuite extends
StreamRealTimeModeSuiteBase {
}
}
+ test("pipelined shuffle: a union reads a shuffle that is not its first
child") {
+ // The union stage runs the single-partition stream as task 0 and the
repartitioned stream's
+ // reduce partitions 0 and 1 as tasks 1 and 2, so its shuffle readers must
connect to the
+ // writers as their reduce partitions rather than their task partitions.
+ val inputData1 = LowLatencyMemoryStream.singlePartition[Int]
+ val inputData2 = LowLatencyMemoryStream[Int](2)
+ val unioned = inputData1.toDS().union(inputData2.toDS().repartition(2))
+
+ testStream(unioned, OutputMode.Update, Map.empty, new
ContinuousMemorySink())(
+ AddData(inputData1, (0 until 10): _*),
+ AddData(inputData2, (10 until 100): _*),
+ StartStream(),
+ CheckAnswerWithTimeout(60000, (0 until 100): _*),
+ Execute { q =>
+ val union = q.lastExecution.executedPlan.collectFirst { case u:
UnionExec => u }.get
+ val shuffles = union.children.map(_.collect { case s:
ShuffleExchangeExec => s })
+ assert(shuffles.map(_.nonEmpty) == Seq(false, true))
+ assert(shuffles(1).forall(_.pipelined), "the streaming-path shuffle
must be pipelined")
+ },
+ StopStream
+ )
+ }
+
test("multiple broadcast joins with the same static table run in Real-Time
Mode") {
// Two broadcast joins against the SAME static table -- exchange reuse
collapses the second
// broadcast into a ReusedExchangeExec. This is the supported reuse shape
in Real-Time Mode: a
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]