You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by vi...@apache.org on 2026/09/14 07:24:28 UTC
(spark) branch branch-4.x updated: [SPARK-57399][CORE][SQL] Local repartition: in-process pipelined channel shuffle for a single executor
This is an automated email from the ASF dual-hosted git repository.
viirya pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new 51ac6a9f0f72 [SPARK-57399][CORE][SQL] Local repartition: in-process pipelined channel shuffle for a single executor
51ac6a9f0f72 is described below
commit 51ac6a9f0f72d3d28b2bcd3295efd6f15b4237d8
Author: Liang-Chi Hsieh <vi...@gmail.com>
AuthorDate: Mon Sep 14 00:24:02 2026 -0700
[SPARK-57399][CORE][SQL] Local repartition: in-process pipelined channel shuffle for a single executor
### What changes were proposed in this pull request?
This PR adds an experimental, opt-in, in-process channel transport for local-mode batch pipelined shuffles. Eligible SQL queries run producer and consumer stages concurrently, exchanging records through bounded in-memory queues instead of shuffle files. The feature is disabled by default, and its new settings are internal.
It builds on `PipelinedShuffleDependency` and dependency-type shuffle routing (SPARK-58185), concurrent-stage scheduling (SPARK-58263), group-atomic failure handling (SPARK-58398), and MapOutputTracker decoupling (SPARK-58454).
**Core transport and lifecycle**
- `ChannelShuffleRendezvous`, `ChannelShuffleWriter`, and `ChannelShuffleReader` exchange batches through bounded queues, with a single reader per reduce partition and end-of-stream markers from each producer. Run epochs isolate repeated executions; run completion releases channel state even while the Dataset remains reachable.
- `PipelinedChannelShuffleManager` requires local mode, bypasses the streaming shuffle output tracker, and declares `requiresDetachedRecords = true`. The SQL shuffle input path copies records when needed before handing them to concurrent consumers.
- The scheduler supplies live reduce partitions so producers do not block on queues for partitions that a partial-read job will never consume. Runtime admission still checks actual group demand and available slots.
**SQL integration and fallbacks**
- `EnablePipelinedShuffle` and `AQEEnablePipelinedShuffle` rewrite eligible exchanges only when the opt-in flag is enabled, Spark is in local mode, and the channel manager is configured. An incompatible manager leaves execution regular and emits a one-time warning.
- Both rules estimate the complete pipelined group's task demand. Plans exceeding local capacity, or with unknown widths, retain regular shuffles. Ordinary non-bucketed file scans report unknown widths and therefore remain regular in this iteration; pipeline eligibility requires a known width, as provided by range and some partitioned inputs. This allows the default 200 shuffle partitions to execute on local[8] without a pipelined slot-admission failure, and preserves explicitly reque [...]
- `Dataset.rdd`, PySpark RDD exports, checkpoint/localCheckpoint, cache construction, and cached-input plans use regular shuffles. RDD-backed SQL inputs also remain regular, and recursive CTE execution uses regular plans when exporting iteration RDDs. Unsupported consumer shapes, including coalesced shuffle reads, Cartesian products, and limit operators that build hidden shuffles, also retain regular execution. Exchange-reuse guards prevent unsupported channel fan-out.
- `toLocalIterator` (JVM and Python, including prefetch) and SQL cursors use a separate regular-shuffle plan, including when the Dataset has already executed a pipelined action. A fallback QueryExecution is memoized for repeated exits; shuffle-free or ineligible executions avoid cloning a session. Iterator jobs can reuse materialized shuffle output without changing the caller's session setting or original plan.
- AQE keeps mixed regular/pipelined shapes regular. Pipelined exchanges do not receive AQE partition coalescing.
**Internal configuration**
| Setting | Default | Purpose |
| --- | --- | --- |
| `spark.sql.shuffle.localPipelined.enabled` | `false` | Opt in to eligible local batch SQL rewrites |
| `spark.shuffle.channel.batchSize` | `1024` | Records per channel batch |
| `spark.shuffle.channel.queueCapacity` | `64` | Batches per partition queue |
All three settings are internal. `spark.shuffle.manager.incremental` must select `org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager` for the SQL rewrite to take effect.
**Scope and deferred work**
- Concurrent actions sharing the same pipelined exchange remain unsupported. Rejecting a second action preserves the owning action's channel state; this is not support for concurrent sharing. General concurrent sharing is deferred.
- Recovery from lost regular-shuffle prefixes within a mixed pipelined job is deferred. The lower-level scheduler can admit a mixed job whose regular prefix is already materialized, but a prefix `FetchFailed` aborts the pipelined group; automatic prefix rematerialization and retry are not implemented. The SQL rewrite therefore conservatively retains regular shuffles for mixed plans. Lower-level mixed-job execution is not a supported SQL recovery capability.
- The `toLocalIterator` fallback does not provide general cross-job output reuse for pipelined exchanges. Other multi-job consumers can recompute producers for each job.
### Why are the changes needed?
For local batch workloads, handing records directly to concurrently running consumers can avoid shuffle-file I/O and serialization/fetch overhead. This transport uses Spark's existing shuffle routing and concurrent-stage scheduler, retaining separately scheduled stages and shuffle metrics.
The internal, disabled-by-default scope allows this transport to be evaluated while its supported execution paths remain limited. Conservative regular-shuffle fallbacks cover SQL paths that cannot safely use bounded, single-reader channels.
### Does this PR introduce _any_ user-facing change?
Yes, when explicitly enabled with the channel manager in local mode: eligible batch queries use in-process pipelined exchanges and concurrently scheduled producer/consumer stages. There is no behavior change by default. The three new settings are internal experimental controls, not public configuration commitments. Unsupported SQL shapes retain regular shuffles, subject to the scope and limitations above.
### How was this patch tested?
Added or extended coverage includes:
- `PipelinedChannelShuffleSuite`: row correctness, routing, slot admission, local-mode enforcement, partial reads, lifecycle cleanup, epoch isolation, and lower-level materialized-prefix execution.
- `PipelinedShuffleSqlSuite` and `AQEPipelinedShuffleSuite`: eligible query results, Dataset/RDD and cache fallbacks, repeated actions, owner preservation when concurrent reuse is rejected, and regular execution for mixed AQE plans.
- Capacity regressions in both AQE modes: default and explicit 200-partition plans on local[8], preservation of explicit partition counts, and whole-group demand of 2 + 6 slots remaining pipelined while 2 + 6 + 1 slots falls back.
- `toLocalIterator` regressions in both AQE modes, before and after `collect`: four output-partition jobs evaluate 1,000 producer rows once, and repeated iterator actions can reuse the fallback shuffle output when it is retained.
- `AQEEnablePipelinedShuffleRuleSuite` and `PipelinedLimitHangSuite`: mixed-plan and unsupported-consumer fallbacks.
- `DAGSchedulerSuite`, `PipelinedShuffleRoutingSuite`, and `ContextCleanerSuite`: job-shape classification, group failure handling, routing, and cleanup. These tests do not establish automatic mixed-prefix recovery.
The latest validation passed 143 SQL/cursor tests and the PySpark pipelined-shuffle regression suite. Added coverage includes RDD-backed SQL actions, recursive CTEs, file-scan fallback, fallback reuse, and cache eviction with bounded queues and an accumulator verifying partition recomputation. The Python suite is registered with the CI test module, and the dangling-test check passes. Core, Catalyst, and SQL source Scala style checks, plus SQL test Scala style checks, completed with ze [...]
The PR includes `PipelinedShuffleBenchmark` and a checked-in results file comparing the channel, regular shuffle, and RPC streaming transports across batch shapes. The benchmark was not rerun for the latest fallback/configuration changes.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code
Generated-by: OpenAI Codex
Closes #58097 from viirya/local-repartition-v2-pr.
Authored-by: Liang-Chi Hsieh <vi...@gmail.com>
Signed-off-by: Liang-Chi Hsieh <vi...@gmail.com>
(cherry picked from commit 6232f2191437d30f2077cdaab06398e789d74e0b)
Signed-off-by: Liang-Chi Hsieh <vi...@gmail.com>
---
.../scala/org/apache/spark/ContextCleaner.scala | 37 +
.../main/scala/org/apache/spark/SparkContext.scala | 15 +
.../src/main/scala/org/apache/spark/SparkEnv.scala | 12 +-
.../org/apache/spark/internal/config/package.scala | 30 +
.../spark/rdd/ShuffleReducePartitionMapping.scala | 42 ++
.../scala/org/apache/spark/rdd/ShuffledRDD.scala | 5 +-
.../org/apache/spark/scheduler/DAGScheduler.scala | 493 +++++++++++--
.../org/apache/spark/shuffle/ShuffleManager.scala | 58 +-
.../local/pipelined/ChannelShuffleRendezvous.scala | 197 +++++
.../pipelined/ChannelShuffleWriterReader.scala | 359 ++++++++++
.../pipelined/PipelinedChannelShuffleManager.scala | 158 ++++
.../apache/spark/scheduler/DAGSchedulerSuite.scala | 212 +++++-
.../shuffle/PipelinedShuffleRoutingSuite.scala | 62 +-
.../pipelined/PipelinedChannelShuffleSuite.scala | 590 +++++++++++++++
dev/sparktestsupport/modules.py | 1 +
python/pyspark/sql/tests/test_pipelined_shuffle.py | 105 +++
.../org/apache/spark/sql/internal/SQLConf.scala | 19 +
.../PipelinedShuffleBenchmark-jdk21-results.txt | 110 +++
.../PipelinedShuffleBenchmark-jdk25-results.txt | 110 +++
.../org/apache/spark/sql/classic/Dataset.scala | 17 +-
.../apache/spark/sql/execution/CacheManager.scala | 5 +-
.../spark/sql/execution/QueryExecution.scala | 38 +-
.../spark/sql/execution/ShuffledRowRDD.scala | 24 +-
.../apache/spark/sql/execution/UnionLoopExec.scala | 11 +-
.../adaptive/AQEEnablePipelinedShuffle.scala | 205 ++++++
.../execution/adaptive/AdaptiveSparkPlanExec.scala | 20 +-
.../sql/execution/command/v2/OpenCursorExec.scala | 2 +-
.../exchange/EnablePipelinedShuffle.scala | 150 ++++
.../exchange/PipelinedShuffleEligibility.scala | 134 ++++
.../execution/exchange/ShuffleExchangeExec.scala | 23 +-
.../AQEEnablePipelinedShuffleRuleSuite.scala | 67 ++
.../adaptive/AQEPipelinedShuffleSuite.scala | 168 +++++
.../exchange/PipelinedLimitHangSuite.scala | 148 ++++
.../exchange/PipelinedShuffleBenchmark.scala | 459 ++++++++++++
.../exchange/PipelinedShuffleSqlSuite.scala | 792 +++++++++++++++++++++
.../exchange/PipelinedShuffleTestSession.scala | 81 +++
36 files changed, 4820 insertions(+), 139 deletions(-)
diff --git a/core/src/main/scala/org/apache/spark/ContextCleaner.scala b/core/src/main/scala/org/apache/spark/ContextCleaner.scala
index 6c1b49157cc0..52d8507fb953 100644
--- a/core/src/main/scala/org/apache/spark/ContextCleaner.scala
+++ b/core/src/main/scala/org/apache/spark/ContextCleaner.scala
@@ -261,6 +261,25 @@ private[spark] class ContextCleaner(
streamingShuffleOutputTrackerMaster.foreach(_.unregisterShuffle(shuffleId))
listeners.asScala.foreach(_.shuffleCleaned(shuffleId))
logDebug("Cleaned pipelined shuffle " + shuffleId)
+ } else if (heldByTracklessPipelinedManager(shuffleId)) {
+ // The shuffle is in NEITHER tracker AND a pipelined manager that keeps no output tracker
+ // (PipelinedChannelShuffleManager.usesStreamingShuffleOutputTracker = false) reports that
+ // it holds this shuffle. An in-process pipelined shuffle registers with no tracker at all,
+ // so the two branches above miss it, yet its process-wide rendezvous queues
+ // (ChannelShuffleRendezvous) still need freeing. The removeShuffle call below issues a
+ // RemoveShuffle that routes to the manager's unregisterShuffle (via
+ // SparkEnv.unregisterShuffleFromAllManagers) -> ChannelShuffleRendezvous.removeShuffle,
+ // freeing the queues.
+ // This arm is gated on the manager actually HOLDING this shuffle id, not merely on the
+ // manager being tracker-less: an already-cleaned REGULAR shuffle also reaches this else
+ // (RDD.cleanShuffleDependencies unregisters it from the MapOutputTracker eagerly, then its
+ // later GC re-cleans it), even in a feature-ON session that runs regular shuffles too, and
+ // firing an extra cluster-wide RemoveShuffle RPC + shuffleCleaned callback for it would be
+ // a behavior change. Scoping to holdsShuffle keeps the new call on the pipelined path only.
+ logDebug("Cleaning tracker-less pipelined shuffle " + shuffleId)
+ shuffleDriverComponents.removeShuffle(shuffleId, blocking)
+ listeners.asScala.foreach(_.shuffleCleaned(shuffleId))
+ logDebug("Cleaned tracker-less pipelined shuffle " + shuffleId)
} else {
logDebug("Asked to cleanup non-existent shuffle (maybe it was already removed)")
}
@@ -269,6 +288,24 @@ private[spark] class ContextCleaner(
}
}
+ /**
+ * Whether a pipelined shuffle manager that keeps NO output tracker is configured AND the
+ * in-process rendezvous currently holds state for `shuffleId` -- the only case where a shuffle
+ * in neither tracker legitimately holds cleanup state (rendezvous queues / abandoned marks) that
+ * doCleanupShuffle's else arm must free. False for the default (no pipelined manager, or the RPC
+ * streaming manager, which registers in the streaming tracker), and false for a REGULAR shuffle
+ * in a feature-on session (never present in the rendezvous) -- so an already-cleaned shuffle
+ * reaching that else stays a no-op rather than firing a duplicate cluster-wide RemoveShuffle RPC.
+ *
+ * The manager answers `holdsShuffle` from the state that would leak rather than from a
+ * registration record -- see `PipelinedShuffleManager.holdsShuffle` -- so a shuffle unregistered
+ * before its job ran, whose state the run then recreated, is still freed here.
+ */
+ private def heldByTracklessPipelinedManager(shuffleId: Int): Boolean = {
+ val mgr = sc.env.pipelinedShuffleManager
+ mgr != null && !mgr.usesStreamingShuffleOutputTracker && mgr.holdsShuffle(shuffleId)
+ }
+
/** Perform broadcast cleanup. */
def doCleanupBroadcast(broadcastId: Long, blocking: Boolean): Unit = {
try {
diff --git a/core/src/main/scala/org/apache/spark/SparkContext.scala b/core/src/main/scala/org/apache/spark/SparkContext.scala
index 5c8c30e2807c..482630e497bc 100644
--- a/core/src/main/scala/org/apache/spark/SparkContext.scala
+++ b/core/src/main/scala/org/apache/spark/SparkContext.scala
@@ -3495,6 +3495,21 @@ object SparkContext extends Logging {
private[spark] val SPARK_JOB_DESCRIPTION = "spark.job.description"
private[spark] val SPARK_JOB_GROUP_ID = "spark.jobGroup.id"
private[spark] val SPARK_JOB_INTERRUPT_ON_CANCEL = "spark.job.interruptOnCancel"
+ // Comma-separated live reduce-partition ids for a pipelined job (SPARK-57399): the reduce
+ // partitions this job actually reads. Attached to a pipelined PRODUCER stage's task
+ // properties so the in-process channel writer can drop records routed to partitions no
+ // consumer will drain (e.g. LIMIT/executeTake reads only a subset), which would otherwise
+ // fill their bounded queues and deadlock the writer. Absent = every partition is live.
+ private[spark] val SPARK_PIPELINED_LIVE_REDUCE_PARTITIONS =
+ "spark.pipelined.liveReducePartitions"
+ // Per-run epoch for a pipelined job (SPARK-57399), set to the jobId. Attached to the job's
+ // properties so BOTH the producer (writer) and consumer (reader) tasks of the one gang read
+ // the same value, and keys the in-process channel rendezvous per run: a re-run of the same
+ // shuffleId (a RangePartitioner sample job then the main job; executeTake batches; a classic
+ // Dataset re-executing a reused plan) gets a fresh epoch, so its queues are physically
+ // separate from the previous run's leftovers rather than relying on clearing shared state.
+ // Absent = epoch 0 (the core-RDD test path that never re-runs a shuffleId).
+ private[spark] val SPARK_PIPELINED_RUN_EPOCH = "spark.pipelined.runEpoch"
private[spark] val SPARK_JOB_TAGS = "spark.job.tags"
private[spark] val SPARK_SCHEDULER_POOL = "spark.scheduler.pool"
private[spark] val RDD_SCOPE_KEY = "spark.rdd.scope"
diff --git a/core/src/main/scala/org/apache/spark/SparkEnv.scala b/core/src/main/scala/org/apache/spark/SparkEnv.scala
index d48640d9469b..f8e2ae3abcca 100644
--- a/core/src/main/scala/org/apache/spark/SparkEnv.scala
+++ b/core/src/main/scala/org/apache/spark/SparkEnv.scala
@@ -48,7 +48,7 @@ import org.apache.spark.security.CryptoStreamUtils
import org.apache.spark.serializer.{JavaSerializer, Serializer, SerializerManager}
import org.apache.spark.shuffle.{BlockingShuffleManager, PipelinedShuffleManager}
import org.apache.spark.shuffle.{ShuffleBlockResolver, ShuffleManager}
-import org.apache.spark.shuffle.streaming.{MultiShuffleManager, StreamingShuffleManager}
+import org.apache.spark.shuffle.streaming.MultiShuffleManager
import org.apache.spark.storage._
import org.apache.spark.udf.worker.UDFWorkerSpecification
import org.apache.spark.udf.worker.core.{UDFDispatcherFactory, UDFDispatcherManager, WorkerDispatcher}
@@ -464,12 +464,14 @@ class SparkEnv (
return
}
- // The tracker is needed when the pipelined manager (spark.shuffle.manager.incremental) is a
- // StreamingShuffleManager -- which is the default. Inspect the already-instantiated manager
- // rather than re-reading the config; this runs at the end of initializeShuffleManager, so the
+ // The tracker is a transport directory of writer task locations; it is needed only by a
+ // pipelined manager that discovers writers over RPC. The manager declares this via
+ // usesStreamingShuffleOutputTracker (the RPC streaming manager returns true, the default;
+ // an in-process transport returns false). Inspect the already-instantiated manager rather
+ // than re-reading the config; this runs at the end of initializeShuffleManager, so the
// manager is non-null here.
val incrementalIsStreaming =
- _pipelinedShuffleManager.isInstanceOf[StreamingShuffleManager]
+ _pipelinedShuffleManager.usesStreamingShuffleOutputTracker
// It is also needed when a MultiShuffleManager is the blocking manager (spark.shuffle.manager):
// it internally routes some shuffles to streaming. A bare StreamingShuffleManager cannot be the
// blocking manager -- it is pipelined and rejected from that slot in initializeShuffleManager.
diff --git a/core/src/main/scala/org/apache/spark/internal/config/package.scala b/core/src/main/scala/org/apache/spark/internal/config/package.scala
index 87373d777d93..500229f0c9da 100644
--- a/core/src/main/scala/org/apache/spark/internal/config/package.scala
+++ b/core/src/main/scala/org/apache/spark/internal/config/package.scala
@@ -1867,6 +1867,36 @@ package object config {
.stringConf
.createWithDefault("streaming")
+ private[spark] val SHUFFLE_PIPELINED_CHANNEL_BATCH_SIZE =
+ ConfigBuilder("spark.shuffle.channel.batchSize")
+ .internal()
+ .doc("Number of records the in-process pipelined channel shuffle accumulates per output " +
+ "partition before handing a batch across its queue in one operation. Larger batches " +
+ "amortize the queue's per-operation lock cost at the price of higher hand-off latency " +
+ "and per-partition buffering. Only used when spark.shuffle.manager.incremental is the " +
+ "in-process channel manager.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .intConf
+ .checkValue(_ > 0, "batch size must be positive")
+ .createWithDefault(1024)
+
+ private[spark] val SHUFFLE_PIPELINED_CHANNEL_QUEUE_CAPACITY =
+ ConfigBuilder("spark.shuffle.channel.queueCapacity")
+ .internal()
+ .doc("Depth, in BATCHES, of each per-reduce-partition queue in the in-process pipelined " +
+ "channel shuffle. This is the backpressure bound: a producer blocks once a partition's " +
+ "queue holds this many batches. It also sets the worst-case heap the transport pins for " +
+ "one shuffle -- roughly queueCapacity * spark.shuffle.channel.batchSize * " +
+ "numPartitions rows held as strong references (not tracked by the memory manager and not " +
+ "spilled), so raise it together with an eye on that product. Only used when " +
+ "spark.shuffle.manager.incremental is the in-process channel manager.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .intConf
+ .checkValue(_ > 0, "queue capacity must be positive")
+ .createWithDefault(64)
+
private[spark] val SHUFFLE_REDUCE_LOCALITY_ENABLE =
ConfigBuilder("spark.shuffle.reduceLocality.enabled")
.doc("Whether to compute locality preferences for reduce tasks")
diff --git a/core/src/main/scala/org/apache/spark/rdd/ShuffleReducePartitionMapping.scala b/core/src/main/scala/org/apache/spark/rdd/ShuffleReducePartitionMapping.scala
new file mode 100644
index 000000000000..efaf6eb30c90
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/rdd/ShuffleReducePartitionMapping.scala
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.rdd
+
+/**
+ * Implemented by an RDD that reads a shuffle, to declare how ITS partition index maps to the
+ * shuffle's REDUCE partition index.
+ *
+ * The scheduler needs this for a pipelined shuffle with a partial read: it must tell the producer
+ * which reduce partitions actually have a reader, and it derives that from the subset of result
+ * partitions the job runs (see `DAGScheduler.liveReduceSet`). Equal partition COUNTS do not imply
+ * an identity mapping -- a reader that splits one reduce partition across two of its partitions and
+ * coalesces two others into one has the same count and a different mapping -- and guessing wrong is
+ * not a hang but silently dropped records, since the producer skips every partition outside the set
+ * it is given. So the mapping is asked of the reader rather than inferred.
+ *
+ * An implementation returns `None` for a partition whose reduce index is not a single well-defined
+ * value (a coalesced range, a partial-mapper split); the scheduler then treats the mapping as
+ * uncomputable and keeps every reduce partition live.
+ */
+private[spark] trait ShuffleReducePartitionMapping {
+ /**
+ * The single reduce partition index this RDD's partition `partitionIndex` reads, or `None` if it
+ * reads no single reduce partition (e.g. a coalesced multi-reducer range).
+ */
+ def reducePartitionIndex(partitionIndex: Int): Option[Int]
+}
diff --git a/core/src/main/scala/org/apache/spark/rdd/ShuffledRDD.scala b/core/src/main/scala/org/apache/spark/rdd/ShuffledRDD.scala
index 0c48d4da0c28..a596ba925d34 100644
--- a/core/src/main/scala/org/apache/spark/rdd/ShuffledRDD.scala
+++ b/core/src/main/scala/org/apache/spark/rdd/ShuffledRDD.scala
@@ -41,7 +41,10 @@ private[spark] class ShuffledRDDPartition(val idx: Int) extends Partition {
class ShuffledRDD[K: ClassTag, V: ClassTag, C: ClassTag](
@transient var prev: RDD[_ <: Product2[K, V]],
part: Partitioner)
- extends RDD[(K, C)](prev.context, Nil) {
+ extends RDD[(K, C)](prev.context, Nil) with ShuffleReducePartitionMapping {
+
+ // One partition per reduce partition, in order (see getPartitions), so the mapping is identity.
+ override def reducePartitionIndex(partitionIndex: Int): Option[Int] = Some(partitionIndex)
private var userSpecifiedSerializer: Option[Serializer] = None
diff --git a/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala b/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
index 6a897e461528..6d4d9c7a5b2f 100644
--- a/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
+++ b/core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala
@@ -45,7 +45,7 @@ import org.apache.spark.network.shuffle.{BlockStoreClient, MergeFinalizerListene
import org.apache.spark.network.shuffle.protocol.MergeStatuses
import org.apache.spark.network.util.JavaUtils
import org.apache.spark.partial.{ApproximateActionListener, ApproximateEvaluator, PartialResult}
-import org.apache.spark.rdd.{DeterministicLevel, RDD, RDDCheckpointData, ReliableRDDCheckpointData}
+import org.apache.spark.rdd.{DeterministicLevel, RDD, RDDCheckpointData, ReliableRDDCheckpointData, ShuffleReducePartitionMapping}
import org.apache.spark.resource.{CpuAmount, ResourceProfile, TaskResourceProfile}
import org.apache.spark.resource.ResourceProfile.{CPUS, DEFAULT_RESOURCE_PROFILE_ID, EXECUTOR_CORES_LOCAL_PROPERTY, MAX_TASKS_PER_EXECUTOR_LOCAL_PROPERTY, PYSPARK_MEMORY_LOCAL_PROPERTY}
import org.apache.spark.rpc.RpcTimeout
@@ -757,12 +757,17 @@ private[spark] class DAGScheduler(
// before addActiveJob (its sole populator) runs, so a pipelined stage's mapStageJobs is always
// empty; and checkAndScheduleShuffleMergeFinalize's getStatistics is on the push-based-merge
// path, which a pipelined dependency rejects up front (checkPipelinedProducerSupported).
- if (!outputTracker.containsShuffle(shuffleDep.shuffleId)) {
- logInfo(log"Registering RDD ${MDC(RDD_ID, rdd.id)} " +
- log"(${MDC(CREATION_SITE, rdd.getCreationSite)}) as input to " +
- log"shuffle ${MDC(SHUFFLE_ID, shuffleDep.shuffleId)}")
- outputTracker.registerShuffle(shuffleDep.shuffleId, rdd.partitions.length,
- shuffleDep.partitioner.numPartitions, jobId)
+ // `outputTracker` is None only for a pipelined shuffle whose in-process manager needs no
+ // tracker; such a shuffle registers with no output tracker (its availability lives on the
+ // stage). Otherwise register as before.
+ outputTracker.foreach { tracker =>
+ if (!tracker.containsShuffle(shuffleDep.shuffleId)) {
+ logInfo(log"Registering RDD ${MDC(RDD_ID, rdd.id)} " +
+ log"(${MDC(CREATION_SITE, rdd.getCreationSite)}) as input to " +
+ log"shuffle ${MDC(SHUFFLE_ID, shuffleDep.shuffleId)}")
+ tracker.registerShuffle(shuffleDep.shuffleId, rdd.partitions.length,
+ shuffleDep.partitioner.numPartitions, jobId)
+ }
}
stage
}
@@ -777,15 +782,36 @@ private[spark] class DAGScheduler(
* enforces the same invariant, see StreamingShuffleReader).
*/
private def outputTrackerMaster(
- shuffleDep: ShuffleDependency[_, _, _]): ShuffleOutputTrackerMaster = {
+ shuffleDep: ShuffleDependency[_, _, _]): Option[ShuffleOutputTrackerMaster] = {
if (shuffleDep.isInstanceOf[PipelinedShuffleDependency[_, _, _]]) {
- sc.env.streamingShuffleOutputTracker
- .getOrElse(throw new IllegalStateException(
- s"A pipelined shuffle (id ${shuffleDep.shuffleId}) requires a " +
- "StreamingShuffleOutputTracker, but none is configured"))
- .asInstanceOf[StreamingShuffleOutputTrackerMaster]
+ // A pipelined shuffle uses the StreamingShuffleOutputTracker only when its manager
+ // discovers writers over RPC. An in-process transport declares it needs no tracker; such a
+ // shuffle registers with no output tracker at all, and its map-stage availability is tracked
+ // locally on the ShuffleMapStage.
+ //
+ // Key off the manager's flag, NOT merely off tracker PRESENCE: a tracker can exist even when
+ // the pipelined (incremental) manager does not want one. SparkEnv.initialize-
+ // StreamingShuffleOutputTracker creates the tracker when the incremental manager needs it OR
+ // when the BLOCKING manager is a MultiShuffleManager (blockingIsMulti). In the latter case
+ // (MultiShuffleManager blocking + in-process channel incremental) the tracker is present but
+ // the channel manager reports usesStreamingShuffleOutputTracker = false, so a channel shuffle
+ // must still register with NO tracker -- registering it there would be inert (the channel
+ // reader/writer never consult it) but would contradict this invariant and the one
+ // PipelinedShuffleRoutingSuite pins. When the manager DOES want a tracker but none exists,
+ // that is a real misconfiguration (a consumer would find no writer locations), so fail loud.
+ if (!sc.env.pipelinedShuffleManager.usesStreamingShuffleOutputTracker) {
+ None
+ } else {
+ sc.env.streamingShuffleOutputTracker match {
+ case some @ Some(_) => some.map(_.asInstanceOf[StreamingShuffleOutputTrackerMaster])
+ case None =>
+ throw new IllegalStateException(
+ s"A pipelined shuffle (id ${shuffleDep.shuffleId}) requires a " +
+ "StreamingShuffleOutputTracker, but none is configured")
+ }
+ }
} else {
- mapOutputTracker
+ Some(mapOutputTracker)
}
}
@@ -1138,17 +1164,51 @@ private[spark] class DAGScheduler(
}
/**
- * Classifies the shuffle boundaries in the RDD graph rooted at `finalRDD` by kind, walking the
- * RDD dependency graph directly (before any stages are created). Returns whether the graph
- * contains any [[PipelinedShuffleDependency]] and whether it contains any regular (non-pipelined)
- * `ShuffleDependency`. Narrow dependencies are not boundaries and are ignored.
+ * Shape of the shuffle boundaries in the RDD graph rooted at a job's final RDD, computed by
+ * [[classifyJobShuffleShape]] before any stage is created (so an unsupported job is rejected
+ * fail-fast with no partial scheduler state).
+ *
+ * The supported shapes are:
+ * - all-regular (`hasPipelined` false, nothing pipelined anywhere);
+ * - all-pipelined (`hasPipelined` true, no regular boundary anywhere);
+ * - MATERIALIZED-PREFIX MIXED: pipelined shuffles in the region reachable from the final RDD
+ * without crossing a regular shuffle, where every regular boundary at the edge of that
+ * region is FULLY MATERIALIZED (all map outputs registered with the MapOutputTracker) and
+ * no pipelined shuffle sits below any regular boundary. The materialized prefix never
+ * re-runs, so the job executes exactly like an all-pipelined job whose leaves read
+ * already-materialized shuffle data; gang admission demand (final stage + suffix producers)
+ * is unchanged. This is the shape adaptive execution produces: prior map-stage jobs
+ * materialize the prefix stages, and the final job runs the pipelined tail.
*
- * A job must be either ALL-regular or ALL-pipelined: a job whose shuffle graph mixes a pipelined
- * shuffle with a regular one is rejected fail-fast (see `handleJobSubmitted`). Restricting to a
- * single kind makes the whole job one pipelined group when pipelined, so gang admission can be
- * decided up front before any stage is submitted.
+ * An UNMATERIALIZED regular boundary in a pipelined job stays rejected: its stage would have to
+ * run while gang-admitted producers already hold slots (blocked on transport backpressure
+ * waiting for consumers), and admission does not account for the prefix's slots -- the prefix
+ * could be starved and deadlock the group. Sequencing the prefix before the gang is future
+ * work. A pipelined shuffle BELOW a regular boundary is also rejected: it is not part of the
+ * suffix group, and (if the boundary were unmaterialized) would have to run under a regime the
+ * group machinery does not cover.
*/
- private def classifyJobShuffleKinds(finalRDD: RDD[_]): (Boolean, Boolean) = {
+ private[scheduler] case class JobShuffleShape(
+ hasPipelined: Boolean,
+ hasUnmaterializedRegularBoundary: Boolean,
+ hasPipelinedBelowRegular: Boolean) {
+ /** Mixed in a way the scheduler does not support (see class doc). */
+ def isUnsupportedMix: Boolean =
+ hasPipelinedBelowRegular || (hasPipelined && hasUnmaterializedRegularBoundary)
+ }
+
+ /**
+ * Which KINDS of shuffle boundary the RDD graph rooted at `finalRDD` contains: any
+ * [[PipelinedShuffleDependency]], and any regular (non-pipelined) `ShuffleDependency`. Narrow
+ * dependencies are not boundaries and are ignored. Walks the RDD graph directly (before any stage
+ * exists) over the shared `traverseRDDGraph`, whose visited set is keyed on the RDD alone -- so
+ * this pass allocates nothing per visit.
+ *
+ * This is the cheap pre-pass for [[classifyJobShuffleShape]]: a job with only one kind cannot be
+ * an unsupported mix, so the precise (and more expensive) below-regular analysis is only needed
+ * when both kinds are present.
+ */
+ private[scheduler] def classifyJobShuffleKinds(finalRDD: RDD[_]): (Boolean, Boolean) = {
var hasPipelined = false
var hasRegular = false
traverseRDDGraph(finalRDD) { (rdd, enqueue) =>
@@ -1166,6 +1226,94 @@ private[spark] class DAGScheduler(
(hasPipelined, hasRegular)
}
+ /** Classify `finalRDD`'s shuffle graph; see [[JobShuffleShape]] for the shape semantics. */
+ private[scheduler] def classifyJobShuffleShape(finalRDD: RDD[_]): JobShuffleShape = {
+ // Cheap pre-pass first: which KINDS of boundary the graph has, over the shared
+ // `traverseRDDGraph` (a HashSet[RDD] visited set, no per-visit allocation). Only a job with
+ // BOTH kinds can be an unsupported mix, and only then are the two below-regular facts
+ // meaningful:
+ // - all-regular (no pipelined dep) => nothing can be pipelined-below-regular;
+ // - all-pipelined (no regular dep) => no regular boundary to be below, or to materialize.
+ // So every job that is not mixed -- which is EVERY job on a deployment that never enables the
+ // feature -- costs exactly what it costs without this feature, instead of paying for the
+ // (RDD, Boolean)-keyed two-context walk and the boundary map below.
+ val (hasPipelinedKind, hasRegularKind) = classifyJobShuffleKinds(finalRDD)
+ if (!hasPipelinedKind || !hasRegularKind) {
+ return JobShuffleShape(
+ hasPipelined = hasPipelinedKind,
+ hasUnmaterializedRegularBoundary = false,
+ hasPipelinedBelowRegular = false)
+ }
+ var hasPipelined = false
+ var pipelinedBelow = false
+ // Frontier regular shuffle boundaries: those reachable from the final RDD WITHOUT crossing
+ // another regular boundary, deduped by shuffle ID. Only these matter for the materialization
+ // check (a regular boundary below another one is never a runnable suffix member).
+ val regularBoundaries = new HashMap[Int, ShuffleDependency[_, _, _]]
+
+ // ONE walk, carrying `belowRegular` (true once the path from the final RDD has crossed a
+ // regular boundary), computes hasPipelined and pipelinedBelow together -- replacing the old
+ // per-boundary rddGraphHasPipelinedDependency re-walks (O(K x graph) on shared ancestors).
+ // A node reachable BOTH above and below a regular boundary must be explored in BOTH contexts:
+ // a pipelined dep under it counts as pipelinedBelow on the below path but not on the above
+ // path. So the visited set is keyed on (RDD, belowRegular), NOT on the RDD alone -- keying on
+ // the RDD alone would let the first-reached context win and drop the other, missing a
+ // pipelined-below-regular dep (a wrongly-accepted job). A node is thus visited at most twice,
+ // keeping the cost O(graph) rather than O(K x graph). hasPipelined is set only above a regular
+ // boundary, matching the old walk (which stopped at boundaries): a below-boundary pipelined
+ // dep is the pipelinedBelow reject case, never a runnable group member.
+ val visited = new HashSet[(RDD[_], Boolean)]
+ val stack = new ListBuffer[(RDD[_], Boolean)]
+ stack += ((finalRDD, false))
+ while (stack.nonEmpty) {
+ val entry = stack.remove(0)
+ val rdd = entry._1
+ val belowRegular = entry._2
+ if (visited.add(entry)) {
+ rdd.dependencies.foreach {
+ case pd: PipelinedShuffleDependency[_, _, _] =>
+ if (belowRegular) pipelinedBelow = true else hasPipelined = true
+ stack.prepend((pd.rdd, belowRegular))
+ case sd: ShuffleDependency[_, _, _] =>
+ // A frontier boundary only when not already below one; descend with belowRegular set.
+ if (!belowRegular) regularBoundaries.getOrElseUpdate(sd.shuffleId, sd)
+ stack.prepend((sd.rdd, true))
+ case narrowDep =>
+ stack.prepend((narrowDep.rdd, belowRegular))
+ }
+ }
+ }
+
+ // The materialization check only matters for a pipelined job: `isUnsupportedMix` consumes
+ // `hasUnmaterializedRegularBoundary` only when `hasPipelined` is true (a pipelined shuffle
+ // below an unmaterialized regular boundary is the rejected shape). A job with no pipelined
+ // dependency -- every job on a feature-off deployment -- would otherwise pay K
+ // getNumAvailableOutputs lookups (a read-locked shuffleStatuses count) for a value never read,
+ // on the single-threaded event loop. So skip the loop entirely unless the walk saw a pipelined
+ // dependency; a non-pipelined job reports hasUnmaterialized = false (unused).
+ var hasUnmaterialized = false
+ if (hasPipelined) {
+ regularBoundaries.values.foreach { sd =>
+ // Materialized means every MAP partition has a registered output: the tracker counts map
+ // outputs, so compare against the producer RDD's partition count (matching how
+ // ShuffleMapStage.isAvailable derives completeness), not the reducer-side partitioner.
+ // This is a point-in-time check at job submission. If a materialized prefix's output were
+ // LOST after this classification but before the pipelined suffix finished (executor loss),
+ // the prefix would need to re-run while the gang holds all slots -- the very deadlock this
+ // shape check forbids. That is safe here for two reasons: (1) the only supported deployment
+ // is single-executor local mode, where executor loss does not occur in normal operation;
+ // and (2) if a FetchFailed did strip the prefix, handleTaskCompletion routes it to a
+ // WHOLE-GROUP abort (the failing stage is a pipelined group member), not a lone-stage
+ // resubmit into the held slots. A caller must rematerialize lost prefixes before retrying;
+ // the SQL channel rules exclude this mixed shape.
+ if (mapOutputTracker.getNumAvailableOutputs(sd.shuffleId) != sd.rdd.partitions.length) {
+ hasUnmaterialized = true
+ }
+ }
+ }
+ JobShuffleShape(hasPipelined, hasUnmaterialized, pipelinedBelow)
+ }
+
/**
* Reject a job that uses a pipelined shuffle in combination with a cluster feature that a
* pipelined group cannot support. Checked up front, before any stage is created, so a rejection
@@ -1446,6 +1594,9 @@ private[spark] class DAGScheduler(
* @param job The job whose state to cleanup.
*/
private def cleanupStateForJobAndIndependentStages(job: ActiveJob): Unit = {
+ if (job.hasPipelinedDependency && pipelinedManagerWantsLiveReduceHints) {
+ sc.env.pipelinedShuffleManager.endRun(job.jobId)
+ }
cleanupStagesForJob(job.jobId)
jobIdToActiveJob -= job.jobId
activeJobs -= job
@@ -1803,20 +1954,167 @@ private[spark] class DAGScheduler(
* pipelined producer, whose consumers may run concurrently with it. Callers that need the
* producer/consumer relationship check `child.parents.contains(stage)` separately.
*/
+ /**
+ * Whether the configured pipelined manager consumes the driver's live-reduce-partition hint and
+ * per-run epoch (see `PipelinedShuffleManager.supportsLiveReducePartitionHints`). False for the
+ * RPC streaming transport, whose writer reads neither -- so for a Real-Time Mode job the
+ * scheduler skips computing and stamping them, and skips the partial-read abort whose remedy
+ * (disabling the batch SQL flag) does not apply to it.
+ */
+ private def pipelinedManagerWantsLiveReduceHints: Boolean = {
+ val mgr = sc.env.pipelinedShuffleManager
+ mgr != null && mgr.supportsLiveReducePartitionHints
+ }
+
private def isPipelinedProducer(stage: Stage): Boolean = stage match {
case m: ShuffleMapStage => m.shuffleDep.isInstanceOf[PipelinedShuffleDependency[_, _, _]]
case _ => false
}
/**
- * The total concurrent-task demand of an all-pipelined job, computed from the RDD graph BEFORE
- * any stage is created (so a rejection based on it leaves no partial scheduler state, exactly as
- * the barrier slot check and the speculation/DA reject do). Because a job is either all-regular
- * or all-pipelined, an all-pipelined job's whole stage graph is one pipelined group; its members
- * are the final result stage plus every pipelined producer. Each member's task count is its RDD's
- * partition count (`rdd.partitions.length`), matching how `createShuffleMapStage` derives
- * `numTasks`. `finalNumPartitions` is the result stage's task count (the number of partitions the
- * job runs, which may be a subset of `finalRDD.partitions`).
+ * The set of reduce partitions of `targetShuffleId` that the result stage actually reads, given
+ * the result RDD and the subset of ITS partitions the job runs (`liveResultPartitions`). Used to
+ * tell a pipelined producer which of its reduce partitions have a consumer, so it can drop the
+ * rest (a partial read -- LIMIT / executeTake -- runs only some result partitions).
+ *
+ * Walk from `rdd` toward the target shuffle, threading the live partition-index set. Each hop is
+ * either a `NarrowDependency` -- map the live set through its generic `getParents(p)` contract
+ * (OneToOne is identity, RangeDependency is an offset, a coalesce dependency is a range, etc.;
+ * no per-operator special-casing) and recurse into the parent -- or the target
+ * `ShuffleDependency` itself, at which point the reader RDD's partition index equals the reduce
+ * partition index (the pipelined reader always uses a width-1 CoalescedPartitionSpec(i, i+1);
+ * the count check below guards against a future offset spec). A node with several dependencies
+ * (a join's ZippedPartitionsRDD) contributes from every branch that reaches the target shuffle.
+ *
+ * Returns None if an edge cannot be mapped (a non-target ShuffleDependency in the path -- which a
+ * result-feeding producer never has, since pipelined-below-regular is rejected earlier -- or a
+ * reader RDD whose partition count does not match the shuffle's, i.e. a non-identity spec).
+ * The caller treats None as "cannot determine": safe to ignore for a full read, fail-fast for a
+ * partial read.
+ */
+ private def liveReduceSet(
+ rdd: RDD[_], liveResultPartitions: Set[Int], targetShuffleId: Int): Option[Set[Int]] = {
+ // Precompute, ONCE, which RDDs reach the target shuffle (memoized, iterative -- see
+ // rddReachesShuffle). The walk below queries this map instead of re-walking the subtree per
+ // branch per level, which was O(n^2) on a deep narrow chain and exponential on a narrow
+ // diamond (a shared ancestor reached by several branches, e.g. a self-join's zip).
+ val reaches = rddReachesShuffle(rdd, targetShuffleId)
+
+ // Explicit worklist (not recursion) so a chain thousands of operators deep does not overflow
+ // the dag-scheduler event-loop's stack. The work unit is (rdd -> the live subset of ITS
+ // partition indices on the path from the result RDD). A node reachable via several branches
+ // with different live subsets is processed with the UNION of them: getParents distributes over
+ // union (union(A,B).flatMap(f) == union(A.flatMap(f), B.flatMap(f))), so merging the live sets
+ // at a node and mapping once equals the recursion's per-branch map + final union. Re-enqueue a
+ // node only when its accumulated set actually GREW (set inequality, not size -- two distinct
+ // sets can share a size); sets grow monotonically in a finite index domain, so it converges.
+ val liveAt = new HashMap[RDD[_], Set[Int]]
+ val worklist = new ListBuffer[RDD[_]]
+ val resultReduce = scala.collection.mutable.Set.empty[Int]
+ var unmappable = false
+ liveAt(rdd) = liveResultPartitions
+ worklist += rdd
+ while (worklist.nonEmpty && !unmappable) {
+ val cur = worklist.remove(0)
+ val live = liveAt(cur)
+ // A direct target dependency wins (matches the old collectFirst): the reader RDD's live
+ // partition indices ARE the reduce indices, guarded by the partition-count identity check.
+ cur.dependencies.collectFirst {
+ case sd: ShuffleDependency[_, _, _] if sd.shuffleId == targetShuffleId => sd
+ } match {
+ case Some(sd) =>
+ // Ask the reader RDD which reduce partition each live partition index reads, rather than
+ // assuming index == reduce id when the counts happen to match: a reader that skew-splits
+ // one reducer and coalesces two others has the same count and a different mapping, and
+ // guessing wrong here is not a hang but SILENTLY DROPPED records (the producer skips
+ // every partition outside the set it is told about). A reader that cannot name a single
+ // reduce partition for some live index makes the whole mapping uncomputable, which the
+ // caller treats as "keep everything live".
+ cur match {
+ case mapping: ShuffleReducePartitionMapping =>
+ val mapped = live.map(mapping.reducePartitionIndex)
+ if (mapped.exists(_.isEmpty)) unmappable = true
+ else resultReduce ++= mapped.flatten
+ case _ =>
+ // An unknown reader RDD: no way to establish the mapping, so do not risk dropping.
+ unmappable = true
+ }
+ case None =>
+ // Follow every dependency whose subtree reaches the target, mapping the live set through
+ // that (narrow) dependency's getParents. A reaching non-narrow edge (should not occur --
+ // reachability does not cross a non-target shuffle) is unmappable. A node that reaches
+ // nothing is a dead end -> unmappable (matches the old branches.isEmpty => None).
+ val reachingDeps = cur.dependencies.filter {
+ case nd: NarrowDependency[_] => reaches.getOrElse(nd.rdd, false)
+ case _ => false
+ }
+ if (reachingDeps.isEmpty) {
+ unmappable = true
+ } else {
+ reachingDeps.foreach { case nd: NarrowDependency[_] =>
+ val parentLive = live.flatMap(nd.getParents)
+ val merged = liveAt.get(nd.rdd).map(_ ++ parentLive).getOrElse(parentLive)
+ if (!liveAt.get(nd.rdd).contains(merged)) {
+ liveAt(nd.rdd) = merged
+ worklist += nd.rdd
+ }
+ }
+ }
+ }
+ }
+ if (unmappable) None else Some(resultReduce.toSet)
+ }
+
+ /**
+ * Whether the RDD graph rooted at `startRdd` reaches `targetShuffleId`: some dependency IS the
+ * target shuffle, or some NarrowDependency's rdd reaches it. A non-target ShuffleDependency does
+ * NOT propagate reachability (a regular boundary is not crossed). Memoized and computed
+ * iteratively (a two-phase post-order over an explicit stack) so a shared ancestor is visited
+ * once and a deep chain does not overflow the stack. Returns the full memo so a caller walking
+ * the same graph can query any node.
+ */
+ private def rddReachesShuffle(
+ startRdd: RDD[_], targetShuffleId: Int): HashMap[RDD[_], Boolean] = {
+ val memo = new HashMap[RDD[_], Boolean]
+ // Each stack entry is (rdd, childrenDone): the first visit pushes the node back as done and
+ // pushes its unvisited narrow-dependency parents; the done visit computes from the (now
+ // memoized) parents.
+ val stack = new ListBuffer[(RDD[_], Boolean)]
+ stack.prepend((startRdd, false))
+ while (stack.nonEmpty) {
+ val entry = stack.remove(0)
+ val cur = entry._1
+ val childrenDone = entry._2
+ if (childrenDone) {
+ memo(cur) = cur.dependencies.exists {
+ case sd: ShuffleDependency[_, _, _] => sd.shuffleId == targetShuffleId
+ case nd: NarrowDependency[_] => memo.getOrElse(nd.rdd, false)
+ case _ => false
+ }
+ } else if (!memo.contains(cur)) {
+ // Mark visited pre-emptively (guards a diamond from being scheduled twice) then compute on
+ // the done pass; the value is overwritten there.
+ memo(cur) = false
+ stack.prepend((cur, true))
+ cur.dependencies.foreach {
+ case nd: NarrowDependency[_] if !memo.contains(nd.rdd) => stack.prepend((nd.rdd, false))
+ case _ =>
+ }
+ }
+ }
+ memo
+ }
+
+ /**
+ * The total concurrent-task demand of a pipelined job's group, computed from the RDD graph
+ * BEFORE any stage is created (so a rejection based on it leaves no partial scheduler state,
+ * exactly as the barrier slot check and the speculation/DA reject do). A pipelined job's group
+ * is the final result stage plus every pipelined producer; a materialized-prefix mixed job (see
+ * JobShuffleShape) contributes no additional members, since its regular prefix never re-runs
+ * and (by the shape check) has no pipelined shuffle below it. Each member's task count is its
+ * RDD's partition count (`rdd.partitions.length`), matching how `createShuffleMapStage` derives
+ * `numTasks`. `finalNumPartitions` is the result stage's task count (the number of partitions
+ * the job runs, which may be a subset of `finalRDD.partitions`).
*
* Count each producer once per SHUFFLE ID, matching what execution schedules: one stage is
* created per shuffle ID (`getOrCreateShuffleMapStage`), not per dependency edge. A fan-out or
@@ -1834,7 +2132,8 @@ private[spark] class DAGScheduler(
if (countedShuffleIds.add(pd.shuffleId)) {
demand += pd.rdd.partitions.length
}
- case _ => // regular/narrow deps do not occur in an all-pipelined job's group
+ case _ => // narrow deps are not boundaries; a regular dep is a materialized prefix
+ // boundary (JobShuffleShape), whose stages never run and are not members
}
rdd.dependencies.foreach(dep => enqueue(dep.rdd))
}
@@ -1842,14 +2141,14 @@ private[spark] class DAGScheduler(
}
/**
- * Up-front gang admission for an all-pipelined job, checked BEFORE any stage exists. Because a
- * job is either all-regular or all-pipelined (mixed jobs are already rejected), an all-pipelined
- * job's whole stage graph is one pipelined group with no regular prefix, so its full demand is
- * known up front and the group is ready to admit immediately. Checking here (rather than in
- * `submitStage` once a producer is already running) is true all-or-nothing gang admission: the
- * whole group is admitted, or the job is failed before any member runs, so a member is never left
- * running while a sibling cannot get slots -- and, like the barrier slot check, a rejection
- * leaves no partial scheduler state.
+ * Up-front gang admission for a pipelined job, checked BEFORE any stage exists. A pipelined
+ * job's runnable stage graph is one pipelined group (an unsupported mix is already rejected,
+ * and a materialized-prefix mixed job's regular stages never run -- see JobShuffleShape), so
+ * its full demand is known up front and the group is ready to admit immediately. Checking here
+ * (rather than in `submitStage` once a producer is already running) is true all-or-nothing gang
+ * admission: the whole group is admitted, or the job is failed before any member runs, so a
+ * member is never left running while a sibling cannot get slots -- and, like the barrier slot
+ * check, a rejection leaves no partial scheduler state.
*
* Free-slot accounting: demand vs. total capacity (`maxNumConcurrentTasks` for the default
* profile -- a group is required to be single-profile) minus what OTHER work (other jobs) has
@@ -2136,26 +2435,30 @@ private[spark] class DAGScheduler(
return
}
- // A job must be either ALL-regular or ALL-pipelined, not a mix: a job whose shuffle graph
- // combines a pipelined shuffle with a regular one is rejected up front (before any stage is
- // created). Restricting to a single kind makes an all-pipelined job's whole stage graph one
- // pipelined group with no regular prefix, so gang admission is decided up front (see the slot
- // check below) rather than mid-DAG once a producer is already running.
- val (hasPipelined, hasRegular) = classifyJobShuffleKinds(finalRDD)
- if (hasPipelined && hasRegular) {
+ // A job's shuffle graph must be all-regular, all-pipelined, or the materialized-prefix mixed
+ // shape (every regular boundary fully materialized and below the pipelined suffix -- see
+ // JobShuffleShape). Anything else is rejected up front (before any stage is created): an
+ // unmaterialized regular stage would have to run while gang-admitted producers hold slots
+ // blocked on transport backpressure, which admission does not account for and can deadlock.
+ val shape = classifyJobShuffleShape(finalRDD)
+ val hasPipelined = shape.hasPipelined
+ if (shape.isUnsupportedMix) {
logWarning(log"Rejecting job ${MDC(JOB_ID, jobId)}: a job mixing a pipelined shuffle with " +
- log"a regular shuffle is not supported")
+ log"a regular shuffle is only supported when every regular shuffle is a materialized " +
+ log"prefix below the pipelined shuffles")
listener.jobFailed(new SparkException(
"A job that mixes a pipelined shuffle dependency with a regular shuffle dependency is " +
- "not supported: a job must be either all-regular or all-pipelined."))
+ "only supported when every regular shuffle is a fully-materialized prefix below the " +
+ "pipelined shuffles; otherwise a job must be either all-regular or all-pipelined."))
return
}
- // Gang admission for an all-pipelined job: the whole stage graph is one pipelined group, so
- // check up front (before any stage is created) that the cluster can run the entire group
- // concurrently. If it cannot fit, fail the job now -- no partial scheduler state, and no member
- // ever left running while a sibling waits on slots (true all-or-nothing gang admission). Inert
- // for a regular job (no pipelined dependency).
+ // Gang admission for a pipelined job: the runnable stage graph is one pipelined group (a
+ // materialized prefix's stages never run), so check up front (before any stage is created)
+ // that the cluster can run the entire group concurrently. If it cannot fit, fail the job now
+ // -- no partial scheduler state, and no member ever left running while a sibling waits on
+ // slots (true all-or-nothing gang admission). Inert for a regular job (no pipelined
+ // dependency).
if (hasPipelined && rejectUnadmittablePipelinedGroup(jobId, finalRDD, partitions, listener)) {
return
}
@@ -2229,8 +2532,24 @@ private[spark] class DAGScheduler(
// Job submitted, clear internal data.
barrierJobIdToNumTasksCheckFailures.remove(jobId)
+ // For a pipelined job, stamp the per-run epoch (the jobId) into the job's properties BEFORE
+ // creating the ActiveJob, so submitMissingTasks -- which clones jobIdToActiveJob(jobId)
+ // .properties per stage -- carries the SAME epoch to every stage's tasks. Both the producer
+ // (writer) and the consumer (reader) of the one gang belong to this job, so both read one
+ // value; a different run is a different job, hence a different epoch, which keys the
+ // in-process channel rendezvous per run (see SPARK_PIPELINED_RUN_EPOCH). Copy the caller's
+ // Properties rather than mutating it. Inert for a non-pipelined job (property never set,
+ // never read).
+ val jobProperties =
+ if (hasPipelined && pipelinedManagerWantsLiveReduceHints) {
+ val p = Utils.cloneProperties(if (properties == null) new Properties() else properties)
+ p.setProperty(SparkContext.SPARK_PIPELINED_RUN_EPOCH, jobId.toString)
+ p
+ } else {
+ properties
+ }
// Pass hasPipelined (computed above) into the job; see ActiveJob.hasPipelinedDependency.
- val job = new ActiveJob(jobId, finalStage, callSite, listener, artifacts, properties,
+ val job = new ActiveJob(jobId, finalStage, callSite, listener, artifacts, jobProperties,
hasPipelinedDependency = hasPipelined)
clearCacheLocs()
logInfo(
@@ -2255,6 +2574,9 @@ private[spark] class DAGScheduler(
listenerBus.post(
SparkListenerJobStart(job.jobId, jobSubmissionTime, stageInfos,
Utils.cloneProperties(properties)))
+ if (hasPipelined && pipelinedManagerWantsLiveReduceHints) {
+ sc.env.pipelinedShuffleManager.startRun(jobId)
+ }
submitStage(finalStage)
}
@@ -2704,6 +3026,67 @@ private[spark] class DAGScheduler(
.getOrElse(new Properties())
addPySparkConfigsToProperties(stage, properties)
+ // For a pipelined PRODUCER stage, tell its tasks which of its reduce partitions the job
+ // actually reads. The in-process channel writer drops records routed to partitions no
+ // consumer will drain -- otherwise a partial-read job (LIMIT / executeTake reads a subset)
+ // fills the unread partitions' bounded queues and deadlocks the writer. The result stage
+ // is created before submitStage, so its partitions are known here.
+ //
+ // The live set is per-SHUFFLE-EDGE, not per-job: it is the reduce partitions the consumer of
+ // THIS shuffle reads. liveReduceSet computes it by walking the narrow chain from the result
+ // RDD down to this shuffle, threading the read partition subset through each dependency's
+ // getParents. A MIDDLE pipelined exchange in a chain (e.g. a subquery's hash below a
+ // single-partition agg) is consumed by another map stage that reads ALL its partitions, and
+ // its shuffle is not narrow-reachable from the result RDD (an intervening shuffle blocks the
+ // walk), so liveReduceSet returns None and the property is left unset -- fully live -- which
+ // is correct. See the None handling below for the fail-fast case.
+ stage match {
+ case sms: ShuffleMapStage
+ if isPipelinedProducer(stage) && pipelinedManagerWantsLiveReduceHints =>
+ val resultStage = jobIdToActiveJob.get(jobId).map(_.finalStage)
+ .collect { case rs: ResultStage => rs }
+ resultStage.foreach { rs =>
+ // Tell this pipelined producer's tasks which of ITS reduce partitions the job's readers
+ // will actually drain, so the writer can drop records routed to partitions no consumer
+ // reads (a partial read -- LIMIT / executeTake -- runs only a subset of the result
+ // stage's partitions; feeding the rest fills their bounded queues and deadlocks the
+ // writer). This is the reduce-partition set the result stage's partition subset maps to
+ // through the narrow chain down to this shuffle (see liveReduceSet).
+ liveReduceSet(rs.rdd, rs.partitions.toSet, sms.shuffleDep.shuffleId) match {
+ case Some(reduceSet) =>
+ properties.setProperty(
+ SparkContext.SPARK_PIPELINED_LIVE_REDUCE_PARTITIONS,
+ reduceSet.toArray.sorted.mkString(","))
+ case None =>
+ // liveReduceSet is None in two very different situations:
+ //
+ // (a) the result stage does NOT narrow-reach THIS shuffle -- a MIDDLE pipelined
+ // exchange in a chain, whose shuffle sits below an intervening shuffle the
+ // narrow walk cannot cross. Its consumer (the next map stage) reads ALL of its
+ // reduce partitions, so it must stay fully live. Leave the property unset
+ // regardless of partial vs full read -- never fail here.
+ //
+ // (b) the result stage DOES narrow-reach this shuffle but the mapping is
+ // uncomputable (a non-identity reader spec, or an unrecognized narrow edge on
+ // the reaching path). For a FULL read that is safe (all partitions get a
+ // reader, all-live drops nothing). For a PARTIAL read it is the one unsafe
+ // case: the writer would feed reduce partitions with no reader and hang.
+ //
+ // Only (b) with a partial read fails fast; every other None leaves it fully live.
+ val reaches =
+ rddReachesShuffle(rs.rdd, sms.shuffleDep.shuffleId).getOrElse(rs.rdd, false)
+ val partialRead = rs.partitions.length < rs.rdd.partitions.length
+ if (reaches && partialRead) {
+ abortStage(sms, "Pipelined shuffle cannot determine the live reduce-partition " +
+ "set for a partial read (LIMIT/take) through this plan shape; disable " +
+ "spark.sql.shuffle.localPipelined.enabled for this query.", None)
+ return
+ }
+ }
+ }
+ case _ =>
+ }
+
runningStages += stage
// SparkListenerStageSubmitted should be posted before testing whether tasks are
// serializable. If tasks are not serializable, a SparkListenerStageCompleted event
diff --git a/core/src/main/scala/org/apache/spark/shuffle/ShuffleManager.scala b/core/src/main/scala/org/apache/spark/shuffle/ShuffleManager.scala
index df47f7552688..e59cf8613f46 100644
--- a/core/src/main/scala/org/apache/spark/shuffle/ShuffleManager.scala
+++ b/core/src/main/scala/org/apache/spark/shuffle/ShuffleManager.scala
@@ -129,7 +129,63 @@ private[spark] trait BlockingShuffleManager extends ShuffleManager {
* has no [[ShuffleBlockResolver]]. [[org.apache.spark.shuffle.streaming.StreamingShuffleManager]]
* is the built-in implementation.
*/
-private[spark] trait PipelinedShuffleManager extends ShuffleManager
+private[spark] trait PipelinedShuffleManager extends ShuffleManager {
+ /**
+ * Whether this manager relies on a `StreamingShuffleOutputTracker` to discover writer task
+ * locations. The RPC streaming transport needs it (writers publish their host/port; readers
+ * look them up to open connections). An in-process transport that finds writer and reader
+ * within the same JVM does not, and returns false so `SparkEnv` skips creating the tracker
+ * and the scheduler skips registering the shuffle with it. Defaults to true so the built-in
+ * streaming manager is unaffected.
+ */
+ def usesStreamingShuffleOutputTracker: Boolean = true
+
+ /**
+ * Whether this manager's writer hands record OBJECTS to a concurrently-running consumer, so
+ * each record must be detached from any producer-reused buffer before `write` sees it (for a
+ * SQL row: `InternalRow.copy()`, done before constructing the shuffle dependency). A transport
+ * that
+ * serializes records promptly -- the RPC streaming manager -- detaches by serializing and
+ * must NOT pay an extra per-row copy on its hot path; that is the default. The in-process
+ * channel transport shares object references across threads and overrides this to true.
+ */
+ def requiresDetachedRecords: Boolean = false
+
+ /**
+ * Whether this manager's writer consumes the driver's live-reduce-partition hint -- the set of
+ * reduce partitions a partial read (LIMIT / executeTake) will actually drain, stamped into the
+ * producer's task properties as `SPARK_PIPELINED_LIVE_REDUCE_PARTITIONS`, plus the per-run epoch
+ * `SPARK_PIPELINED_RUN_EPOCH` that keys its rendezvous.
+ *
+ * Only a transport whose writer would BLOCK on a partition nobody drains needs the hint: the
+ * in-process channel hands batches across a bounded queue, so feeding a reader-less partition
+ * fills it and parks the writer forever. A transport that does not block that way (the RPC
+ * streaming shuffle, whose writer never reads either property) returns false, and the scheduler
+ * then skips computing and stamping the hint entirely -- leaving the Real-Time Mode path exactly
+ * as it is without this feature, rather than paying for a hint nobody reads and risking an abort
+ * whose remedy does not apply to it.
+ */
+ def supportsLiveReducePartitionHints: Boolean = false
+
+ /** Open a job's transport epoch before submitting any of its tasks. */
+ def startRun(epoch: Int): Unit = {}
+
+ /** Release a job's transport state, including on cancellation or failure. */
+ def endRun(epoch: Int): Unit = {}
+
+ /**
+ * Whether this manager currently holds driver-side cleanup state for `shuffleId`.
+ *
+ * A manager that keeps NO output tracker (an in-process transport) has its shuffles in neither
+ * output tracker, so the `ContextCleaner` cannot tell one of them apart from an already-cleaned
+ * regular shuffle by tracker membership; it asks here instead, and only frees what a manager
+ * actually holds. Answer from the state that would leak -- not from a registration record, which
+ * an unregister-before-run sequence drops while the state itself is recreated lazily when the job
+ * finally runs. Defaults to false: a manager whose shuffles ARE in an output tracker is found
+ * that way and never needs this.
+ */
+ def holdsShuffle(shuffleId: Int): Boolean = false
+}
/**
* Utility companion object to create a ShuffleManager given a spark configuration.
diff --git a/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleRendezvous.scala b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleRendezvous.scala
new file mode 100644
index 000000000000..d02f0f7c278e
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleRendezvous.scala
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.shuffle.local.pipelined
+
+import java.util.concurrent.{ConcurrentHashMap, LinkedBlockingQueue}
+
+import org.apache.spark.{SparkContext, TaskContext, TaskKilledException}
+
+/**
+ * Bounded in-JVM channels, one per (shuffleId, job epoch, reduce partition). All map tasks
+ * share a partition's queue with its single reader. Values are record batches or EndOfStream.
+ * Each run uses separate state so tasks from an aborted run cannot reach a later run's queues.
+ * The scheduler opens the epoch before launching tasks and closes it when the job ends.
+ */
+private[spark] object ChannelShuffleRendezvous {
+
+ /**
+ * Marker placed on a queue by each map task when it finishes writing to that reduce
+ * partition. A reader stops once it has seen one marker per map task.
+ */
+ val EndOfStream: AnyRef = new AnyRef
+
+ /** The job epoch propagated to both sides of a channel; standalone tests use epoch 0. */
+ def epochOf(tc: TaskContext): Int =
+ Option(tc)
+ .flatMap(t => Option(t.getLocalProperty(SparkContext.SPARK_PIPELINED_RUN_EPOCH)))
+ .map(_.toInt)
+ .getOrElse(0)
+
+ // Index by shuffle first so cleanup inspects only the requested shuffle.
+ private val queues =
+ new ConcurrentHashMap[Int, ConcurrentHashMap[(Int, Int), LinkedBlockingQueue[AnyRef]]]()
+
+ // (epoch, reducePartitionId) keys, per shuffleId, whose reader has departed (its reduce task
+ // finished) and will drain no more. A writer stops feeding an abandoned partition and drops the
+ // rest. This covers the LIVE-partition early-stop case (e.g. a LIMIT reader that pulled enough
+ // and quit): without it the writer fills the partition's bounded queue and blocks forever.
+ private val abandoned =
+ new ConcurrentHashMap[Int, java.util.Set[(Int, Int)]]()
+
+ // Only active jobs are retained. Access and teardown serialize so a cancelled task cannot
+ // recreate registered state after endRun. A task already holding a queue may finish against
+ // that detached queue, but cannot affect a later epoch.
+ private val activeRuns = ConcurrentHashMap.newKeySet[Int]()
+
+ def startRun(epoch: Int): Unit = synchronized {
+ activeRuns.add(epoch)
+ }
+
+ def endRun(epoch: Int): Unit = synchronized {
+ activeRuns.remove(epoch)
+ val queueIterator = queues.entrySet().iterator()
+ while (queueIterator.hasNext) {
+ val entry = queueIterator.next()
+ entry.getValue.keySet().removeIf(_._1 == epoch)
+ if (entry.getValue.isEmpty) queueIterator.remove()
+ }
+ val markIterator = abandoned.entrySet().iterator()
+ while (markIterator.hasNext) {
+ val entry = markIterator.next()
+ entry.getValue.removeIf(_._1 == epoch)
+ if (entry.getValue.isEmpty) markIterator.remove()
+ }
+ }
+
+ private def runHasEnded(epoch: Int): Boolean =
+ TaskContext.get() != null && !activeRuns.contains(epoch)
+
+ /**
+ * Per-queue capacity in BATCHES (not rows), the backpressure bound and the heap-residency
+ * knob (see spark.shuffle.channel.queueCapacity). Set once by the channel manager at
+ * construction from that conf; defaults to 64 (with the default 1024-row batch, ~64K rows per
+ * reduce partition in flight) until a manager sets it. `@volatile` because the manager sets it
+ * on the driver while writer/reader threads read it.
+ */
+ @volatile private var capacity = 64
+
+ /** Set the per-queue capacity in batches. Called by the channel manager from its conf. */
+ private[pipelined] def setCapacity(batches: Int): Unit = { capacity = batches }
+
+ /** The queue for one `(shuffleId, epoch, reducePartitionId)`, created on first access. */
+ def queue(
+ shuffleId: Int,
+ epoch: Int,
+ reducePartitionId: Int): LinkedBlockingQueue[AnyRef] = {
+ def checkRun(): Unit = {
+ if (runHasEnded(epoch)) {
+ throw new TaskKilledException("Pipelined shuffle run has ended")
+ }
+ }
+ checkRun()
+ val existing = queues.get(shuffleId)
+ if (existing != null) {
+ val q = existing.get((epoch, reducePartitionId))
+ if (q != null) return q
+ }
+ synchronized {
+ checkRun()
+ val perShuffle = queues.computeIfAbsent(
+ shuffleId, _ => new ConcurrentHashMap[(Int, Int), LinkedBlockingQueue[AnyRef]]())
+ perShuffle.computeIfAbsent(
+ (epoch, reducePartitionId), _ => new LinkedBlockingQueue[AnyRef](capacity))
+ }
+ }
+
+ /** Whether this reduce partition's reader has departed for this run (see [[abandon]]). */
+ def isAbandoned(shuffleId: Int, epoch: Int, reducePartitionId: Int): Boolean = {
+ val marks = abandoned.get(shuffleId)
+ runHasEnded(epoch) || (marks != null && marks.contains((epoch, reducePartitionId)))
+ }
+
+ /**
+ * Mark a reduce partition abandoned: its reader task has finished and will drain no more.
+ * Called from the reader's task-completion listener. Besides recording the flag (so the
+ * writer stops feeding this partition), it DRAINS the queue to unblock a writer already
+ * parked in a full-queue `put`: clearing capacity lets that put return, after which the
+ * writer's next abandoned-check stops it cooperatively (no reliance on interrupt).
+ */
+ def abandon(shuffleId: Int, epoch: Int, reducePartitionId: Int): Unit = synchronized {
+ if (runHasEnded(epoch)) return
+ abandoned
+ .computeIfAbsent(shuffleId, _ => ConcurrentHashMap.newKeySet[(Int, Int)]())
+ .add((epoch, reducePartitionId))
+ val perShuffle = queues.get(shuffleId)
+ if (perShuffle != null) {
+ val q = perShuffle.get((epoch, reducePartitionId))
+ if (q != null) q.clear()
+ }
+ }
+
+ /**
+ * Release idle state on unregister. SQL cleanup can run while another action still owns a
+ * live epoch; removing its queues would disconnect its readers and writers. endRun releases
+ * those entries when their owner finishes.
+ */
+ def removeShuffle(shuffleId: Int): Unit = synchronized {
+ if (activeRuns.isEmpty) {
+ queues.remove(shuffleId)
+ abandoned.remove(shuffleId)
+ return
+ }
+ val perShuffle = queues.get(shuffleId)
+ if (perShuffle != null) {
+ perShuffle.keySet().removeIf(key => !activeRuns.contains(key._1))
+ if (perShuffle.isEmpty) queues.remove(shuffleId)
+ }
+ val marks = abandoned.get(shuffleId)
+ if (marks != null) {
+ marks.removeIf(key => !activeRuns.contains(key._1))
+ if (marks.isEmpty) abandoned.remove(shuffleId)
+ }
+ }
+
+ /** Whether there is transport state for the cleaner to release. */
+ def holdsShuffle(shuffleId: Int): Boolean = {
+ val perShuffle = queues.get(shuffleId)
+ val marks = abandoned.get(shuffleId)
+ (perShuffle != null && !perShuffle.isEmpty) || (marks != null && !marks.isEmpty)
+ }
+
+ /**
+ * Drop every queue and every abandoned mark. Called when the owning manager stops (i.e. the
+ * SparkContext stops): this object is process-wide and epochs (jobIds) restart at 0 in a new
+ * SparkContext, so without this a fresh context in the same JVM -- a test fork, a REPL/notebook
+ * restart -- could collide with rows or end-of-stream markers the previous context left behind
+ * under the same (shuffleId, epoch, reducePartitionId). Also the reset hook used by tests
+ * between contexts.
+ */
+ private[spark] def clear(): Unit = synchronized {
+ activeRuns.clear()
+ queues.clear()
+ abandoned.clear()
+ }
+
+ /** Visible for testing: number of live queues. */
+ private[pipelined] def numQueuesForTesting: Int = {
+ var n = 0
+ val it = queues.values().iterator()
+ while (it.hasNext) n += it.next().size()
+ n
+ }
+}
diff --git a/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleWriterReader.scala b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleWriterReader.scala
new file mode 100644
index 000000000000..c8ab80d6d9c3
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/ChannelShuffleWriterReader.scala
@@ -0,0 +1,359 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.shuffle.local.pipelined
+
+import java.util.Arrays
+
+import org.apache.spark.{SparkContext, SparkEnv, TaskContext}
+import org.apache.spark.scheduler.MapStatus
+import org.apache.spark.shuffle.{BaseShuffleHandle, ShuffleReader, ShuffleReadMetricsReporter, ShuffleWriteMetricsReporter, ShuffleWriter}
+
+/**
+ * Map-side of the in-process pipelined shuffle. Each input record is routed to the reduce
+ * partition its key hashes to and accumulated in a per-partition batch; a FULL batch (an
+ * `Array[AnyRef]` of `batchSize` pairs) is pushed onto that partition's shared queue in one
+ * queue operation (see [[ChannelShuffleRendezvous]]) -- the consumer stage, running
+ * concurrently, drains it batch by batch. No serialization, no disk, no network.
+ *
+ * Batching is what makes the transport viable for large unaggregated shuffles: the queue
+ * costs a lock acquisition per operation (~hundreds of ns under producer/consumer
+ * contention), so handing rows across one at a time costs that PER ROW -- measured at ~19x
+ * slower than a regular shuffle on a 20M-row repartition. Batching divides the lock traffic
+ * by `batchSize`, the same lesson as any object-batch transport. A batch
+ * array is handed off to the consumer and never touched again by the writer (a fresh array
+ * is allocated after each put), so ownership transfer is clean across threads.
+ */
+private[spark] class ChannelShuffleWriter[K, V](
+ handle: BaseShuffleHandle[K, V, _],
+ mapId: Long,
+ batchSize: Int,
+ writeMetrics: ShuffleWriteMetricsReporter)
+ extends ShuffleWriter[K, V] with org.apache.spark.internal.Logging {
+
+ require(batchSize > 0, s"batchSize must be positive, got $batchSize")
+
+ private val dep = handle.dependency
+ private val partitioner = dep.partitioner
+ private val numPartitions = partitioner.numPartitions
+ private val shuffleId = handle.shuffleId
+
+ // Per-run epoch (the jobId), read from the job-level local property the DAGScheduler set for a
+ // pipelined job. The reader of this gang reads the SAME value, so both address the same
+ // per-run queues in the process-wide rendezvous; a re-run of this shuffleId is a different job
+ // and gets a different epoch, keeping its queues physically separate. Absent (a core-RDD test
+ // path that never sets it, and never re-runs a shuffleId concurrently) means epoch 0.
+ private val runEpoch = ChannelShuffleRendezvous.epochOf(TaskContext.get())
+
+ // The reduce partitions this job actually reads, from the producer stage's task property
+ // (set by the DAGScheduler from the result stage's partitions). A record routed to a
+ // partition NOT in this set has no consumer -- putting it would fill that partition's
+ // bounded queue and, because the writer interleaves all partitions on one thread, block
+ // the writer before it can feed even the read partitions or emit their end-of-stream,
+ // deadlocking the job. So such records are dropped. Absent property (None) means every
+ // partition is live (the normal full-read case: collect, count, a full-partition job) and
+ // nothing is dropped.
+ private val liveReducePartitions: Option[Set[Int]] =
+ Option(TaskContext.get())
+ .flatMap(tc =>
+ Option(tc.getLocalProperty(SparkContext.SPARK_PIPELINED_LIVE_REDUCE_PARTITIONS)))
+ .map(_.split(",").filter(_.nonEmpty).map(_.toInt).toSet)
+
+ // Per-partition liveness, precomputed ONCE from the (static) live set: true iff a consumer
+ // reads this reduce partition at all. This is the hot-path gate -- checked per input record --
+ // so it is a plain Array[Boolean] load, not a boxed Set lookup: on a large repartition the
+ // per-record path must not allocate (the transport's whole point is amortizing per-row cost).
+ // Absent property means every partition is live. The OTHER half of "worth writing" --
+ // abandonment, which happens at runtime when a reader departs early (e.g. LIMIT) -- is dynamic
+ // and is checked where it matters (at hand-off, in putUnlessAbandoned), NOT per record:
+ // accumulating a few more rows into an in-memory batch for a since-abandoned partition is
+ // harmless because that batch is never put (putUnlessAbandoned drops it).
+ private val liveMask: Array[Boolean] = {
+ val mask = Array.fill(numPartitions)(true)
+ liveReducePartitions.foreach { live =>
+ var p = 0
+ while (p < numPartitions) { mask(p) = live.contains(p); p += 1 }
+ }
+ mask
+ }
+
+ // Hand a batch to a partition's queue, but do NOT block forever if its reader departs:
+ // poll with a short timeout and bail out the moment the partition becomes abandoned. This
+ // is the cooperative unblock for the early-stop case -- abandon() also drains the queue to
+ // release a parked put, and this re-check ensures the writer then stops rather than
+ // re-filling. Returns false if the partition was abandoned before the batch was accepted.
+ // On a successful hand-off, records the batch's records and the time spent (including any
+ // backpressure wait) against the write metrics; a dropped/abandoned batch counts nothing,
+ // since those records are never shuffled out. `records` is the number of pairs in `batch`
+ // (a full batch is `batchSize`, a trimmed tail is shorter; the end-of-stream marker is 0).
+ private def putUnlessAbandoned(pid: Int, batch: AnyRef, records: Int): Boolean = {
+ val q = ChannelShuffleRendezvous.queue(shuffleId, runEpoch, pid)
+ val start = System.nanoTime()
+ while (!ChannelShuffleRendezvous.isAbandoned(shuffleId, runEpoch, pid)) {
+ // Wake on a task kill even without thread interruption. `isAbandoned` is set only by a
+ // reduce task that actually STARTED (its completion listener); if the reader for pid never
+ // started -- the group aborts while this producer is already filling queues (an
+ // unserializable consumer task, an early failure of another member, a job cancel) -- the
+ // mark never appears and this offer loop would park forever, pinning the executor slot
+ // (spark.job.interruptOnCancel defaults to false, so the kill does not interrupt the
+ // thread). Checking the TaskContext interrupt flag each cycle is the symmetric escape to
+ // the reader's takeItem.
+ Option(TaskContext.get()).foreach(_.killTaskIfInterrupted())
+ if (q.offer(batch, 100, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ // A successful offer can race abandon(): abandon does `add(mark)` then `q.clear()`, so if
+ // it ran between the isAbandoned check above and this offer, our batch lands AFTER the
+ // clear and would be stranded in the queue (no reader will ever drain it). Re-check and
+ // clear it ourselves so nothing is left behind. The reader has departed, so discarding is
+ // correct; and it keeps the queue empty for removeShuffle rather than pinning a batch.
+ if (ChannelShuffleRendezvous.isAbandoned(shuffleId, runEpoch, pid)) {
+ q.clear()
+ return false
+ }
+ if (records > 0) {
+ writeMetrics.incRecordsWritten(records.toLong)
+ writeMetrics.incWriteTime(System.nanoTime() - start)
+ }
+ return true
+ }
+ }
+ false
+ }
+
+ override def write(records: Iterator[Product2[K, V]]): Unit = {
+ // No stale-state reset is needed here: this run's queues and abandoned marks are keyed by
+ // runEpoch (the jobId), so an EARLIER run of this shuffleId (a RangePartitioner sampling job
+ // then the main job; executeTake batches; a re-executed classic plan) used a different epoch
+ // and its leftovers are physically separate -- this run starts against empty per-epoch state.
+
+ // One in-progress batch per reduce partition, plus its fill count. A partition's batch array
+ // is allocated LAZILY, on its first record (batches(pid) starts null), so a map task pays for
+ // only the partitions it actually writes -- a wide shuffle (thousands of partitions) or a
+ // partial read (liveMask leaves most partitions dead) does not eagerly allocate
+ // numPartitions * batchSize empty slots up front.
+ val batches = new Array[Array[AnyRef]](numPartitions)
+ val sizes = new Array[Int](numPartitions)
+ // Records skipped because their reduce partition has no consumer (see liveMask).
+ // Reported at the end of write().
+ var droppedRecords = 0L
+
+ while (records.hasNext) {
+ val rec = records.next()
+ val pid = partitioner.getPartition(rec._1)
+ // Only accumulate for partitions a consumer reads (liveMask). Abandonment is not checked
+ // here -- it is handled at hand-off in putUnlessAbandoned (see liveMask's comment).
+ if (!liveMask(pid)) {
+ // This record is routed to a reduce partition the driver said no consumer reads, so it is
+ // dropped -- see liveMask. Count it: dropping is CORRECT only if the live set was computed
+ // correctly, and everything else here fails loudly (a wrong width fails a require, a
+ // reader-less live partition hangs the writer), while an under-approximated live set would
+ // instead lose rows quietly. A non-zero count at the end of a job whose result looks wrong
+ // is the thread to pull.
+ droppedRecords += 1
+ } else {
+ if (batches(pid) == null) batches(pid) = new Array[AnyRef](batchSize)
+ // Records must already be detached from the producer's reused row buffers by the time
+ // they reach here (the producer reuses its output UnsafeRow across iterations, and the
+ // consumer reads on another thread). The copy is done in the SQL layer's
+ // ShuffleExchangeExec.prepareShuffleDependency via needToCopyObjectsBeforeShuffle
+ // for the pipelined path. This core class cannot reference SQL rows.
+ // `rec` is already a detached (key, value) pair, so batch it directly rather than
+ // re-wrapping it in a fresh Tuple2 -- one fewer allocation per record on the hot loop.
+ // Product2 is typed as Any; the concrete record is always a reference (a Tuple2 of the
+ // pid and the row), so store it as AnyRef. The reader casts each element back to Product2.
+ batches(pid)(sizes(pid)) = rec.asInstanceOf[AnyRef]
+ sizes(pid) += 1
+ if (sizes(pid) == batchSize) {
+ putUnlessAbandoned(pid, batches(pid), batchSize)
+ // Hand off ownership of the filled array to the consumer; the next record for this
+ // partition re-allocates lazily (so a partition whose last record just filled a batch
+ // does not allocate a fresh array it never uses).
+ batches(pid) = null
+ sizes(pid) = 0
+ }
+ }
+ }
+
+ // Flush partial batches (trimmed so the reader can iterate array length directly), then
+ // signal end-of-stream to every partition still wanted, so each live reader can count
+ // this map task as done. Same thread, same queue: data always precedes the marker. A
+ // partition that is dead (no reader) or abandoned (reader departed) gets neither -- its
+ // queue is left for removeShuffle to drop.
+ var p = 0
+ while (p < numPartitions) {
+ if (liveMask(p)) {
+ if (sizes(p) > 0) {
+ putUnlessAbandoned(p, Arrays.copyOf(batches(p), sizes(p)), sizes(p))
+ }
+ // Re-check: the reader may have departed while the trimmed batch was being put.
+ if (!ChannelShuffleRendezvous.isAbandoned(shuffleId, runEpoch, p)) {
+ putUnlessAbandoned(p, ChannelShuffleRendezvous.EndOfStream, records = 0)
+ }
+ }
+ p += 1
+ }
+
+ // Report what this task dropped. Correct for a partial read (those partitions have no reader),
+ // but the only quiet failure mode on this path, so leave a trace: a wrong live set shows up
+ // here as drops on a job whose result is short. Not a metric -- shuffleWrite counters mean
+ // "bytes/records that crossed the transport", which these did not.
+ if (droppedRecords > 0) {
+ logDebug(s"Pipelined shuffle $shuffleId map $mapId dropped $droppedRecords record(s) " +
+ s"routed " +
+ s"to reduce partitions with no consumer (live set: " +
+ s"${liveReducePartitions.map(_.toArray.sorted.mkString(",")).getOrElse("all")})")
+ }
+ }
+
+ override def stop(success: Boolean): Option[MapStatus] = {
+ // A pipelined reducer never reads partition lengths, but the ShuffleWriter contract
+ // still requires a MapStatus. Return an all-zero placeholder, mirroring the RPC
+ // streaming writer.
+ Some(MapStatus(
+ SparkEnv.get.blockManager.shuffleServerId,
+ Array.fill(numPartitions)(0L),
+ mapId))
+ }
+
+ override def getPartitionLengths(): Array[Long] = Array.fill(numPartitions)(0L)
+}
+
+/**
+ * Reduce-side of the in-process pipelined shuffle. Drains the shared queue for this reduce
+ * partition batch by batch, handing rows to the consumer stage as the map tasks produce
+ * them, until every map task has signalled end-of-stream.
+ *
+ * `numMaps` is the number of map tasks feeding this shuffle; the reader stops after it has
+ * observed that many [[ChannelShuffleRendezvous.EndOfStream]] markers on its queue.
+ *
+ * ONE reduce partition per reader task ONLY: `endPartition - startPartition` must be 1. The
+ * channel transport cannot serve a coalesced multi-partition range. The reader would have to
+ * drain the range's queues in some order, but the map-side writer interleaves all partitions
+ * on ONE thread and blocks on a full bounded queue; if the reader drains partition `start` to
+ * completion before touching `start+1` while the writer has parked filling `start+1`, the two
+ * deadlock with no timeout escape. The SQL layer keeps a coalesced spec from ever reaching a
+ * pipelined dependency: `EnablePipelinedShuffle` / `AQEEnablePipelinedShuffle` refuse to
+ * pipeline any shuffle read by a `CoalesceExec` (leaving it regular), and AQE also keeps a
+ * pipelined exchange out of any ShuffleQueryStage so CoalesceShufflePartitions never coalesces
+ * it -- so both the AQE and non-AQE readers use width-1 CoalescedPartitionSpec(i, i+1). The
+ * `require` below makes that a hard, fail-loud invariant rather than a silent hang if a future
+ * change ever lets a coalesced spec reach a pipelined dependency.
+ */
+private[spark] class ChannelShuffleReader[K, C](
+ handle: BaseShuffleHandle[K, _, C],
+ startPartition: Int,
+ endPartition: Int,
+ numMaps: Int,
+ readMetrics: ShuffleReadMetricsReporter)
+ extends ShuffleReader[K, C] {
+
+ require(endPartition - startPartition == 1,
+ s"ChannelShuffleReader supports exactly one reduce partition per task, got " +
+ s"[$startPartition, $endPartition); the in-process channel transport does not support " +
+ "coalesced multi-partition reads (see class doc).")
+
+ // Per-run epoch (the jobId), the same value the writer of this gang reads, so both address the
+ // same per-run queues in the process-wide rendezvous. See ChannelShuffleRendezvous.epochOf.
+ private val runEpoch = ChannelShuffleRendezvous.epochOf(TaskContext.get())
+
+ // On task completion (normal end, early stop like LIMIT, or failure) mark this reader's
+ // partition as abandoned, so a writer still feeding it stops and does not wedge on its bounded
+ // queue. Registered once here; fires whether or not the iterator was drained to the end.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ =>
+ var p = startPartition
+ while (p < endPartition) {
+ ChannelShuffleRendezvous.abandon(handle.shuffleId, runEpoch, p)
+ p += 1
+ }
+ }
+ }
+
+ override def read(): Iterator[Product2[K, C]] =
+ (startPartition until endPartition).iterator.flatMap(drainQueue)
+
+ private def drainQueue(reducePartitionId: Int): Iterator[Product2[K, C]] = {
+ val q = ChannelShuffleRendezvous.queue(handle.shuffleId, runEpoch, reducePartitionId)
+ new Iterator[Product2[K, C]] {
+ // The current batch being handed out, and the cursor into it. A null batch after
+ // advance() means every map task has signalled end-of-stream: iteration is over.
+ private var batch: Array[AnyRef] = _
+ private var pos = 0
+ private var endOfStreamSeen = 0
+ advance()
+
+ // Interruptibly wait for the next queue item. `LinkedBlockingQueue.take()` blocks
+ // UNINTERRUPTIBLY here: if this reader's producers die (a map task throws before emitting
+ // end-of-stream for this partition), the DAGScheduler aborts the group and kills this
+ // reduce task, but the kill sets the interrupt flag on the TaskContext WITHOUT necessarily
+ // interrupting the thread (spark.job.interruptOnCancel defaults to false), so a plain
+ // take() would park forever and pin the executor slot for the app's life. Poll with a
+ // short timeout and check the TaskContext's interrupt flag each cycle -- the symmetric
+ // cooperative escape to the writer's putUnlessAbandoned. Time spent parked here is the
+ // read-side backpressure signal (producer slower than consumer), so it is reported as
+ // fetch-wait time.
+ private def takeItem(): AnyRef = {
+ var item: AnyRef = null
+ // Time the WHOLE wait and convert once, the way ShuffleBlockFetcherIterator's
+ // withFetchWaitTimeTracked does. Converting each poll separately truncated every
+ // sub-millisecond wait to zero -- and a normal hand-off returns in microseconds -- so a
+ // consumer that really was waiting reported ~0, inverting what this metric is for.
+ val start = System.nanoTime()
+ while (item == null) {
+ Option(TaskContext.get()).foreach(_.killTaskIfInterrupted())
+ item = q.poll(100, java.util.concurrent.TimeUnit.MILLISECONDS)
+ }
+ readMetrics.incFetchWaitTime(
+ java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start))
+ item
+ }
+
+ // Blocking-drain until the next non-empty data batch, or until every map task has
+ // signalled end-of-stream for this queue (then leave `batch` null to end iteration).
+ private def advance(): Unit = {
+ batch = null
+ pos = 0
+ // A producer with zero map tasks (numMaps == 0, e.g. a pipelined shuffle over an empty
+ // RDD) enqueues nothing and no end-of-stream marker ever arrives; without this guard the
+ // wait below would never terminate. Terminate immediately with an empty iterator. The
+ // check is also correct for numMaps > 0 once every marker has been seen (advance is not
+ // called again after batch stays null, but this keeps the invariant explicit).
+ if (endOfStreamSeen >= numMaps) return
+ var item = takeItem()
+ while (item eq ChannelShuffleRendezvous.EndOfStream) {
+ endOfStreamSeen += 1
+ if (endOfStreamSeen >= numMaps) return
+ item = takeItem()
+ }
+ batch = item.asInstanceOf[Array[AnyRef]]
+ // Count the records handed to the consumer as this batch is fetched. Local, so this
+ // is the read-side records metric; there is no remote fetch and no wire bytes.
+ readMetrics.incRecordsRead(batch.length.toLong)
+ }
+
+ override def hasNext: Boolean = batch != null
+
+ override def next(): Product2[K, C] = {
+ if (batch == null) throw new NoSuchElementException
+ val cur = batch(pos).asInstanceOf[Product2[K, C]]
+ pos += 1
+ // Writers only enqueue non-empty batches, so exhausting one means fetching the next.
+ if (pos == batch.length) advance()
+ cur
+ }
+ }
+ }
+}
diff --git a/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleManager.scala b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleManager.scala
new file mode 100644
index 000000000000..a13721994de9
--- /dev/null
+++ b/core/src/main/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleManager.scala
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.shuffle.local.pipelined
+
+import org.apache.spark.{ShuffleDependency, SparkConf, TaskContext}
+import org.apache.spark.internal.config
+import org.apache.spark.shuffle.{BaseShuffleHandle, PipelinedShuffleManager, ShuffleHandle, ShuffleReader, ShuffleReadMetricsReporter, ShuffleWriteMetricsReporter, ShuffleWriter}
+
+/**
+ * A pipelined shuffle manager whose writer -> reader transport is an in-process bounded
+ * channel (see [[ChannelShuffleRendezvous]]) rather than the RPC streaming shuffle. It
+ * serves a [[org.apache.spark.PipelinedShuffleDependency]] on a single executor, letting
+ * the concurrent-stage scheduler run a shuffle's map and reduce stages at the same time
+ * while records flow between them in memory -- the in-process pipelined shuffle execution model.
+ *
+ * Selected via `spark.shuffle.manager.incremental`.
+ *
+ * Unlike the RPC streaming manager, this one needs no `StreamingShuffleOutputTracker`: it
+ * finds each reader/writer pair through the JVM-local [[ChannelShuffleRendezvous]] rather
+ * than a directory of writer host/port locations. It therefore declares
+ * `usesStreamingShuffleOutputTracker = false`, so `SparkEnv` creates no tracker and the
+ * scheduler registers the shuffle with none (a pipelined stage's availability is tracked on
+ * the stage itself, not in any output tracker). This is why it implements the
+ * `PipelinedShuffleManager` trait directly instead of subclassing the concrete streaming
+ * manager.
+ *
+ * This manager deliberately keeps NO per-shuffle registry. An early version recorded each
+ * shuffle's map-task count at registration and looked it up in getReader -- and lost it when
+ * an unregisterShuffle arrived BETWEEN registration and the job running, which happens
+ * legitimately: Dataset.rdd builds the RDD inside a SQL execution scope that ends (and, with
+ * spark.sql.classic.shuffleDependency.fileCleanup.enabled, removes the shuffle from every
+ * manager) before any job has run. The reader then saw a missing entry as numMaps = 0 and
+ * silently under-read the channel. The count is instead stamped into the shuffle handle at
+ * registration ([[ChannelShuffleHandle.numMaps]]): the handle travels with the dependency
+ * into every task, a plain Int field survives task serialization (the dependency's own `rdd`
+ * reference is @transient and is null inside a deserialized task), and no later unregister
+ * can take it away.
+ */
+private[spark] class PipelinedChannelShuffleManager(conf: SparkConf)
+ extends PipelinedShuffleManager {
+
+ // The in-process rendezvous is JVM-local: on a multi-executor deployment each executor would
+ // get its own empty queue map, and every reader would block forever on data written in some
+ // other JVM -- a silent hang. Refuse to construct anywhere but local mode, so a
+ // misconfiguration fails loudly at startup instead.
+ require(org.apache.spark.util.Utils.isLocalMaster(conf),
+ "PipelinedChannelShuffleManager is an in-process (single-JVM) transport and requires " +
+ s"local mode; got master '${conf.get("spark.master", "")}'")
+
+ // Rows accumulated per output partition before a batch is handed across the channel in one
+ // queue operation. Batching amortizes the queue's per-operation lock cost; per-row hand-off
+ // measured ~19x slower than a regular shuffle on a 20M-row repartition.
+ private val batchSize = conf.get(config.SHUFFLE_PIPELINED_CHANNEL_BATCH_SIZE)
+
+ // Per-queue depth in batches (backpressure bound + heap-residency knob). Set the process-wide
+ // rendezvous from the conf at construction, before any writer/reader creates a queue.
+ ChannelShuffleRendezvous.setCapacity(conf.get(config.SHUFFLE_PIPELINED_CHANNEL_QUEUE_CAPACITY))
+
+ override def usesStreamingShuffleOutputTracker: Boolean = false
+
+ // Records cross the channel as object references read by a concurrent consumer thread; the
+ // SQL layer must detach each row from the producer's reused buffer before the writer sees it.
+ override def requiresDetachedRecords: Boolean = true
+
+ // The channel writer parks on a full bounded queue, so it needs the driver's
+ // live-reduce-partition
+ // hint to drop records routed to partitions no reader will drain (see ChannelShuffleWriter's
+ // liveMask), and the per-run epoch to key its rendezvous.
+ override def supportsLiveReducePartitionHints: Boolean = true
+
+ override def startRun(epoch: Int): Unit = ChannelShuffleRendezvous.startRun(epoch)
+
+ override def endRun(epoch: Int): Unit = ChannelShuffleRendezvous.endRun(epoch)
+
+ // Answer from the rendezvous -- the state that would leak -- rather than from a registration
+ // record: a shuffle unregistered BEFORE its job runs (Dataset.rdd under fileCleanup)
+ // recreates its
+ // queues lazily when the job does run, and a registry dropped at unregister would never list it
+ // again, leaking those queues for the life of the context.
+ override def holdsShuffle(shuffleId: Int): Boolean =
+ ChannelShuffleRendezvous.holdsShuffle(shuffleId)
+
+ override def registerShuffle[K, V, C](
+ shuffleId: Int,
+ dependency: ShuffleDependency[K, V, C]): ShuffleHandle =
+ new ChannelShuffleHandle(shuffleId, dependency, dependency.rdd.partitions.length)
+
+ override def getWriter[K, V](
+ handle: ShuffleHandle,
+ mapId: Long,
+ context: TaskContext,
+ metrics: ShuffleWriteMetricsReporter): ShuffleWriter[K, V] =
+ new ChannelShuffleWriter[K, V](
+ handle.asInstanceOf[BaseShuffleHandle[K, V, _]], mapId, batchSize, metrics)
+
+ override def getReader[K, C](
+ handle: ShuffleHandle,
+ startMapIndex: Int,
+ endMapIndex: Int,
+ startPartition: Int,
+ endPartition: Int,
+ context: TaskContext,
+ metrics: ShuffleReadMetricsReporter): ShuffleReader[K, C] = {
+ // A reduce task reads the reduce-partition range [startPartition, endPartition). The channel
+ // transport serves exactly ONE reduce partition per reader task -- ChannelShuffleReader
+ // require()s endPartition - startPartition == 1 (its class doc explains why a coalesced
+ // multi-partition range cannot be drained safely). A width-1 spec is what actually arrives:
+ // the SQL rules (EnablePipelinedShuffle / AQEEnablePipelinedShuffle) refuse to pipeline any
+ // shuffle read by a CoalesceExec, and AQE also keeps a pipelined exchange out of a
+ // ShuffleQueryStage so CoalesceShufflePartitions never coalesces it -- so both core ShuffledRDD
+ // and SQL's ShuffledRowRDD hand a width-1 spec here. The require makes any future wider range
+ // fail loud rather than deadlock. Map-index bounds are irrelevant (all map tasks share each
+ // partition's queue). The final 5-arg getReader forwards here with the partition range.
+ //
+ // numMaps -- how many end-of-stream markers to expect per queue -- was stamped into the
+ // handle at registration, never kept in mutable manager state (see class scaladoc).
+ val h = handle.asInstanceOf[ChannelShuffleHandle[K, _, C]]
+ new ChannelShuffleReader[K, C](h, startPartition, endPartition, h.numMaps, metrics)
+ }
+
+ override def unregisterShuffle(shuffleId: Int): Boolean = {
+ ChannelShuffleRendezvous.removeShuffle(shuffleId)
+ true
+ }
+
+ // Called from SparkEnv.stop() when the SparkContext stops. Drop the process-wide rendezvous
+ // state: it is keyed by (shuffleId, epoch, reducePartitionId) with no application scoping, so a
+ // fresh SparkContext in the same JVM (a test fork, a REPL/notebook restart) would restart both
+ // shuffle ids and epochs (jobIds) at 0 and could read rows or end-of-stream markers this context
+ // left behind under the same key.
+ override def stop(): Unit = ChannelShuffleRendezvous.clear()
+}
+
+/**
+ * The channel manager's shuffle handle: a [[BaseShuffleHandle]] plus the producer's map-task
+ * count, captured at registration while the dependency's (transient) RDD is still reachable.
+ * The reader needs it to know how many end-of-stream markers close a queue.
+ */
+private[spark] class ChannelShuffleHandle[K, V, C](
+ shuffleId: Int,
+ dependency: ShuffleDependency[K, V, C],
+ val numMaps: Int)
+ extends BaseShuffleHandle(shuffleId, dependency)
diff --git a/core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala b/core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala
index 3a824efec511..1d175c3d6ae6 100644
--- a/core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala
+++ b/core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala
@@ -6807,9 +6807,10 @@ class DAGSchedulerSuite extends SparkFunSuite with TempLocalSparkContext with Ti
}
test("pipelined shuffle: a job mixing a pipelined and a regular shuffle is rejected up front") {
- // A job must be either all-regular or all-pipelined, not a mix. A consumer
- // depending on BOTH a pipelined producer AND a regular producer is a mixed job and must be
- // rejected up front (before any stage is submitted), leaving no scheduler state behind.
+ // A consumer depending on BOTH a pipelined producer AND an UNMATERIALIZED regular producer
+ // is an unsupported mix and must be rejected up front (before any stage is submitted),
+ // leaving no scheduler state behind. (A fully-MATERIALIZED regular prefix is the supported
+ // exception -- see the materialized-prefix test below.)
val pipelinedProducerRdd = new MyRDD(sc, 2, Nil)
val pipelinedDep = new PipelinedShuffleDependency(pipelinedProducerRdd, new HashPartitioner(2))
val regularProducerRdd = new MyRDD(sc, 2, Nil)
@@ -6831,11 +6832,11 @@ class DAGSchedulerSuite extends SparkFunSuite with TempLocalSparkContext with Ti
}
test("pipelined shuffle: a regular-shuffle prefix feeding a pipelined producer is rejected") {
- // Also mixed: a regular shuffle in the PREFIX that feeds a pipelined producer
- // (regularRoot --regular--> producer(pipelined) --pipelined--> consumer). Rather than treat
- // the regular edge as an ordinary external input to the group and support a mid-DAG regular
- // prefix, a pipelined job rejects ANY regular shuffle up front (the supported shape is
- // scan-of-files --pipelined--> stateful, with no upstream shuffle).
+ // An UNMATERIALIZED regular shuffle in the PREFIX that feeds a pipelined producer
+ // (regularRoot --regular--> producer(pipelined) --pipelined--> consumer) is rejected: the
+ // prefix stage would have to run while gang-admitted producers hold slots blocked on
+ // transport backpressure, which admission does not account for. Once the prefix is
+ // MATERIALIZED the same shape is accepted (see the materialized-prefix test below).
val regularRoot = new MyRDD(sc, 2, Nil)
val regularDep = new ShuffleDependency(regularRoot, new HashPartitioner(2))
val producerRdd = new MyRDD(sc, 2, List(regularDep), tracker = mapOutputTracker)
@@ -6855,6 +6856,201 @@ class DAGSchedulerSuite extends SparkFunSuite with TempLocalSparkContext with Ti
assertDataStructuresEmpty()
}
+ test("pipelined shuffle: a fully-materialized regular prefix below the suffix is accepted") {
+ // The materialized-prefix mixed shape (the one adaptive execution produces: prior jobs
+ // materialize the prefix stages, the final job runs the pipelined tail). First job
+ // materializes the regular shuffle; the second job's pipelined producer reads that
+ // materialized output, so the prefix stage is skipped and only the gang runs. The prefix's
+ // map side (2) and reduce side (3) are deliberately asymmetric: materialization
+ // completeness must be measured in MAP outputs, and a symmetric count would hide a check
+ // against the wrong side.
+ val regularRoot = new MyRDD(sc, 2, Nil)
+ val regularDep = new ShuffleDependency(regularRoot, new HashPartitioner(3))
+ val prefixReader = new MyRDD(sc, 3, List(regularDep), tracker = mapOutputTracker)
+ submit(prefixReader, Array(0, 1, 2))
+ completeShuffleMapStageSuccessfully(taskSets.head.stageId, 0, 3)
+ complete(taskSets(1), Seq((Success, 1), (Success, 2), (Success, 3)))
+ assert(results === Map(0 -> 1, 1 -> 2, 2 -> 3))
+ results.clear()
+ val taskSetsBefore = taskSets.size
+
+ // producer(reads materialized regular) --[pipelined]--> consumer (result stage).
+ val producerRdd = new MyRDD(sc, 3, List(regularDep), tracker = mapOutputTracker)
+ val pipelinedDep = new PipelinedShuffleDependency(producerRdd, new HashPartitioner(2))
+ val consumerRdd = new MyRDD(sc, 2, List(pipelinedDep), tracker = mapOutputTracker)
+ submit(consumerRdd, Array(0, 1))
+
+ // Not rejected; the prefix stage is available (not resubmitted); producer and consumer
+ // gang-run concurrently.
+ assert(taskSets.size === taskSetsBefore + 2,
+ s"expected producer and consumer submitted concurrently, got ${taskSets.size} task sets")
+ assert(scheduler.runningStages.exists(_.rdd eq producerRdd))
+ assert(scheduler.runningStages.exists(_.rdd eq consumerRdd))
+ assert(!scheduler.runningStages.exists(_.rdd eq regularRoot),
+ "the materialized prefix stage must not re-run")
+
+ completeShuffleMapStageSuccessfully(taskSets(taskSetsBefore).stageId, 0, 2)
+ complete(taskSets(taskSetsBefore + 1), Seq((Success, 42), (Success, 43)))
+ assert(results === Map(0 -> 42, 1 -> 43))
+ assertDataStructuresEmpty()
+ }
+
+ test("pipelined shuffle: losing a materialized prefix's output mid-group aborts the whole " +
+ "group, not a lone prefix resubmit") {
+ // The materialized-prefix mixed shape does not need a slot to re-run its prefix -- but if the
+ // prefix's shuffle output is LOST while the gang is running (FetchFailed / executor loss), a
+ // base-scheduler lone-stage resubmit of the prefix would deadlock: the gang holds all slots
+ // (producers blocked on backpressure), leaving no slot for the prefix to recompute into. This
+ // is the one FetchFailed path where the failing consumer reads OUTSIDE its group (the external
+ // prefix), which the group-internal FetchFailed test does not exercise. It must still route to
+ // a whole-group abort, because isPipelinedGroupMember keys off the FAILING STAGE (the pipelined
+ // producer reading the prefix is a group member) regardless of which shuffle's fetch failed.
+ val regularRoot = new MyRDD(sc, 2, Nil)
+ val regularDep = new ShuffleDependency(regularRoot, new HashPartitioner(3))
+ val prefixReader = new MyRDD(sc, 3, List(regularDep), tracker = mapOutputTracker)
+ submit(prefixReader, Array(0, 1, 2))
+ completeShuffleMapStageSuccessfully(taskSets.head.stageId, 0, 3)
+ complete(taskSets(1), Seq((Success, 1), (Success, 2), (Success, 3)))
+ results.clear()
+ val taskSetsBefore = taskSets.size
+
+ // producer(reads the materialized regular prefix) --[pipelined]--> consumer (result stage).
+ val producerRdd = new MyRDD(sc, 3, List(regularDep), tracker = mapOutputTracker)
+ val pipelinedDep = new PipelinedShuffleDependency(producerRdd, new HashPartitioner(2))
+ val consumerRdd = new MyRDD(sc, 2, List(pipelinedDep), tracker = mapOutputTracker)
+ submit(consumerRdd, Array(0, 1))
+ assert(taskSets.size === taskSetsBefore + 2, "producer and consumer gang-submitted")
+ val producerTs = taskSets(taskSetsBefore)
+ val taskSetsBeforeFetchFailure = taskSets.size
+
+ // The pipelined PRODUCER task fails fetching the EXTERNAL materialized prefix (regularDep),
+ // not the pipelined shuffle. Its output for mapIndex 0 was placed on hostA by
+ // completeShuffleMapStageSuccessfully.
+ runEvent(makeCompletionEvent(
+ producerTs.tasks(0),
+ FetchFailed(makeBlockManagerId("hostA"), regularDep.shuffleId, 0L, 0, 0, "ignored"),
+ null))
+
+ // Whole-group abort: the job fails, and no lone stage (neither the pipelined producer nor the
+ // materialized prefix's map stage) is resubmitted into the slot-starved gang.
+ scheduler.resubmitFailedStages()
+ assert(failure != null,
+ "losing a materialized prefix's output under a running gang must fail the job")
+ assert(taskSets.size === taskSetsBeforeFetchFailure,
+ "no lone stage may be resubmitted after the group is aborted")
+ assert(!scheduler.runningStages.exists(_.rdd eq regularRoot),
+ "the prefix's map stage must not be resubmitted in isolation into the gang's held slots")
+ sc.listenerBus.waitUntilEmpty()
+ assertDataStructuresEmpty()
+ }
+
+ test("pipelined shuffle: an all-pipelined group with no regular prefix classifies identically " +
+ "under the materialized-prefix relaxation (a previously-valid shape is unchanged)") {
+ // The prefix relaxation (classifyJobShuffleShape) keys purely off dependency TYPE, so it is
+ // open to any PipelinedShuffleDependency. But the materialized-prefix mixed shape it newly
+ // admits is produced only by adaptive execution; an all-pipelined job (no regular boundary)
+ // never hits the relaxed path, so it classifies identically before and after the relaxation
+ // -- the relaxation is a strict superset that leaves every previously-valid shape unchanged.
+ val producerRdd = new MyRDD(sc, 2, Nil)
+ val pipelinedDep = new PipelinedShuffleDependency(producerRdd, new HashPartitioner(2))
+ val consumerRdd = new MyRDD(sc, 2, List(pipelinedDep), tracker = mapOutputTracker)
+ submit(consumerRdd, Array(0, 1))
+
+ // Accepted and gang-scheduled exactly like the pre-relaxation all-pipelined path: producer and
+ // consumer submitted concurrently, no rejection, no materialized-prefix machinery engaged.
+ assert(taskSets.size === 2,
+ s"all-pipelined job must gang-submit producer + consumer, got ${taskSets.size} task sets")
+ assert(scheduler.runningStages.exists(_.rdd eq producerRdd))
+ assert(scheduler.runningStages.exists(_.rdd eq consumerRdd))
+
+ complete(taskSets.head, Seq(
+ (Success, makeMapStatus("hostA", 2)),
+ (Success, makeMapStatus("hostB", 2))))
+ val consumerTs = taskSets.find { ts =>
+ scheduler.stageIdToStage(ts.stageId).rdd eq consumerRdd
+ }.get
+ complete(consumerTs, Seq((Success, 42), (Success, 43)))
+ assert(results === Map(0 -> 42, 1 -> 43))
+ assertDataStructuresEmpty()
+ }
+
+ test("pipelined shuffle: a non-mixed job is classified by the cheap kinds pre-pass") {
+ // classifyJobShuffleShape runs on EVERY job submission, including on deployments that never
+ // enable this feature, so a non-mixed job must not pay the precise (RDD, belowRegular)-keyed
+ // walk that only a pipelined/regular MIX needs.
+ //
+ // This is a COST property, not a behavioral one: for a non-mixed job both paths return the same
+ // shape, so no assertion on the result can distinguish them. What is pinned here instead is the
+ // contract the pre-pass rests on -- the kinds pre-pass alone determines the answer for a
+ // non-mixed graph -- for each of the three non-mixed shapes. If a future change makes the
+ // shape depend on the precise walk for these graphs, these equalities break.
+ def shapeOf(rdd: MyRDD): (Boolean, Boolean, Boolean) = {
+ val sh = scheduler.classifyJobShuffleShape(rdd)
+ (sh.hasPipelined, sh.hasUnmaterializedRegularBoundary, sh.hasPipelinedBelowRegular)
+ }
+
+ // (1) all-regular, boundary unmaterialized: not a mix -> nothing to report.
+ val regularDep = new ShuffleDependency(new MyRDD(sc, 2, Nil), new HashPartitioner(2))
+ val overRegular = new MyRDD(sc, 2, List(regularDep), tracker = mapOutputTracker)
+ assert(scheduler.classifyJobShuffleKinds(overRegular) === (false, true))
+ assert(shapeOf(overRegular) === (false, false, false))
+
+ // (2) all-pipelined: not a mix -> hasPipelined only.
+ val pipelinedDep = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new HashPartitioner(2))
+ val overPipelined = new MyRDD(sc, 2, List(pipelinedDep), tracker = mapOutputTracker)
+ assert(scheduler.classifyJobShuffleKinds(overPipelined) === (true, false))
+ assert(shapeOf(overPipelined) === (true, false, false))
+
+ // (3) no shuffle at all.
+ val noShuffle = new MyRDD(sc, 2, Nil)
+ assert(scheduler.classifyJobShuffleKinds(noShuffle) === (false, false))
+ assert(shapeOf(noShuffle) === (false, false, false))
+
+ // And the MIX still gets the precise answer (the expensive walk does run when it matters):
+ // a pipelined dep below an unmaterialized regular boundary must be detected.
+ val deepPipelined =
+ new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new HashPartitioner(2))
+ val belowRegular = new MyRDD(sc, 2, List(deepPipelined), tracker = mapOutputTracker)
+ val regularOverPipelined = new ShuffleDependency(belowRegular, new HashPartitioner(2))
+ val mixed = new MyRDD(sc, 2, List(regularOverPipelined), tracker = mapOutputTracker)
+ assert(scheduler.classifyJobShuffleKinds(mixed) === (true, true), "this graph IS a mix")
+ val mixedShape = scheduler.classifyJobShuffleShape(mixed)
+ assert(mixedShape.hasPipelinedBelowRegular,
+ "the precise walk must still detect a pipelined dependency below a regular boundary")
+ assert(mixedShape.isUnsupportedMix, "and such a job must be rejected as an unsupported mix")
+ }
+
+ test("pipelined shuffle: a manager that does not consume the live-reduce hint gets no hint") {
+ // The scheduler's live-reduce-partition hint and per-run epoch exist for a transport whose
+ // writer PARKS on a partition nobody drains (the in-process channel's bounded queue). The RPC
+ // streaming transport -- the default `spark.shuffle.manager.incremental`, and what Real-Time
+ // Mode runs on -- reads neither property, so a pipelined job on it must be left exactly as it
+ // is without this feature: no cloned Properties, no epoch, no live set, and no partial-read
+ // abort whose remedy (disabling the batch SQL flag) does not even apply to it.
+ assert(!sc.env.pipelinedShuffleManager.supportsLiveReducePartitionHints,
+ "precondition: the default incremental manager does not consume the hint")
+
+ val producerRdd = new MyRDD(sc, 2, Nil)
+ val pipelinedDep = new PipelinedShuffleDependency(producerRdd, new HashPartitioner(2))
+ val consumerRdd = new MyRDD(sc, 2, List(pipelinedDep), tracker = mapOutputTracker)
+ // A PARTIAL read (one of two result partitions) is the shape that would compute and stamp the
+ // hint -- and, if unmappable, abort the stage.
+ submit(consumerRdd, Array(0))
+
+ assert(taskSets.nonEmpty, "the pipelined group should have been submitted")
+ taskSets.foreach { ts =>
+ val props = Option(ts.properties)
+ assert(props.forall(p =>
+ p.getProperty(SparkContext.SPARK_PIPELINED_RUN_EPOCH) == null),
+ s"no epoch may be stamped for a manager that does not consume it (stage ${ts.stageId})")
+ assert(props.forall(p =>
+ p.getProperty(SparkContext.SPARK_PIPELINED_LIVE_REDUCE_PARTITIONS) == null),
+ s"no live-reduce set may be stamped for such a manager (stage ${ts.stageId})")
+ }
+ // And the job was not aborted by the partial-read fail-fast path.
+ assert(failure == null, s"the job must not be aborted; got: $failure")
+ }
+
test("pipelined shuffle: deep chain A->B->C is submitted fully concurrently") {
// A --pipelined--> B --pipelined--> C : all three co-scheduled (each edge is non-sequencing).
val rddA = new MyRDD(sc, 2, Nil)
diff --git a/core/src/test/scala/org/apache/spark/shuffle/PipelinedShuffleRoutingSuite.scala b/core/src/test/scala/org/apache/spark/shuffle/PipelinedShuffleRoutingSuite.scala
index 8e0f9e04c1bd..647c2611ca58 100644
--- a/core/src/test/scala/org/apache/spark/shuffle/PipelinedShuffleRoutingSuite.scala
+++ b/core/src/test/scala/org/apache/spark/shuffle/PipelinedShuffleRoutingSuite.scala
@@ -85,7 +85,13 @@ private class DefaultRecordingManager(conf: SparkConf, isDriver: Boolean)
override def shuffleBlockResolver: ShuffleBlockResolver = mock(classOf[ShuffleBlockResolver])
}
private class IncrementalRecordingManager(conf: SparkConf, isDriver: Boolean)
- extends RecordingShuffleManager(conf, isDriver) with PipelinedShuffleManager
+ extends RecordingShuffleManager(conf, isDriver) with PipelinedShuffleManager {
+ // A non-streaming pipelined manager (an in-process transport): it needs no
+ // StreamingShuffleOutputTracker, unlike the RPC streaming manager that the trait defaults to.
+ // The "SparkEnv does not initialize the tracker when the incremental manager is not streaming"
+ // and fail-loud tests rely on this manager reporting false here.
+ override def usesStreamingShuffleOutputTracker: Boolean = false
+}
/**
* Tests routing of shuffles to the default vs. incremental [[ShuffleManager]] by dependency type,
@@ -240,44 +246,22 @@ class PipelinedShuffleRoutingSuite extends SparkFunSuite with LocalSparkContext
assert(SparkEnv.get.streamingShuffleOutputTracker.isEmpty)
}
- test("createShuffleMapStage fails loud for a pipelined dependency when no streaming tracker") {
- // A pipelined shuffle is served solely by the StreamingShuffleOutputTracker. With a non-
- // streaming incremental manager configured, that tracker is absent (verified above), so a job
- // whose stage graph contains a PipelinedShuffleDependency cannot be scheduled.
- // createShuffleMapStage must fail loud rather than silently register the shuffle in no tracker
- // (which would strand a consumer with no writer locations). This guards the decoupling's
- // invariant that a pipelined dependency implies a streaming tracker.
- // local[4]: the pipelined group's up-front slot admission (producer 2 + result 2 = 4) must pass
- // so that stage creation is actually reached -- otherwise the job is rejected for slots first.
- sc = new SparkContext("local[4]", "test", newConf())
- assert(SparkEnv.get.streamingShuffleOutputTracker.isEmpty)
- val producer = sc.parallelize(1 to 4, 2).map(x => (x, x))
- val pipelined = new PipelinedShuffleDependency[Int, Int, Int](producer, new HashPartitioner(2))
- // A minimal reduce-side RDD whose single dependency is the pipelined shuffle, so submitting an
- // action forces createShuffleMapStage for the pipelined producer.
- val consumer = new RDD[(Int, Int)](sc, Seq(pipelined)) {
- override def compute(split: Partition, ctx: TaskContext): Iterator[(Int, Int)] =
- Iterator.empty
- override protected def getPartitions: Array[Partition] =
- Array.tabulate(2)(i => new Partition { override def index: Int = i })
- }
- val ex = intercept[Exception] {
- consumer.count()
- }
- assert(findCause[IllegalStateException](ex).exists(
- _.getMessage.contains("requires a StreamingShuffleOutputTracker")),
- s"expected a fail-loud IllegalStateException about the missing tracker, got: $ex")
-
- // The fail-loud throw happens BEFORE createShuffleMapStage mutates stageIdToStage /
- // shuffleIdToMapStage, so it leaves no partial scheduler state behind. If it left a
- // half-created stage cached in shuffleIdToMapStage, a re-submission would reuse that stale
- // stage instead of re-throwing. Re-submitting the same job must therefore re-throw the error.
- val ex2 = intercept[Exception] {
- consumer.count()
- }
- assert(findCause[IllegalStateException](ex2).exists(
- _.getMessage.contains("requires a StreamingShuffleOutputTracker")),
- s"a re-submission must re-throw the fail-loud error (no leaked partial stage), got: $ex2")
+ test("a pipelined shuffle with a no-tracker manager registers with NO output tracker") {
+ // A pipelined manager reporting usesStreamingShuffleOutputTracker = false (the in-process
+ // channel manager) registers its shuffle with NEITHER tracker: SparkEnv creates no
+ // StreamingShuffleOutputTracker, and createShuffleMapStage takes outputTrackerMaster's None
+ // arm so the shuffle never enters the MapOutputTracker either -- its availability lives on
+ // the stage. This pins that routing (the relaxed successor to the old "fails loud when no
+ // tracker" invariant, which no longer holds now that a tracker-less manager is legitimate).
+ val env = startEnv()
+ val dep = pipelinedDep(sc)
+ assert(env.shuffleManagerFor(dep).isInstanceOf[IncrementalRecordingManager],
+ "the pipelined dep must route to the no-tracker incremental manager")
+ assert(SparkEnv.get.streamingShuffleOutputTracker.isEmpty,
+ "no StreamingShuffleOutputTracker should be created for a no-tracker manager")
+ assert(!env.mapOutputTracker.asInstanceOf[MapOutputTrackerMaster]
+ .containsShuffle(dep.shuffleId),
+ "a no-tracker pipelined shuffle must not be registered with the MapOutputTracker")
}
test("spark.shuffle.manager.incremental resolves the same short aliases as the default manager") {
diff --git a/core/src/test/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleSuite.scala b/core/src/test/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleSuite.scala
new file mode 100644
index 000000000000..90faa085b2a3
--- /dev/null
+++ b/core/src/test/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleSuite.scala
@@ -0,0 +1,590 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.shuffle.local.pipelined
+
+import scala.reflect.ClassTag
+
+import org.mockito.Mockito.{mock, when}
+
+import org.apache.spark.{HashPartitioner, Partitioner, PipelinedShuffleDependency, SparkConf, SparkContext, SparkEnv, SparkFunSuite, TaskContext, TaskKilledException}
+import org.apache.spark.executor.TempShuffleReadMetrics
+import org.apache.spark.rdd.{RDD, ShuffledRDD}
+import org.apache.spark.shuffle.BaseShuffleHandle
+
+/**
+ * A [[ShuffledRDD]] that emits a [[PipelinedShuffleDependency]] instead of a regular
+ * `ShuffleDependency`, so its shuffle is served by the pipelined manager and its stages are
+ * co-scheduled. Test-only: in production the pipelined boundary would be emitted by the SQL
+ * planner (a pipelined exchange), not by a hand-built RDD.
+ */
+private class PipelinedShuffledRDD[K: ClassTag, V: ClassTag, C: ClassTag](
+ prev: RDD[_ <: Product2[K, V]],
+ part: Partitioner)
+ extends ShuffledRDD[K, V, C](prev, part) {
+
+ override def getDependencies: Seq[org.apache.spark.Dependency[_]] =
+ List(new PipelinedShuffleDependency[K, V, C](
+ prev.asInstanceOf[RDD[_ <: Product2[K, V]]], part, SparkEnv.get.serializer))
+
+ // A pipelined shuffle is not registered with the MapOutputTracker; skip locality hints,
+ // whose inherited implementation casts to MapOutputTrackerMaster for a shuffle that is
+ // not there.
+ override def getPreferredLocations(partition: org.apache.spark.Partition): Seq[String] = Nil
+}
+
+class PipelinedChannelShuffleSuite extends SparkFunSuite {
+
+ private def withPipelinedSparkContext(cores: Int)(body: SparkContext => Unit): Unit = {
+ ChannelShuffleRendezvous.clear()
+ val conf = new SparkConf()
+ .setMaster(s"local[$cores]")
+ .setAppName("pipelined-channel-shuffle-test")
+ .set("spark.shuffle.manager.incremental",
+ "org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager")
+ .set("spark.speculation", "false")
+ val sc = new SparkContext(conf)
+ try {
+ body(sc)
+ } finally {
+ sc.stop()
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ /** Repartition `0 until n` to `numOut` partitions and return (partitionIndex, key, value). */
+ private def repartition(
+ sc: SparkContext, n: Int, numIn: Int, numOut: Int): Array[(Int, Int, Int)] = {
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until n, numIn).map(v => (v, v))
+ val out = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(numOut))
+ out.mapPartitionsWithIndex { (idx, it) =>
+ it.map { case (k, v) => (idx, k, v) }
+ }.collect()
+ }
+
+ test("repartition through the channel transport loses no rows and routes correctly") {
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val n = 1000
+ val numOut = 4
+ val out = repartition(sc, n, numIn = 3, numOut = numOut)
+ // No row lost or duplicated.
+ assert(out.map(_._3).toSet === (0 until n).toSet)
+ // Every row landed in the partition its key hashes to.
+ val part = new HashPartitioner(numOut)
+ out.foreach { case (idx, k, _) =>
+ assert(part.getPartition(k) === idx, s"key $k routed to partition $idx")
+ }
+ }
+ }
+
+ test("result matches a regular shuffle of the same workload") {
+ // Ground-truth grouping from a plain (non-pipelined) repartition.
+ val expected = {
+ ChannelShuffleRendezvous.clear()
+ val sc = new SparkContext(
+ new SparkConf().setMaster("local[8]").setAppName("baseline"))
+ try {
+ sc.parallelize(0 until 1000, 3).map(v => (v, v))
+ .partitionBy(new HashPartitioner(4))
+ .mapPartitionsWithIndex((idx, it) => it.map { case (k, _) => (idx, k) })
+ .collect().toSet
+ } finally {
+ sc.stop()
+ }
+ }
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val actual = repartition(sc, 1000, numIn = 3, numOut = 4)
+ .map { case (idx, k, _) => (idx, k) }.toSet
+ assert(actual === expected)
+ }
+ }
+
+ test("fan-in whose whole-group demand fits the slots repartitions correctly") {
+ // Whole-group demand = producer parts + consumer parts must be <= free slots, since the
+ // pipelined stages run concurrently. On local[8]: 5 + 2 = 7 <= 8, admissible.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val out = repartition(sc, n = 2000, numIn = 5, numOut = 2)
+ assert(out.map(_._3).toSet === (0 until 2000).toSet)
+ }
+ }
+
+ test("a group whose demand exceeds the slots is rejected up front") {
+ // This is the single-machine ceiling of the pipelined model: all stages of the group
+ // must hold a slot at once. On local[8], numIn=8 + numOut=2 = 10 > 8, so the scheduler
+ // rejects the job before any task runs rather than deadlocking. Documented constraint,
+ // pinned here so a future scheduler change that silently relaxes it is caught.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val ex = intercept[org.apache.spark.SparkException] {
+ repartition(sc, n = 100, numIn = 8, numOut = 2)
+ }
+ assert(ex.getMessage.contains("CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT") ||
+ ex.getMessage.contains("concurrent task slots"),
+ s"expected an insufficient-slot rejection, got: ${ex.getMessage}")
+ }
+ }
+
+ test("unregisterShuffle drops the shuffle's rendezvous queues across all epochs") {
+ // Test the manager's cleanup contract directly rather than relying on the async
+ // ContextCleaner + GC to fire (which would be flaky). Populate queues for a shuffle id under
+ // TWO different epochs (a re-run), plus a different shuffle, then confirm unregisterShuffle
+ // removes every epoch of shuffle 7 and leaves shuffle 9 alone.
+ ChannelShuffleRendezvous.clear()
+ try {
+ ChannelShuffleRendezvous.queue(7, epoch = 1, 0).put("a")
+ ChannelShuffleRendezvous.queue(7, epoch = 1, 1).put("b")
+ ChannelShuffleRendezvous.queue(7, epoch = 2, 0).put("a2") // a re-run of shuffle 7
+ ChannelShuffleRendezvous.queue(9, epoch = 1, 0).put("c") // a different shuffle, must survive
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 4)
+
+ ChannelShuffleRendezvous.removeShuffle(7)
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 1,
+ "every epoch of shuffle 7's queues should be dropped")
+ // Shuffle 9's queue is untouched.
+ assert(ChannelShuffleRendezvous.queue(9, epoch = 1, 0).peek() === "c")
+ } finally {
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ test("ContextCleaner frees the channel's queues for a tracker-less pipelined shuffle") {
+ // Regression for the production leak (C1): a channel-manager shuffle registers in NO output
+ // tracker (usesStreamingShuffleOutputTracker = false), so ContextCleaner.doCleanupShuffle
+ // finds it in neither the MapOutputTracker nor the StreamingShuffleOutputTracker and takes
+ // its tracker-less branch. That branch must still reach the manager's unregisterShuffle (->
+ // ChannelShuffleRendezvous.removeShuffle) or the process-wide queues leak for the JVM's life.
+ // The SQL suite cannot catch this: it runs under spark.sql.classic.shuffleDependency.
+ // fileCleanup.enabled, whose default is Utils.isTesting = true, so the SQL path proactively
+ // removes the shuffle in tests and masks the leak. Here we drive doCleanupShuffle directly
+ // (the production GC path, minus the flaky GC) and assert the queues are freed.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 1000, 3).map(v => (v, v))
+ val rdd = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ val shuffleId = rdd.dependencies.head
+ .asInstanceOf[org.apache.spark.ShuffleDependency[_, _, _]].shuffleId
+ // Run it so the writer creates the rendezvous queues.
+ rdd.collect()
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 0)
+ // The cleaner also handles state created outside a scheduler-managed run.
+ ChannelShuffleRendezvous.queue(shuffleId, epoch = -1, 0)
+
+ // The production cleanup path: ContextCleaner.doCleanupShuffle for this shuffle id. With the
+ // fix, its tracker-less branch calls shuffleDriverComponents.removeShuffle, which routes to
+ // the channel manager and frees the queues.
+ sc.cleaner.get.doCleanupShuffle(shuffleId, blocking = true)
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 0,
+ "doCleanupShuffle must free the channel's queues for a tracker-less pipelined shuffle")
+ }
+ }
+
+ test("the tracker-less cleanup arm is scoped to shuffles the rendezvous actually holds") {
+ // The tracker-less arm of doCleanupShuffle must fire only for a shuffle the channel rendezvous
+ // holds state for, not for any shuffle that happens to be in neither tracker while the manager
+ // is active. The gating signal is ChannelShuffleRendezvous.holdsShuffle (NOT the manager's
+ // registration), because a channel shuffle unregistered before its job runs recreates its
+ // queues lazily even though the manager no longer lists it -- keying off the rendezvous frees
+ // those recreated queues while staying false for a regular shuffle (never present here).
+ withPipelinedSparkContext(cores = 8) { sc =>
+ // A channel (pipelined) shuffle: after it runs, the rendezvous holds its queues...
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 1000, 3).map(v => (v, v))
+ val rdd = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ val pipelinedId = rdd.dependencies.head
+ .asInstanceOf[org.apache.spark.ShuffleDependency[_, _, _]].shuffleId
+ rdd.collect()
+ assert(!ChannelShuffleRendezvous.holdsShuffle(pipelinedId))
+ ChannelShuffleRendezvous.queue(pipelinedId, epoch = -1, 0)
+ assert(ChannelShuffleRendezvous.holdsShuffle(pipelinedId))
+
+ // A REGULAR shuffle in the same feature-on context routes to the DEFAULT manager and never
+ // touches the rendezvous, so holdsShuffle is false -- the arm skips it (no duplicate RPC).
+ val regular = sc.parallelize(0 until 1000, 3).map(v => (v, v)).reduceByKey(_ + _)
+ val regularId = regular.dependencies.head
+ .asInstanceOf[org.apache.spark.ShuffleDependency[_, _, _]].shuffleId
+ regular.collect()
+ assert(!ChannelShuffleRendezvous.holdsShuffle(regularId),
+ "the rendezvous must NOT hold a regular shuffle")
+
+ // Unregister frees the rendezvous state, so a later GC-time re-clean is a no-op.
+ ChannelShuffleRendezvous.removeShuffle(pipelinedId)
+ assert(!ChannelShuffleRendezvous.holdsShuffle(pipelinedId),
+ "removeShuffle must clear the rendezvous state for the shuffle")
+ }
+ }
+
+ test("cleanup frees a channel shuffle unregistered BEFORE it ran (re-run recreated its queues)") {
+ // Regression for the unregister-before-run leak: a shuffle whose SQL scope ended (Dataset.rdd
+ // under fileCleanup) unregisters it before any job runs, then the job runs and recreates the
+ // rendezvous queues lazily. An earlier fix keyed cleanup off the manager's registration, which
+ // was dropped at that unregister and never re-added, so holdsShuffle stayed false forever and
+ // the recreated queues leaked. Keying off the rendezvous fixes that: the recreated queues make
+ // holdsShuffle true again, so doCleanupShuffle's arm frees them.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 1000, 3).map(v => (v, v))
+ val rdd = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ val shuffleId = rdd.dependencies.head
+ .asInstanceOf[org.apache.spark.ShuffleDependency[_, _, _]].shuffleId
+
+ // Simulate the unregister-before-run: clear any state, then run so the writer/reader recreate
+ // the queues -- WITHOUT any manager re-registration in between.
+ ChannelShuffleRendezvous.removeShuffle(shuffleId)
+ rdd.collect()
+ assert(!ChannelShuffleRendezvous.holdsShuffle(shuffleId),
+ "job cleanup must free state even when the shuffle was unregistered before running")
+
+ // The cleanup arm must now free them (it keys off the rendezvous, not a stale registry).
+ sc.cleaner.get.doCleanupShuffle(shuffleId, blocking = true)
+ assert(!ChannelShuffleRendezvous.holdsShuffle(shuffleId),
+ "doCleanupShuffle must free the recreated queues for a re-run channel shuffle")
+ }
+ }
+
+ /**
+ * Run a job over only SOME of `rdd`'s partitions -- a PARTIAL READ, the shape that makes the
+ * DAGScheduler stamp a live reduce-partition set on a pipelined producer (see
+ * DAGScheduler.liveReduceSet). Returns the rows the read partitions produced, under a deadline:
+ * if the live set is mapped wrongly the producer keeps feeding a partition no reader will drain,
+ * fills its bounded queue and parks forever, so a regression surfaces as a timeout, not a hang.
+ *
+ * These are RDD-level on purpose. The SQL LIMIT shapes that used to cover this now fall back to
+ * a regular shuffle (a LIMIT operator builds a hidden regular shuffle in doExecute, so the
+ * enabling rules refuse to pipeline a plan containing one), which would make a SQL-level partial
+ * read test vacuous -- it would pass while exercising nothing.
+ */
+ private def partialReadWithin(
+ sc: SparkContext, seconds: Int, rdd: RDD[_], partitions: Seq[Int]): Option[Long] = {
+ val pool = java.util.concurrent.Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new java.util.concurrent.Callable[Long] {
+ override def call(): Long = {
+ // Count rows per read partition. `PipelinedChannelShuffleSuite.countRows` is a static
+ // (companion) function so the job closure captures nothing from the suite instance --
+ // a closure capturing the suite is not serializable.
+ sc.runJob(rdd, PipelinedChannelShuffleSuite.countRows _, partitions).sum
+ }
+ })
+ try {
+ Some(fut.get(seconds.toLong, java.util.concurrent.TimeUnit.SECONDS))
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ None
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+
+ test("partial read of a pipelined shuffle completes (identity narrow chain)") {
+ // The result RDD reads the shuffle through a 1:1 chain, so the live reduce set is the read
+ // partition set itself. Only partition 0 is read; the writer must drop 1..3 rather than fill
+ // their queues and park.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 400000, 4).map(v => (v, v))
+ val shuffled = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ // A 1:1 map keeps the chain narrow and same-index (OneToOneDependency).
+ val mapped = shuffled.map { case (k, v) => (k, v) }
+ // Read a NON-ZERO partition on purpose: a live-set bug that collapses to {0} (or to the
+ // result-partition ids when they differ from the reduce ids) would starve this reader and
+ // hang, instead of accidentally being right.
+ val got = partialReadWithin(sc, 90, mapped, Seq(2))
+ assert(got.isDefined,
+ "partial read of a pipelined shuffle hung: the producer kept feeding partitions that " +
+ "have no reader (the live reduce set was mapped wrongly)")
+ assert(got.get > 0, "the read partition should have produced rows")
+ }
+ }
+
+ test("partial read through a union of two pipelined shuffles completes") {
+ // union() reaches each shuffle through a RangeDependency whose getParents applies a per-branch
+ // offset, so liveReduceSet must map the read partition set through both branches' offsets.
+ withPipelinedSparkContext(cores = 12) { sc =>
+ def branch(): RDD[(Int, Int)] = {
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 200000, 4).map(v => (v, v))
+ new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ }
+ // Both branches share a HashPartitioner, so union() yields a PartitionerAwareUnionRDD whose
+ // partition i draws from partition i of BOTH branches (4 partitions total, not 8). That is
+ // exactly the fan-in shape under test: one read partition must contribute a live reduce
+ // partition to EACH branch's shuffle.
+ val unioned = branch().union(branch())
+ val got = partialReadWithin(sc, 90, unioned, Seq(2))
+ assert(got.isDefined,
+ "partial read through a union of pipelined shuffles hung: the live set was not mapped " +
+ "through the union's per-branch offsets")
+ }
+ }
+
+ test("partial read through a zip of two pipelined shuffles completes") {
+ // zip() fans in over a ZippedPartitionsRDD: one narrow branch per side down to that side's
+ // shuffle, so liveReduceSet must contribute the live set from EVERY branch reaching a shuffle.
+ withPipelinedSparkContext(cores = 12) { sc =>
+ def branch(): RDD[(Int, Int)] = {
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 200000, 4).map(v => (v, v))
+ new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ }
+ val zipped = branch().zipPartitions(branch())((a, b) => a.zip(b))
+ val got = partialReadWithin(sc, 90, zipped, Seq(2))
+ assert(got.isDefined,
+ "partial read through a zip of pipelined shuffles hung: the live set was not contributed " +
+ "from both zip branches")
+ }
+ }
+
+ test("a failing producer map task fails the job promptly, without parking the reader forever") {
+ // If a producer map task throws before emitting end-of-stream, the reduce task for a
+ // partition it never fed would park in the queue wait. The reader polls interruptibly and
+ // checks the TaskContext interrupt flag (set when the group is aborted), so it wakes and the
+ // job fails fast with the producer's error instead of pinning the executor slot forever.
+ // Run on a background thread under a deadline: a regression (uninterruptible take) would hang
+ // here rather than fail, and the deadline turns that into a test failure, not a stuck suite.
+ val pool = java.util.concurrent.Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new Runnable {
+ override def run(): Unit = withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed = sc.parallelize(0 until 1000, 3).map { v =>
+ if (v == 500) throw new RuntimeException("boom in producer map task")
+ (v, v)
+ }
+ val out = new PipelinedShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(4))
+ // The job must FAIL (the producer threw), not hang. intercept confirms it returned.
+ intercept[org.apache.spark.SparkException](out.collect())
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 0)
+ }
+ })
+ try {
+ fut.get(90, java.util.concurrent.TimeUnit.SECONDS)
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ fail("a failing producer hung the job: the reader parked in an uninterruptible wait")
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+
+ test("the channel manager refuses to construct outside local mode") {
+ // The rendezvous is JVM-local; on a multi-executor master every reader would hang on
+ // data written in another JVM. A cluster misconfiguration must fail loudly at startup.
+ val conf = new SparkConf().set("spark.master", "spark://example.invalid:7077")
+ val ex = intercept[IllegalArgumentException] {
+ new PipelinedChannelShuffleManager(conf)
+ }
+ assert(ex.getMessage.contains("requires local mode"), ex.getMessage)
+ // And constructs fine for local masters.
+ new PipelinedChannelShuffleManager(new SparkConf().set("spark.master", "local[4]"))
+ }
+
+ test("materialized regular prefix + pipelined suffix runs end-to-end") {
+ // The materialized-prefix mixed shape: a regular shuffle materialized by an earlier job,
+ // then a pipelined shuffle over its output in a second job. Previously rejected as a
+ // mixed job; with the prefix relaxation the second job runs, reading the materialized
+ // regular output at the gang's leaves. Demand: 3 (producer, over the prefix's 3
+ // partitions) + 4 (consumer) = 7 <= 8.
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 1000, 2).map(v => (v % 10, v))
+ val prefix = new ShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(3))
+ assert(prefix.count() === 1000) // materialize the regular shuffle
+
+ val suffix = new PipelinedShuffledRDD[Int, Int, Int](prefix, new HashPartitioner(4))
+ val out = suffix.collect()
+ assert(out.map(_._2).toSet === (0 until 1000).toSet,
+ "no row lost or duplicated through the prefix + pipelined suffix")
+ }
+ }
+
+ test("an unmaterialized regular prefix below a pipelined suffix is still rejected") {
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val keyed: RDD[(Int, Int)] = sc.parallelize(0 until 100, 2).map(v => (v % 10, v))
+ val prefix = new ShuffledRDD[Int, Int, Int](keyed, new HashPartitioner(3))
+ // No action on `prefix`: its shuffle is not materialized when the mixed job submits.
+ val suffix = new PipelinedShuffledRDD[Int, Int, Int](prefix, new HashPartitioner(4))
+ val ex = intercept[org.apache.spark.SparkException] {
+ suffix.collect()
+ }
+ assert(ex.getMessage.contains("fully-materialized prefix"),
+ s"expected the unmaterialized-prefix rejection, got: ${ex.getMessage}")
+ }
+ }
+
+ test("unregister preserves an active run until its owner finishes") {
+ ChannelShuffleRendezvous.clear()
+ try {
+ ChannelShuffleRendezvous.startRun(1)
+ val q = ChannelShuffleRendezvous.queue(42, 1, 0)
+ q.put("live")
+ ChannelShuffleRendezvous.abandon(42, 1, 1)
+ ChannelShuffleRendezvous.queue(42, 0, 0).put("idle")
+ ChannelShuffleRendezvous.removeShuffle(42)
+ assert(ChannelShuffleRendezvous.queue(42, 1, 0) eq q)
+ assert(q.peek() === "live")
+ assert(ChannelShuffleRendezvous.isAbandoned(42, 1, 1))
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 1)
+ ChannelShuffleRendezvous.endRun(1)
+ assert(!ChannelShuffleRendezvous.holdsShuffle(42))
+ } finally {
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ test("ending a run releases only its epoch and rejects late task accesses") {
+ ChannelShuffleRendezvous.clear()
+ val tc = TaskContext.empty()
+ try {
+ ChannelShuffleRendezvous.startRun(1)
+ ChannelShuffleRendezvous.startRun(2)
+ ChannelShuffleRendezvous.queue(42, 1, 0).put("old")
+ ChannelShuffleRendezvous.abandon(42, 1, 1)
+ ChannelShuffleRendezvous.queue(42, 2, 0).put("new")
+ ChannelShuffleRendezvous.endRun(1)
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 1)
+ assert(!ChannelShuffleRendezvous.isAbandoned(42, 1, 1))
+ assert(ChannelShuffleRendezvous.queue(42, 2, 0).peek() === "new")
+
+ TaskContext.setTaskContext(tc)
+ intercept[TaskKilledException] {
+ ChannelShuffleRendezvous.queue(42, 1, 0)
+ }
+ ChannelShuffleRendezvous.abandon(42, 1, 0)
+ assert(ChannelShuffleRendezvous.isAbandoned(42, 1, 0))
+ ChannelShuffleRendezvous.endRun(2)
+ assert(!ChannelShuffleRendezvous.holdsShuffle(42))
+ } finally {
+ TaskContext.unset()
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ test("repeated actions release queues while the shuffle dependency remains reachable") {
+ withPipelinedSparkContext(cores = 8) { sc =>
+ val input = sc.parallelize(0 until 1000, 2).map(i => (i, i))
+ val shuffled = new PipelinedShuffledRDD[Int, Int, Int](input, new HashPartitioner(4))
+ for (_ <- 0 until 5) {
+ assert(shuffled.collect().map(_._1).sorted === (0 until 1000).toArray)
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 0)
+ }
+ }
+ }
+
+ test("abandon marks partition and drains its queue") {
+ // abandon() sets an abandoned mark and drains the queue. The key contract:
+ // when a writer is blocked on put() due to a full queue, abandon() drains
+ // the queue so the put() unblocks (freeing capacity). This test verifies both
+ // the mark is set and the queue is drained.
+ ChannelShuffleRendezvous.clear()
+ try {
+ val q = ChannelShuffleRendezvous.queue(42, epoch = 1, 0)
+ // Put a few batches into the queue.
+ q.put("batch1")
+ q.put("batch2")
+ q.put("batch3")
+ assert(!q.isEmpty, "queue should have elements")
+
+ // Abandon the partition.
+ ChannelShuffleRendezvous.abandon(42, epoch = 1, 0)
+
+ // Both conditions must hold after abandon:
+ // 1. The partition is marked abandoned (prevents new writes).
+ assert(ChannelShuffleRendezvous.isAbandoned(42, epoch = 1, 0),
+ "partition should be marked abandoned")
+ // 2. The queue is drained (unblocks any parked put and cleans up).
+ assert(q.isEmpty, "queue should be drained by abandon()")
+ } finally {
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ test("a re-run's epoch isolates it from a prior run's leftover queue and marks") {
+ // Finding B: a re-run of the same shuffleId must not see the previous run's leftovers. Two
+ // runs of one shuffleId are two jobs, so two epochs; keying the rendezvous by epoch makes the
+ // second run's queue and marks physically separate from the first's. This is the property
+ // that prevents a new reader from draining stale batches / counting stale EndOfStream markers
+ // (a silent wrong result) and a straggler writer of the aborted run from touching the new
+ // run's queue.
+ ChannelShuffleRendezvous.clear()
+ try {
+ val shuffleId = 55
+ val pid = 0
+
+ // Run epoch=1 leaves a batch, an EndOfStream, and an abandoned mark on pid (its reader
+ // never fully drained -- e.g. the group aborted).
+ ChannelShuffleRendezvous.queue(shuffleId, epoch = 1, pid).put("stale-batch")
+ ChannelShuffleRendezvous.queue(shuffleId, epoch = 1, pid).put(
+ ChannelShuffleRendezvous.EndOfStream)
+ ChannelShuffleRendezvous.abandon(shuffleId, epoch = 1, pid)
+ // abandon drains the queue, so re-add a leftover to model a partition whose reader never
+ // started (no abandon, queue keeps its contents).
+ val pid2 = 1
+ ChannelShuffleRendezvous.queue(shuffleId, epoch = 1, pid2).put("stale-unread")
+
+ // Run epoch=2 (the re-run) sees FRESH state for the same (shuffleId, pid): a new empty
+ // queue and no abandoned mark, regardless of what epoch 1 left behind.
+ assert(ChannelShuffleRendezvous.queue(shuffleId, epoch = 2, pid).isEmpty,
+ "the re-run's queue must be empty, not the prior run's leftovers")
+ assert(ChannelShuffleRendezvous.queue(shuffleId, epoch = 2, pid2).isEmpty,
+ "the re-run's queue must be empty for an unread prior-run partition too")
+ assert(!ChannelShuffleRendezvous.isAbandoned(shuffleId, epoch = 2, pid),
+ "the re-run must not inherit the prior run's abandoned mark")
+
+ // removeShuffle at cleanup drops every epoch for the shuffle.
+ ChannelShuffleRendezvous.removeShuffle(shuffleId)
+ assert(ChannelShuffleRendezvous.numQueuesForTesting === 0,
+ "removeShuffle should drop queues of every epoch for this shuffle")
+ assert(!ChannelShuffleRendezvous.isAbandoned(shuffleId, epoch = 1, pid),
+ "removeShuffle should clear abandoned marks of every epoch")
+ } finally {
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+
+ test("reader stops after exactly numMaps EndOfStream markers") {
+ // Drive the REAL ChannelShuffleReader.read() (not a reimplementation of its loop): pre-load
+ // its partition queue with data batches interleaved with exactly numMaps EndOfStream markers,
+ // then assert read() yields every data row IN ORDER and terminates -- it must not block
+ // waiting for a further marker (would hang the test), nor stop early. The reader reads only
+ // handle.shuffleId, so a mock handle suffices; TaskContext.get() is None here so no
+ // completion listener is registered and the reader's epoch defaults to 0 -- so pre-load the
+ // queue at epoch 0 to match. TempShuffleReadMetrics is a no-op reporter.
+ ChannelShuffleRendezvous.clear()
+ try {
+ val shuffleId = 11
+ val pid = 0
+ val numMaps = 3
+ val q = ChannelShuffleRendezvous.queue(shuffleId, epoch = 0, pid)
+ // batch1, EOS, batch2, EOS, batch3, EOS (3 markers = numMaps). Rows are (k, v) pairs.
+ q.put(Array[AnyRef]((1, 1), (2, 2)))
+ q.put(ChannelShuffleRendezvous.EndOfStream)
+ q.put(Array[AnyRef]((3, 3)))
+ q.put(ChannelShuffleRendezvous.EndOfStream)
+ q.put(Array[AnyRef]((4, 4), (5, 5), (6, 6)))
+ q.put(ChannelShuffleRendezvous.EndOfStream)
+
+ val handle = mock(classOf[BaseShuffleHandle[Int, Int, Int]])
+ when(handle.shuffleId).thenReturn(shuffleId)
+ val reader = new ChannelShuffleReader[Int, Int](
+ handle, startPartition = pid, endPartition = pid + 1, numMaps = numMaps,
+ readMetrics = new TempShuffleReadMetrics)
+
+ val values = reader.read().map(_._2).toSeq
+ assert(values === Seq(1, 2, 3, 4, 5, 6),
+ s"reader must yield every data row in order and then stop, got $values")
+ assert(q.isEmpty, "the reader should have drained the queue to empty")
+ } finally {
+ ChannelShuffleRendezvous.clear()
+ }
+ }
+}
+
+private object PipelinedChannelShuffleSuite {
+ /** Row count of one partition; a top-level function so a job closure captures no suite state. */
+ def countRows(it: Iterator[_]): Long = it.size.toLong
+}
diff --git a/dev/sparktestsupport/modules.py b/dev/sparktestsupport/modules.py
index 8441926d2cf3..efd3eb41048e 100644
--- a/dev/sparktestsupport/modules.py
+++ b/dev/sparktestsupport/modules.py
@@ -674,6 +674,7 @@ pyspark_sql = Module(
"pyspark.sql.tests.test_context",
"pyspark.sql.tests.test_sql_context",
"pyspark.sql.tests.test_dataframe",
+ "pyspark.sql.tests.test_pipelined_shuffle",
"pyspark.sql.tests.test_collection",
"pyspark.sql.tests.test_creation",
"pyspark.sql.tests.test_conversion",
diff --git a/python/pyspark/sql/tests/test_pipelined_shuffle.py b/python/pyspark/sql/tests/test_pipelined_shuffle.py
new file mode 100644
index 000000000000..2686a2708cc8
--- /dev/null
+++ b/python/pyspark/sql/tests/test_pipelined_shuffle.py
@@ -0,0 +1,105 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import unittest
+
+from pyspark.sql.functions import udf
+from pyspark.sql.types import LongType
+from pyspark.testing.sqlutils import ReusedSQLTestCase
+
+
+class PipelinedShuffleTests(ReusedSQLTestCase):
+ @classmethod
+ def master(cls):
+ return "local[8]"
+
+ @classmethod
+ def conf(cls):
+ return (
+ super()
+ .conf()
+ .set(
+ "spark.shuffle.manager.incremental",
+ "org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager",
+ )
+ .set("spark.sql.shuffle.localPipelined.enabled", "true")
+ .set("spark.sql.shuffle.partitions", "4")
+ .set("spark.sql.classic.shuffleDependency.fileCleanup.enabled", "false")
+ )
+
+ def assert_regular_rdd(self, rdd):
+ pending = [rdd]
+ visited = set()
+ while pending:
+ current = pending.pop()
+ if current.id() in visited:
+ continue
+ visited.add(current.id())
+ dependencies = current.dependencies().iterator()
+ while dependencies.hasNext():
+ dependency = dependencies.next()
+ self.assertNotIn("PipelinedShuffleDependency", dependency.getClass().getName())
+ pending.append(dependency.rdd())
+
+ def test_rdd_consumers(self):
+ for aqe in ("false", "true"):
+ with self.subTest(aqe=aqe), self.sql_conf({"spark.sql.adaptive.enabled": aqe}):
+ df = self.spark.range(0, 4000, 1, 2).repartition(4)
+ self.assertEqual(len(df.collect()), 4000)
+ rdd = df.rdd
+ # Check lineage before running consumers that would hang with a channel.
+ self.assert_regular_rdd(rdd._jrdd.rdd())
+ self.assertEqual(rdd.coalesce(1).count(), 4000)
+ self.assertEqual(
+ sorted(
+ rdd.map(lambda r: (r.id % 2, 1)).reduceByKey(lambda a, b: a + b).collect()
+ ),
+ [(0, 2000), (1, 2000)],
+ )
+
+ def test_iterator_reuses_shuffle_output(self):
+ for aqe in ("false", "true"):
+ for prefetch in (False, True):
+ with (
+ self.subTest(aqe=aqe, prefetch=prefetch),
+ self.sql_conf({"spark.sql.adaptive.enabled": aqe}),
+ ):
+ evaluated = self.sc.accumulator(0)
+
+ @udf(LongType())
+ def record_row(value):
+ evaluated.add(1)
+ return value
+
+ df = (
+ self.spark.range(0, 1000, 1, 2)
+ .select(record_row("id").alias("id"))
+ .repartition(4)
+ )
+ self.assertEqual(len(df.collect()), 1000)
+ self.assertEqual(evaluated.value, 1000)
+ for run in (1, 2):
+ rows = list(df.toLocalIterator(prefetchPartitions=prefetch))
+ self.assertEqual(sorted(r.id for r in rows), list(range(1000)))
+ self.assertEqual(evaluated.value, 2000)
+ self.assertEqual(
+ self.spark.conf.get("spark.sql.shuffle.localPipelined.enabled"), "true"
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index 392764fc51ed..66db4403e8e6 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -1269,6 +1269,23 @@ object SQLConf {
.booleanConf
.createWithDefault(true)
+ val LOCAL_PIPELINED_SHUFFLE_ENABLED = buildConf("spark.sql.shuffle.localPipelined.enabled")
+ .internal()
+ .doc("When true in local mode, eligible shuffle exchanges use the in-process channel " +
+ "manager configured by spark.shuffle.manager.incremental. Producer and consumer stages " +
+ "run concurrently. Plans whose estimated group width exceeds the local task capacity, " +
+ "or whose width cannot be determined, retain regular shuffles. In particular, ordinary " +
+ "non-bucketed file scans report unknown widths and stay regular. Runtime admission still " +
+ "checks available slots and can reject a group when other work occupies them. " +
+ "Pipelined exchanges do not receive AQE coalescing. Dataset.rdd, toLocalIterator, cache " +
+ "construction, cached inputs and mixed AQE plans use regular shuffles. Concurrent " +
+ "actions sharing a pipelined exchange remain unsupported. Other multi-job consumers " +
+ "can recompute pipelined producers for each job. Experimental.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+ .booleanConf
+ .createWithDefault(false)
+
val ADAPTIVE_EXECUTION_ENABLED_IN_STATELESS_STREAMING =
buildConf("spark.sql.adaptive.streaming.stateless.enabled")
.internal()
@@ -8950,6 +8967,8 @@ class SQLConf extends Serializable with Logging with SqlApiConf {
def adaptiveExecutionEnabled: Boolean = getConf(ADAPTIVE_EXECUTION_ENABLED)
+ def localPipelinedShuffleEnabled: Boolean = getConf(LOCAL_PIPELINED_SHUFFLE_ENABLED)
+
def adaptiveExecutionEnabledInStatelessStreaming: Boolean =
getConf(ADAPTIVE_EXECUTION_ENABLED_IN_STATELESS_STREAMING)
diff --git a/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk21-results.txt b/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk21-results.txt
new file mode 100644
index 000000000000..ef2dba200d3e
--- /dev/null
+++ b/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk21-results.txt
@@ -0,0 +1,110 @@
+================================================================================================
+Transport comparison: regular vs RPC-streaming vs in-process channel
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+repartition(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3799 3807 10 5.3 190.0 1.0X
+streaming 3704 3721 24 5.4 185.2 1.0X
+channel 1463 1681 307 13.7 73.2 2.6X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+groupBy(k).count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 317 404 51 63.0 15.9 1.0X
+streaming 306 313 6 65.3 15.3 1.0X
+channel 291 311 19 68.7 14.6 1.1X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+join 10M x 10M on unique k+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 4524 4673 211 2.2 452.4 1.0X
+streaming 4603 4618 22 2.2 460.3 1.0X
+channel 4505 4523 26 2.2 450.5 1.0X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+prototype 1M uniq: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 261 276 11 383.8 2.6 1.0X
+streaming 256 265 9 390.6 2.6 1.0X
+channel 119 149 31 843.5 1.2 2.2X
+
+
+================================================================================================
+Regular vs channel, AQE off
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+repartition(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3627 3683 80 5.5 181.3 1.0X
+pipelined 1678 1738 85 11.9 83.9 2.2X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+groupBy(k).count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 274 287 17 72.9 13.7 1.0X
+pipelined 275 288 17 72.7 13.8 1.0X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+repartitionByRange(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3603 3624 30 5.6 180.1 1.0X
+pipelined 1510 1612 144 13.2 75.5 2.4X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+groupBy(k).count+orderBy(k): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 800 832 39 25.0 40.0 1.0X
+pipelined 806 816 14 24.8 40.3 1.0X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+prototype: repartition(id)+count, 1M uniq: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+-------------------------------------------------------------------------------------------------------------------------
+regular 253 270 18 395.1 2.5 1.0X
+pipelined 115 144 23 867.5 1.2 2.2X
+
+
+================================================================================================
+Regular vs channel, AQE on
+================================================================================================
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+repartition(k)+count (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3584 3671 123 5.6 179.2 1.0X
+pipelined 1460 1486 37 13.7 73.0 2.5X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+groupBy(k).count (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 277 301 53 72.3 13.8 1.0X
+pipelined 269 296 42 74.2 13.5 1.0X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+groupBy(k).count+orderBy(k) (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 842 891 44 23.7 42.1 1.0X
+pipelined 804 830 27 24.9 40.2 1.0X
+
+OpenJDK 64-Bit Server VM 21.0.12+8-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 7763 64-Core Processor
+prototype 1M uniq (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 260 267 5 384.7 2.6 1.0X
+pipelined 108 129 14 928.1 1.1 2.4X
+
+
diff --git a/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk25-results.txt b/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk25-results.txt
new file mode 100644
index 000000000000..cfc885fe6a4f
--- /dev/null
+++ b/sql/core/benchmarks/PipelinedShuffleBenchmark-jdk25-results.txt
@@ -0,0 +1,110 @@
+================================================================================================
+Transport comparison: regular vs RPC-streaming vs in-process channel
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+repartition(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3695 3727 46 5.4 184.7 1.0X
+streaming 3656 3661 6 5.5 182.8 1.0X
+channel 1438 1485 67 13.9 71.9 2.6X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+groupBy(k).count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 287 335 36 69.6 14.4 1.0X
+streaming 277 309 31 72.1 13.9 1.0X
+channel 270 288 22 74.0 13.5 1.1X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+join 10M x 10M on unique k+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 4503 4536 47 2.2 450.3 1.0X
+streaming 4556 4594 54 2.2 455.6 1.0X
+channel 4476 4520 62 2.2 447.6 1.0X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+prototype 1M uniq: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 269 280 14 372.1 2.7 1.0X
+streaming 261 273 11 383.0 2.6 1.0X
+channel 118 146 26 848.1 1.2 2.3X
+
+
+================================================================================================
+Regular vs channel, AQE off
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+repartition(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3584 3642 81 5.6 179.2 1.0X
+pipelined 1438 1439 2 13.9 71.9 2.5X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+groupBy(k).count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 253 278 23 79.1 12.7 1.0X
+pipelined 253 266 12 79.0 12.7 1.0X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+repartitionByRange(k)+count: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3632 3645 19 5.5 181.6 1.0X
+pipelined 1441 1447 8 13.9 72.1 2.5X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+groupBy(k).count+orderBy(k): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 948 956 10 21.1 47.4 1.0X
+pipelined 925 945 25 21.6 46.3 1.0X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+prototype: repartition(id)+count, 1M uniq: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+-------------------------------------------------------------------------------------------------------------------------
+regular 256 264 9 390.5 2.6 1.0X
+pipelined 114 135 18 880.5 1.1 2.3X
+
+
+================================================================================================
+Regular vs channel, AQE on
+================================================================================================
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+repartition(k)+count (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 3585 3612 39 5.6 179.2 1.0X
+pipelined 1447 1530 118 13.8 72.4 2.5X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+groupBy(k).count (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 260 288 23 77.0 13.0 1.0X
+pipelined 252 269 21 79.2 12.6 1.0X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+groupBy(k).count+orderBy(k) (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 907 945 47 22.1 45.3 1.0X
+pipelined 929 935 7 21.5 46.5 1.0X
+
+OpenJDK 64-Bit Server VM 25.0.4+7-LTS on Linux 6.17.0-1022-azure
+AMD EPYC 9V74 80-Core Processor
+prototype 1M uniq (AQE): Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative
+------------------------------------------------------------------------------------------------------------------------
+regular 257 266 10 389.5 2.6 1.0X
+pipelined 111 131 16 901.9 1.1 2.3X
+
+
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/classic/Dataset.scala b/sql/core/src/main/scala/org/apache/spark/sql/classic/Dataset.scala
index bdf9dea22b06..e635484f6ed1 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/classic/Dataset.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/classic/Dataset.scala
@@ -568,7 +568,7 @@ class Dataset[T] private[sql](
reliableCheckpoint: Boolean,
storageLevel: Option[StorageLevel]): Dataset[T] = {
val actionName = if (reliableCheckpoint) "checkpoint" else "localCheckpoint"
- withAction(actionName, queryExecution) { physicalPlan =>
+ withAction(actionName, queryExecution.withRegularShuffle) { physicalPlan =>
val internalRdd = physicalPlan.execute().map(_.copy())
if (reliableCheckpoint) {
assert(storageLevel.isEmpty, "StorageLevel should not be defined for reliableCheckpoint")
@@ -1575,7 +1575,7 @@ class Dataset[T] private[sql](
/** @inheritdoc */
def toLocalIterator(): java.util.Iterator[T] = {
- withAction("toLocalIterator", queryExecution) { plan =>
+ withAction("toLocalIterator", queryExecution.withRegularShuffle) { plan =>
val fromRow = resolvedEnc.createDeserializer()
plan.executeToIterator().map(fromRow).asJava
}
@@ -1662,7 +1662,7 @@ class Dataset[T] private[sql](
// Represents the `QueryExecution` used to produce the content of the Dataset as an `RDD`.
@transient private lazy val rddQueryExecution: QueryExecution = {
val deserialized = CatalystSerde.deserialize[T](logicalPlan)
- sparkSession.sessionState.executePlan(deserialized)
+ sparkSession.sessionState.executePlan(deserialized).withRegularShuffle
}
private[sql] lazy val materializedRdd: RDD[T] = {
@@ -2132,9 +2132,13 @@ class Dataset[T] private[sql](
* Converts a JavaRDD to a PythonRDD.
*/
private[sql] def javaToPython: JavaRDD[Array[Byte]] = {
+ javaToPython(queryExecution.withRegularShuffle)
+ }
+
+ private def javaToPython(qe: QueryExecution): JavaRDD[Array[Byte]] = {
val structType = schema // capture it for closure
val binaryAsBytes = sparkSession.sessionState.conf.pysparkBinaryAsBytes // capture config value
- val rdd = queryExecution.toRdd.map(row =>
+ val rdd = qe.toRdd.map(row =>
EvaluatePython.toJava(row, structType, binaryAsBytes))
EvaluatePython.javaToPython(rdd)
}
@@ -2287,8 +2291,9 @@ class Dataset[T] private[sql](
}
private[sql] def toPythonIterator(prefetchPartitions: Boolean = false): Array[Any] = {
- withNewExecutionId {
- PythonRDD.toLocalIteratorAndServe(javaToPython.rdd, prefetchPartitions)
+ val qe = queryExecution.withRegularShuffle
+ SQLExecution.withNewExecutionId(qe) {
+ PythonRDD.toLocalIteratorAndServe(javaToPython(qe).rdd, prefetchPartitions)
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala
index a7adfdf4049e..01fedf51602f 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala
@@ -647,7 +647,10 @@ class CacheManager extends Logging with AdaptiveSparkPlanHelper {
private def getOrCloneSessionWithConfigsOff(session: SparkSession): SparkSession = {
// Bucketed scan only has one time overhead but can have multi-times benefits in cache,
// so we always do bucketed scan in a cached plan.
- var disableConfigs = Seq(SQLConf.AUTO_BUCKETED_SCAN_ENABLED)
+ // Cache hits bypass shuffle readers. Materialize caches with regular shuffles so a
+ // partially evicted cache can recompute only its missing partitions safely.
+ var disableConfigs = Seq(
+ SQLConf.AUTO_BUCKETED_SCAN_ENABLED, SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED)
if (!session.sessionState.conf.getConf(SQLConf.CAN_CHANGE_CACHED_PLAN_OUTPUT_PARTITIONING)) {
// Allowing changing cached plan output partitioning might lead to regression as it introduces
// extra shuffle
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala
index 8be200dfc5bb..a95cc12db831 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/QueryExecution.scala
@@ -43,11 +43,11 @@ import org.apache.spark.sql.classic.SparkSession
import org.apache.spark.sql.connector.catalog.LookupCatalog
import org.apache.spark.sql.connector.catalog.transactions.Transaction
import org.apache.spark.sql.execution.SQLExecution.EXECUTION_ROOT_ID_KEY
-import org.apache.spark.sql.execution.adaptive.{AdaptiveExecutionContext, InsertAdaptiveSparkPlan}
+import org.apache.spark.sql.execution.adaptive.{AdaptiveExecutionContext, AdaptiveSparkPlanExec, InsertAdaptiveSparkPlan, QueryStageExec}
import org.apache.spark.sql.execution.bucketing.{CoalesceBucketsInJoin, DisableUnnecessaryBucketedScan}
import org.apache.spark.sql.execution.datasources.v2.{TransactionalExec, V2TableRefreshUtil}
import org.apache.spark.sql.execution.dynamicpruning.PlanDynamicPruningFilters
-import org.apache.spark.sql.execution.exchange.EnsureRequirements
+import org.apache.spark.sql.execution.exchange.{EnablePipelinedShuffle, EnsureRequirements, PipelinedShuffleEligibility, ShuffleExchangeExec}
import org.apache.spark.sql.execution.reuse.ReuseExchangeAndSubquery
import org.apache.spark.sql.execution.streaming.checkpointing.OffsetSeqMetadata
import org.apache.spark.sql.execution.streaming.runtime.{IncrementalExecution, WatermarkPropagator}
@@ -409,6 +409,34 @@ class QueryExecution(
def assertExecutedPlanPrepared(): Unit = executedPlan
+ /**
+ * RDD consumers and partition-at-a-time iterators can outlive one SQL job. Give them a
+ * separate plan whose shuffles retain output, without changing this execution's plan.
+ * Reuse one fallback per execution and retain its session for lazy planning and AQE.
+ * Closing that session here would stop the shared SparkContext.
+ */
+ private val lazyRegularShuffle = LazyTry {
+ def hasShuffle(plan: SparkPlan): Boolean = plan match {
+ case _: ShuffleExchangeExec => true
+ case a: AdaptiveSparkPlanExec => hasShuffle(a.executedPlan)
+ case q: QueryStageExec => hasShuffle(q.plan)
+ case other => other.children.exists(hasShuffle)
+ }
+ if (!sparkSession.sessionState.conf.localPipelinedShuffleEnabled ||
+ !PipelinedShuffleEligibility.enabled(executedPlan, sparkSession.sessionState.conf) ||
+ !hasShuffle(executedPlan)) {
+ this
+ } else {
+ val session = SparkSession.getOrCloneSessionWithConfigsOff(
+ sparkSession, Seq(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED))
+ new QueryExecution(session, commandExecuted, mode = mode,
+ shuffleCleanupModeOpt = shuffleCleanupModeOpt,
+ refreshPhaseEnabled = refreshPhaseEnabled, analyzerOpt = Some(analyzer))
+ }
+ }
+
+ private[sql] def withRegularShuffle: QueryExecution = lazyRegularShuffle.get
+
val lazyToRdd = LazyTry {
new SQLExecutionRDD(
executedPlan.execute(),
@@ -829,7 +857,11 @@ object QueryExecution {
Nil
} else {
Seq(ReuseExchangeAndSubquery)
- })
+ }) ++
+ // Opt-in (SPARK-57399): runs last so it observes the final reuse decision (a reused
+ // exchange means fan-out, which it refuses to make pipelined).
+ // No-op unless spark.sql.shuffle.localPipelined.enabled=true and AQE is off.
+ Seq(EnablePipelinedShuffle)
}
/**
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/ShuffledRowRDD.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/ShuffledRowRDD.scala
index 3265d66853e5..5eb258fc307a 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/ShuffledRowRDD.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/ShuffledRowRDD.scala
@@ -131,7 +131,29 @@ class ShuffledRowRDD(
var dependency: ShuffleDependency[Int, InternalRow, InternalRow],
metrics: Map[String, SQLMetric],
partitionSpecs: Array[ShufflePartitionSpec])
- extends RDD[InternalRow](dependency.rdd.context, Nil) {
+ extends RDD[InternalRow](dependency.rdd.context, Nil)
+ with org.apache.spark.rdd.ShuffleReducePartitionMapping {
+
+ /**
+ * The reduce partition this RDD's partition reads, taken from its spec rather than assumed to be
+ * the partition index: only a width-1 `CoalescedPartitionSpec` and a
+ * `PartialReducerPartitionSpec`
+ * name a single reducer. A coalesced range covers several, and a `PartialMapperPartitionSpec`
+ * reads a mapper range rather than one reducer, so both report None (the scheduler then keeps
+ * every reduce partition live instead of dropping records). See
+ * `org.apache.spark.rdd.ShuffleReducePartitionMapping`.
+ */
+ override def reducePartitionIndex(partitionIndex: Int): Option[Int] = {
+ if (partitionIndex < 0 || partitionIndex >= partitionSpecs.length) {
+ None
+ } else {
+ partitionSpecs(partitionIndex) match {
+ case CoalescedPartitionSpec(start, end, _) if end - start == 1 => Some(start)
+ case PartialReducerPartitionSpec(reducerIndex, _, _, _) => Some(reducerIndex)
+ case _ => None
+ }
+ }
+ }
def this(
dependency: ShuffleDependency[Int, InternalRow, InternalRow],
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/UnionLoopExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/UnionLoopExec.scala
index 0d8fb4c814e4..a5610ae64252 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/UnionLoopExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/UnionLoopExec.scala
@@ -128,7 +128,7 @@ case class UnionLoopExec(
}
case _ =>
val materializedDF = df.repartition()
- val count = materializedDF.queryExecution.toRdd.count()
+ val count = materializedDF.queryExecution.withRegularShuffle.toRdd.count()
// In the case we return a sufficiently small number of rows when executing any step of the
// recursion we convert the result into a LocalRelation, so that, if the recursion doesn't
@@ -181,7 +181,7 @@ case class UnionLoopExec(
var limitReached: Boolean = false
- val numPartitions = prevDF.queryExecution.toRdd.partitions.length
+ val numPartitions = prevDF.queryExecution.withRegularShuffle.toRdd.partitions.length
// Main loop for obtaining the result of the recursive query.
while (prevCount > 0 && !limitReached) {
@@ -223,8 +223,9 @@ case class UnionLoopExec(
}
p.copy(projectList = prevPlanToRefMapping)
case _ =>
- val logicalRDD = LogicalRDD.fromDataset(prevDF.queryExecution.toRdd, prevDF,
- prevDF.isStreaming).newInstance()
+ val logicalRDD = LogicalRDD.fromDataset(
+ prevDF.queryExecution.withRegularShuffle.toRdd, prevDF,
+ prevDF.isStreaming).newInstance()
prevPlan = logicalRDD
val optimizedPlan = prevDF.queryExecution.optimizedPlan
val (stats, constraints) = rewriteStatsAndConstraints(r, optimizedPlan,
@@ -284,7 +285,7 @@ case class UnionLoopExec(
}
}
val coalescedDF = df.coalesce(numPartitions)
- coalescedDF.queryExecution.toRdd
+ coalescedDF.queryExecution.withRegularShuffle.toRdd
}
}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffle.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffle.scala
new file mode 100644
index 000000000000..faa9314f1094
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffle.scala
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.adaptive
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.{BinaryExecNode, SparkPlan}
+import org.apache.spark.sql.execution.exchange.{PipelinedShuffleEligibility, ReusedExchangeExec, ShuffleExchangeExec}
+import org.apache.spark.sql.execution.joins.ShuffledJoin
+
+/**
+ * Opt-in channel shuffle rewrite under AQE. Candidates have no stats-sensitive consumer above
+ * them, or are the symmetric shuffle inputs of a join with no such consumer above the join.
+ * A SinglePartition candidate can extend the candidate chain into its child.
+ *
+ * Pipelined exchanges remain inline rather than becoming ShuffleQueryStageExec nodes, so they
+ * give up AQE coalescing and skew optimization. If any shuffle would remain regular, skip the
+ * rewrite: a mixed plan can lose its materialized outputs between actions, and the pipelined
+ * group cannot recover those outputs. Reused exchanges and unsupported consumers also retain
+ * regular execution. The shared environment gate excludes streaming, RDD and cache boundaries.
+ */
+object AQEEnablePipelinedShuffle extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ // Shared environment gate (opt-in flag, single-executor local mode, channel manager active),
+ // identical to the non-AQE rule's -- see PipelinedShuffleEligibility for why it is a
+ // correctness gate that must not drift between the two rules.
+ if (!PipelinedShuffleEligibility.enabled(plan, conf)) return plan
+
+ flipEligibleExchanges(plan)
+ }
+
+ /**
+ * The plan-shape core of the rule, factored out of [[apply]]'s environment guards (opt-in flag,
+ * local mode, channel manager) so it can be unit-tested on a hand-built plan directly. Collects
+ * the eligible exchanges and returns the plan with each flipped to `pipelined = true`.
+ */
+ private[adaptive] def flipEligibleExchanges(plan: SparkPlan): SparkPlan = {
+ val shared = if (conf.exchangeReuseEnabled) duplicatedShuffleForms(plan) else Set.empty[Any]
+ // Collect the exchanges to flip BY IDENTITY (SparkPlan.id, unique per instance), not by the
+ // node itself: TreeNode overrides hashCode but not equals, so a HashSet[ShuffleExchangeExec]
+ // matches structurally, and the transformDown below would then flip EVERY exchange
+ // structurally equal to a collected one -- including a twin the collector deliberately left
+ // regular on a blocked path. That twin, if it sits below a regular boundary, makes
+ // classifyJobShuffleShape reject the whole job. Keying on the instance id flips exactly the
+ // nodes the collector chose, regardless of spark.sql.exchange.reuse (duplicatedShuffleForms,
+ // the only other guard, is empty when reuse is off). transformDown matches each ORIGINAL node
+ // before rebuilding it, so its id is the same instance id the collector recorded.
+ val toFlip = mutable.HashSet.empty[Int]
+ collectCandidates(plan, blocked = false, shared, toFlip)
+ if (toFlip.isEmpty) return plan
+
+ // A regular prefix can lose its files between actions. The scheduler cannot recover that
+ // prefix inside a running pipelined group. Keep the entire plan regular if any
+ // exchange stays regular, including sibling branches and materialized query stages.
+ def hasRegularPrefix(p: SparkPlan): Boolean = p match {
+ case s: ShuffleExchangeExec =>
+ (!s.pipelined && !toFlip.contains(s.id)) || hasRegularPrefix(s.child)
+ case q: QueryStageExec => hasRegularPrefix(q.plan)
+ case r: ReusedExchangeExec => hasRegularPrefix(r.child)
+ case other => other.children.exists(hasRegularPrefix)
+ }
+ if (hasRegularPrefix(plan)) return plan
+ if (!PipelinedShuffleEligibility.fitsLocalCapacity(plan, toFlip.toSet)) return plan
+
+ // transformDown, NOT transformUp: candidates can be nested (a SinglePartition candidate
+ // above a hash candidate). transformUp rebuilds children first, so by the time it
+ // reaches the upper candidate that node is a NEW instance whose (already flipped) child
+ // no longer matches the collected original structurally, and the upper flip is silently
+ // dropped -- leaving a regular exchange above a pipelined one, which the scheduler then
+ // rejects. transformDown hands each candidate to the pattern before its subtree is
+ // rebuilt, so both nested flips apply.
+ plan.transformDown {
+ case s: ShuffleExchangeExec if toFlip.contains(s.id) => s.copy(pipelined = true)
+ }
+ }
+
+ private def isCandidate(s: ShuffleExchangeExec, shared: Set[Any]): Boolean =
+ !s.pipelined && !shared.contains(s.canonicalized)
+
+ /**
+ * Top-down walk collecting exchanges to flip. `blocked` is true once the path from the
+ * root has crossed a stats-sensitive node.
+ */
+ private def collectCandidates(
+ plan: SparkPlan,
+ blocked: Boolean,
+ shared: Set[Any],
+ out: mutable.HashSet[Int]): Unit = plan match {
+ case s: ShuffleExchangeExec =>
+ val flipped = !blocked && isCandidate(s, shared)
+ if (flipped) {
+ out += s.id
+ }
+ // A flipped SinglePartition exchange keeps the walk going: AQE makes no decision at
+ // it (it cannot be coalesced or skew-split), so free candidates BELOW it flip too,
+ // forming a pipelined chain: all exchanges in such a chain must flip together (a
+ // SinglePartition exchange cannot be coalesced or skew-split, so AQE makes no decision
+ // at it and free candidates below it flip too). Below any OTHER exchange (flipped or
+ // not) the walk stops: what is underneath either materializes as the prefix or feeds
+ // a regular exchange whose stats AQE uses, and keeps full AQE treatment either way.
+ if (flipped &&
+ s.outputPartitioning == org.apache.spark.sql.catalyst.plans.physical.SinglePartition) {
+ collectCandidates(s.child, blocked = false, shared, out)
+ }
+
+ case _: QueryStageExec => // already materialized; a leaf here
+
+ case j: ShuffledJoin if !blocked =>
+ // Flip the join's immediate shuffle inputs only as a symmetric pair.
+ val leftCandidate = immediateShuffleInput(j.left, shared)
+ val rightCandidate = immediateShuffleInput(j.right, shared)
+ (leftCandidate, rightCandidate) match {
+ case (Some(l), Some(r)) =>
+ out += l.id
+ out += r.id
+ case _ => // asymmetric (a broadcast side, a materialized stage, no clean input): skip
+ }
+ // Anything deeper is below a join input; blocked either way.
+
+ case p if isStatsSensitive(p) =>
+ p.children.foreach(collectCandidates(_, blocked = true, shared, out))
+
+ case p =>
+ p.children.foreach(collectCandidates(_, blocked, shared, out))
+ }
+
+ /**
+ * The single eligible [[ShuffleExchangeExec]] at the top of one join input, looking
+ * through unary non-stats-sensitive forwarders. None if the input is anything else.
+ */
+ private def immediateShuffleInput(
+ plan: SparkPlan,
+ shared: Set[Any]): Option[ShuffleExchangeExec] = plan match {
+ case s: ShuffleExchangeExec => Some(s).filter(isCandidate(_, shared))
+ case _: QueryStageExec => None
+ case p if isStatsSensitive(p) => None
+ case p if p.children.size == 1 => immediateShuffleInput(p.children.head, shared)
+ case _ => None
+ }
+
+ /** Block candidates below stats consumers and operators unsupported by the channel. */
+ private def isStatsSensitive(plan: SparkPlan): Boolean = plan match {
+ case _: BinaryExecNode => true
+ case _: ShuffleExchangeExec => true
+ case p if PipelinedShuffleEligibility.isUnsupportedConsumer(p) => true
+ case _ => false
+ }
+
+ /**
+ * Canonicalized forms of shuffle exchanges occurring more than once across the plan,
+ * materialized stages, and subquery plans -- flipping one of these loses stage reuse.
+ *
+ * Note: `ShuffleExchangeExec.pipelined` is a plain case-class field with no doCanonicalize
+ * override, so it PARTICIPATES in the canonical form. An already-flipped (pipelined = true)
+ * exchange and a structurally identical unflipped twin therefore canonicalize DIFFERENTLY and
+ * would not be paired here. The counts are taken over the CURRENT plan on each replanning
+ * round (and this rule does re-run in later rounds on a plan that may already contain an
+ * earlier round's flip -- it is NOT a before-any-flip pass). That is still safe: a flipped and
+ * an unflipped structural twin cannot coexist as a real duplicate, because reuse collapses
+ * twins (ReuseExchangeAndSubquery / ShuffleQueryStageExec) before this rule runs, and if one
+ * somehow slipped through, the DAGScheduler's fan-out check rejects a multi-consumer pipelined
+ * producer rather than producing wrong results. So missing such a pair here is fail-safe.
+ */
+ private def duplicatedShuffleForms(plan: SparkPlan): Set[Any] = {
+ val counts = mutable.HashMap.empty[Any, Int]
+ def inc(s: ShuffleExchangeExec): Unit = {
+ val c = s.canonicalized
+ counts.update(c, counts.getOrElse(c, 0) + 1)
+ }
+ def visit(p: SparkPlan): Unit = p.foreach {
+ case s: ShuffleExchangeExec => inc(s)
+ case q: ShuffleQueryStageExec =>
+ q.plan match {
+ case s: ShuffleExchangeExec => inc(s)
+ case r: ReusedExchangeExec =>
+ r.child match {
+ case s: ShuffleExchangeExec => inc(s)
+ case _ =>
+ }
+ case _ =>
+ }
+ case _ =>
+ }
+ visit(plan)
+ plan.subqueriesAll.foreach(visit)
+ counts.filter(_._2 > 1).keys.toSet
+ }
+}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AdaptiveSparkPlanExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AdaptiveSparkPlanExec.scala
index 0ef9b02d32d0..b01551cf0ad8 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AdaptiveSparkPlanExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AdaptiveSparkPlanExec.scala
@@ -158,7 +158,11 @@ case class AdaptiveSparkPlanExec(
// `RemoveRedundantSorts` runs after `OptimizeSkewedJoin` so that it can also clean up the
// local sort left dangling right below the extra shuffle that skew join optimization may
// insert between two joins.
- RemoveRedundantSorts
+ RemoveRedundantSorts,
+ // Flips the final unmaterialized tail's exchanges to pipelined (SPARK-57399 pipelined
+ // channel, opt-in). Runs last so skew handling and sort cleanup have settled
+ // before placement is decided.
+ AQEEnablePipelinedShuffle
) ++ context.session.sessionState.adaptiveRulesHolder.queryStagePrepRules
}
@@ -837,6 +841,20 @@ case class AdaptiveSparkPlanExec(
* 3) A list of the new query stages that have been created.
*/
private def createNonResultQueryStages(plan: SparkPlan): CreateStageResult = plan match {
+ // A pipelined shuffle exchange must NOT be promoted to a query stage: a pipelined
+ // producer cannot materialize on its own (its consumer must be gang-scheduled with it;
+ // the DAGScheduler rejects a map-stage job over a pipelined dependency outright).
+ // Instead it stays inline and executes inside the final result job, whose shape the
+ // scheduler accepts as a fully-materialized regular prefix (the stages created below
+ // here) plus a pipelined suffix group. Recurse through it so child stages still
+ // materialize normally.
+ case s: ShuffleExchangeExec if s.pipelined =>
+ val result = createNonResultQueryStages(s.child)
+ CreateStageResult(
+ newPlan = s.withNewChildren(Seq(result.newPlan)),
+ allChildStagesMaterialized = result.allChildStagesMaterialized,
+ newStages = result.newStages)
+
case e: Exchange =>
// First have a quick check in the `stageCache` without having to traverse down the node.
val reusedStage = if (conf.exchangeReuseEnabled) {
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/v2/OpenCursorExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/v2/OpenCursorExec.scala
index 26b89f0516c2..9f694bb51bc9 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/command/v2/OpenCursorExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/command/v2/OpenCursorExec.scala
@@ -84,7 +84,7 @@ case class OpenCursorExec(
val df = org.apache.spark.sql.classic.Dataset.ofRows(
session.asInstanceOf[org.apache.spark.sql.classic.SparkSession],
analyzedQuery)
- val resultIterator = df.queryExecution.executedPlan.executeToIterator()
+ val resultIterator = df.queryExecution.withRegularShuffle.executedPlan.executeToIterator()
// Transition cursor state to Opened with iterator
scriptingContext.updateCursorState(
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnablePipelinedShuffle.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnablePipelinedShuffle.scala
new file mode 100644
index 000000000000..56325f59f60f
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnablePipelinedShuffle.scala
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.execution.SparkPlan
+
+/**
+ * Opt-in (SPARK-57399). Rewrites EVERY [[ShuffleExchangeExec]] in a
+ * batch physical plan to `pipelined = true`, so each shuffle is served by the in-process
+ * pipelined channel manager and the concurrent-stage scheduler runs the map and reduce stages
+ * together.
+ *
+ * The rewrite considers the whole group: the scheduler requires a job to
+ * be all-pipelined (or a materialized prefix below a pipelined suffix), so choosing per exchange
+ * would produce exactly the mixed shapes it rejects. What the rule does decide is ELIGIBILITY --
+ * the environment gates in [[PipelinedShuffleEligibility]] and the plan shapes below that force the
+ * whole plan back to regular.
+ *
+ * Enabled only when `spark.sql.shuffle.localPipelined.enabled=true`. It runs in the non-AQE
+ * `preparations` list, so it also requires AQE to be off (under AQE the plan is hidden behind
+ * an opaque `AdaptiveSparkPlanExec` leaf and this rule sees no exchanges).
+ *
+ * Rewriting ALL shuffles (not just hash-partitioning ones) keeps the job all-pipelined, which
+ * the DAGScheduler requires: a mix of pipelined and regular shuffles in one job is rejected.
+ * SinglePartition and RangePartitioning exchanges pipeline fine -- the channel transport only
+ * routes by `partitioner.getPartition(key)` and does not care which partitioning produced the
+ * id (SinglePartition is the numPartitions == 1 degenerate case).
+ *
+ * These shapes make the rule leave the whole plan regular:
+ * - the estimated producer and consumer widths cannot fit local task capacity.
+ * - Dataset.rdd deserialization and cached inputs (the shared eligibility gate): their actual
+ * shuffle readers depend on consumers or cache availability outside this plan.
+ * - reuse: a pipelined producer with more than one consumer (fan-out) is rejected, so if any
+ * exchange in the plan is reused the rule bails out.
+ * - an UNSUPPORTED CONSUMER reading a shuffle (see [[readsShuffleThroughUnsupportedConsumer]]):
+ * an operator that would drain a shuffle in a way the channel transport cannot serve, or that
+ * builds its own hidden regular shuffle. If such an operator sits above any shuffle the rule
+ * leaves the WHOLE plan regular (leaving only that one exchange regular would put a pipelined
+ * exchange below a regular boundary, which the scheduler rejects -- so it is all-or-nothing).
+ * The query runs correctly, just not pipelined. The unsupported consumers are:
+ * - `CoalesceExec` (user `.coalesce(n)`): its `CoalescedRDD` makes ONE reduce task drain
+ * SEVERAL reduce partitions sequentially. The single-threaded writer parks on a full
+ * bounded queue filling a later partition before emitting an earlier one's markers, so a
+ * reader draining partitions in order deadlocks the writer with no timeout escape;
+ * `coalesce`'s narrow-merge contract also cannot be honored by re-hashing to `n`.
+ * - `CartesianProductExec`: its `UnsafeCartesianRDD` reads each left (child) partition once
+ * per right partition, so N reduce tasks mint N readers on the SAME rendezvous queue for
+ * one `(shuffleId, epoch, pid)` -- rows and end-of-stream markers split
+ * nondeterministically (wrong results), a reader short of `numMaps` markers hangs, and
+ * the first to finish abandons the queue and discards the others' data. The fan-out check
+ * does not catch it (one consumer RDD, computed many times), nor the width-1 require.
+ * - `CollectLimitExec` / `CollectTailExec` / `TakeOrderedAndProjectExec`: each builds a
+ * hidden regular (`pipelined = false`) shuffle inside `doExecute` via
+ * `prepareShuffleDependency`, invisible to this plan walk. A flipped exchange below one of
+ * them would sit under that unmaterialized regular boundary and the job would hard-fail at
+ * submission (`classifyJobShuffleShape`'s pipelined-below-regular rejection). (`.collect()`
+ * on a limit takes `executeTake` and never hits `doExecute`; `.write` / `.toLocalIterator`
+ * / a non-root position do.)
+ */
+object EnablePipelinedShuffle extends Rule[SparkPlan] {
+
+ override def apply(plan: SparkPlan): SparkPlan = {
+ // Shared environment gate (opt-in flag, single-executor local mode, channel manager active),
+ // identical to the AQE rule's -- see PipelinedShuffleEligibility for why it is a correctness
+ // gate. It also requires AQE off implicitly: under AQE this rule sees no exchanges.
+ if (!PipelinedShuffleEligibility.enabled(plan, conf)) return plan
+
+ val shuffles = plan.collect { case s: ShuffleExchangeExec => s }
+ if (shuffles.isEmpty) return plan
+
+ // A reused exchange has more than one consumer; a pipelined producer cannot fan out, so
+ // leave the whole plan regular rather than produce a rejected job. Check subquery plans
+ // too (plan.exists walks the operator tree only): today no SQL shape can place a reused
+ // PIPELINED exchange there -- same-tree reuse is caught here, main-vs-subquery reuse
+ // never fires because the subquery's own preparation pass (PlanSubqueries ->
+ // prepareExecutedPlan, which includes this rule) flips its exchanges pipelined BEFORE
+ // the outer ReuseExchangeAndSubquery compares canonical forms, and subquery-vs-subquery
+ // duplication is collapsed by MergeScalarSubqueries / subquery reuse first -- but the
+ // second mechanism is an accident of rule ordering and the third is optimizer behavior,
+ // so this gate does not rely on either.
+ if (plan.collectWithSubqueries { case r: ReusedExchangeExec => r }.nonEmpty) {
+ // Not a warning: this is a normal, expected fallback (reuse is routine optimizer output,
+ // e.g. self-joins), the query still runs correctly as a regular shuffle, and the user has
+ // nothing to act on. Log at DEBUG as diagnostic ("why this query did not go pipelined")
+ // rather than WARN, which would fire on every reuse-bearing query and read as a fault.
+ logDebug("EnablePipelinedShuffle: plan has a reused exchange; leaving it regular to " +
+ "avoid a fan-out pipelined job.")
+ return plan
+ }
+
+ // An operator that would read a shuffle in a way the channel transport cannot serve, or that
+ // builds its own hidden regular shuffle, forces the whole plan regular (see class doc). Like
+ // the reuse fallback this is a normal, expected outcome, so log at DEBUG rather than WARN.
+ if (readsShuffleThroughUnsupportedConsumer(plan)) {
+ logDebug("EnablePipelinedShuffle: a shuffle is read through an operator the channel " +
+ "transport cannot serve (coalesce / cartesian product / a limit operator that builds a " +
+ "hidden shuffle); leaving the plan regular.")
+ return plan
+ }
+
+ if (!PipelinedShuffleEligibility.fitsLocalCapacity(plan, shuffles.map(_.id).toSet)) {
+ return plan
+ }
+
+ plan.transformUp {
+ case s: ShuffleExchangeExec if !s.pipelined => s.copy(pipelined = true)
+ }
+ }
+
+ /**
+ * True if any [[ShuffleExchangeExec]] in `plan` is read by an operator the channel transport
+ * cannot serve. The unsupported operators (see class doc for why each is fatal) are
+ * `CoalesceExec`, `CartesianProductExec`, and the limit operators `CollectLimitExec` /
+ * `CollectTailExec` / `TakeOrderedAndProjectExec`. For each such operator anywhere in the plan,
+ * check whether a shuffle is reachable below it.
+ *
+ * The reachability walk descends through EVERY child of a non-exchange node -- not only unary
+ * children -- so a shuffle behind a `UnionExec`/join (a `BinaryExecNode`) beneath the operator
+ * is still found. It stops at the FIRST [[ShuffleExchangeExec]] on each path: a shuffle deeper
+ * than that first one is not read by this operator (the intervening exchange's own reader reads
+ * one reduce partition per task), so it is not this operator's concern.
+ */
+ private def readsShuffleThroughUnsupportedConsumer(plan: SparkPlan): Boolean = {
+ def reachesShuffle(p: SparkPlan): Boolean = p match {
+ case _: ShuffleExchangeExec => true
+ case other => other.children.exists(reachesShuffle)
+ }
+ plan.exists {
+ case p if PipelinedShuffleEligibility.isUnsupportedConsumer(p) =>
+ p.children.exists(reachesShuffle)
+ case _ => false
+ }
+ }
+}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleEligibility.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleEligibility.scala
new file mode 100644
index 000000000000..9c9b57daa8a6
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleEligibility.scala
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import java.util.concurrent.atomic.AtomicBoolean
+
+import org.apache.spark.SparkEnv
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.config
+import org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager
+import org.apache.spark.sql.execution.{CoalesceExec, CollectLimitExec, CollectTailExec, DeserializeToObjectExec, ExternalRDDScanExec, RDDScanExec, SparkPlan, TakeOrderedAndProjectExec}
+import org.apache.spark.sql.execution.adaptive.QueryStageExec
+import org.apache.spark.sql.execution.columnar.InMemoryTableScanExec
+import org.apache.spark.sql.execution.joins.CartesianProductExec
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Shared environment gate for the two pipelined-shuffle enabling rules
+ * ([[EnablePipelinedShuffle]] non-AQE and `AQEEnablePipelinedShuffle` under AQE). This is a
+ * CORRECTNESS gate, not cosmetics: flipping an exchange to pipelined while the incremental manager
+ * is still the RPC streaming one would route it to an untested transport that reports
+ * `requiresDetachedRecords = false`, so the SQL layer would skip the row copy and silently corrupt
+ * rows shared across the writer/reader threads. Both rules must apply the identical gate, so it
+ * lives here rather than being copy-pasted into each `apply` (where the two could drift and split
+ * AQE vs non-AQE behavior). Each rule keeps only its own plan-shape logic.
+ */
+private[sql] object PipelinedShuffleEligibility extends Logging {
+
+ // The flag/manager mismatch is a start-up misconfiguration, so warn once per JVM rather than on
+ // every query planned in the session.
+ private val mismatchWarned = new AtomicBoolean(false)
+
+ /** Operators whose consumers cannot safely drain a bounded, single-reader channel. */
+ def isUnsupportedConsumer(plan: SparkPlan): Boolean = plan match {
+ case _: CoalesceExec | _: CartesianProductExec | _: DeserializeToObjectExec |
+ _: CollectLimitExec | _: CollectTailExec | _: TakeOrderedAndProjectExec => true
+ case _ => false
+ }
+
+ /**
+ * Estimate the complete group's task demand without executing or materializing the plan.
+ * Each exchange contributes its producer width; the root contributes the consumer width.
+ * Unknown widths conservatively retain regular execution. The scheduler still checks actual
+ * RDD widths and free slots at submission, including contention from other jobs.
+ */
+ def fitsLocalCapacity(plan: SparkPlan, candidates: Set[Int]): Boolean = {
+ val exchanges = plan.collect {
+ case s: ShuffleExchangeExec if s.pipelined || candidates.contains(s.id) => s
+ }.groupBy(_.id).values.map(_.head).toSeq
+ val widths = plan.outputPartitioning.numPartitions +:
+ exchanges.map(_.child.outputPartitioning.numPartitions)
+ val sc = plan.session.sparkContext
+ val slots = sc.maxNumConcurrentTasks(sc.resourceProfileManager.defaultResourceProfile)
+ val demand = widths.map(_.toLong).sum
+ val fits = widths.forall(_ > 0) && demand <= slots
+ if (!fits) {
+ logDebug(s"Pipelined shuffle: estimated stage widths ${widths.mkString(",")} cannot " +
+ s"fit $slots local task slots; retaining regular shuffles.")
+ }
+ fits
+ }
+
+ /**
+ * Whether the pipelined channel transport may be used for `plan` at all, independent of plan
+ * shape. Requires: the opt-in flag on; single-executor local mode (the in-process channel
+ * transport needs producer and consumer in one JVM); and the configured incremental manager
+ * actually being the in-process channel manager. Returns false (with a DEBUG diagnostic) when
+ * any gate fails, so the caller leaves the plan regular.
+ */
+ def enabled(plan: SparkPlan, conf: SQLConf): Boolean = {
+ if (!conf.localPipelinedShuffleEnabled) {
+ return false
+ }
+ if (plan.session == null || !plan.session.sparkContext.isLocal) {
+ return false
+ }
+ // Batch only. `IncrementalExecution.preparations` inherits QueryExecution's list, so without
+ // this gate a streaming plan would be rewritten here: every micro-batch exchange (the
+ // state-store shuffles, the static side of a stream-static join) would be flipped to pipelined
+ // BEFORE `MarkPipelinedShuffleForRealTimeMode` runs. That contradicts what the Real-Time Mode
+ // rule deliberately does -- it leaves the static side regular, because pulling it into the gang
+ // would demand slots for stages that must instead finish first, failing admission. Streaming
+ // marks its own pipelined boundaries; this opt-in batch path must not pre-empt that decision.
+ // (`logicalLink.exists(_.isStreaming)` is the same signal InsertAdaptiveSparkPlan uses to keep
+ // AQE off streaming plans.)
+ // Dataset.rdd exposes arbitrary consumers beyond the SQL plan, including RDD shuffles,
+ // multi-partition reads and repeated reads of the same partition. Cached inputs also hide
+ // shuffle lineage: cache hits skip those readers, while misses may require regular stages.
+ // RDD scans can hide arbitrary shuffle lineage and sharing outside the SQL plan as well.
+ def hasUnsupportedBoundary(p: SparkPlan): Boolean = p match {
+ case _: DeserializeToObjectExec | _: InMemoryTableScanExec |
+ _: RDDScanExec | _: ExternalRDDScanExec[_] => true
+ case q: QueryStageExec => hasUnsupportedBoundary(q.plan)
+ case other => other.children.exists(hasUnsupportedBoundary)
+ }
+ if (hasUnsupportedBoundary(plan)) return false
+ if (plan.exists(_.logicalLink.exists(_.isStreaming))) {
+ logDebug("Pipelined shuffle: the plan is a streaming plan; leaving it to the streaming " +
+ "engine's own pipelined-shuffle marking.")
+ return false
+ }
+ if (!SparkEnv.get.pipelinedShuffleManager.isInstanceOf[PipelinedChannelShuffleManager]) {
+ // WARN, not DEBUG, and once per JVM: the user asked for this feature and is silently not
+ // getting it, which no plan or metric reveals. The flag alone cannot select the transport --
+ // the manager is a separate, start-up-only config -- so the mismatch is a misconfiguration
+ // the user has to act on, unlike the plan-shape fallbacks (reuse, coalesce) which are normal
+ // outcomes and stay at DEBUG.
+ if (mismatchWarned.compareAndSet(false, true)) {
+ logWarning(s"${SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED.key} is enabled but " +
+ s"${config.SHUFFLE_MANAGER_INCREMENTAL.key} is not the in-process channel manager, so " +
+ s"no shuffle will be pipelined. Set it to " +
+ s"${classOf[PipelinedChannelShuffleManager].getName} to enable the feature, or unset " +
+ s"the SQL flag to silence this warning.")
+ }
+ return false
+ }
+ true
+ }
+}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/ShuffleExchangeExec.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/ShuffleExchangeExec.scala
index 891ac2233889..bbd9196f9bfa 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/ShuffleExchangeExec.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/ShuffleExchangeExec.scala
@@ -206,9 +206,8 @@ case class ShuffleExchangeExec(
override def nodeName: String = "Exchange"
- // `pipelined` is only meaningful for a Real-Time Mode plan, and the default arg string is
- // positional, so printing it unconditionally would add a bare `false` to every shuffle in every
- // plan. Show it only when set, and name it when shown.
+ // The default arg string is positional, so printing `pipelined` unconditionally would add a bare
+ // `false` to every shuffle in every plan. Show it only when set, and name it when shown.
override def stringArgs: Iterator[Any] = {
// `pipelined` is the last field, so drop it positionally rather than by value; argString drops
// the child on its own. Exchange's `[plan_id=...]` suffix is re-appended here.
@@ -307,15 +306,18 @@ object ShuffleExchangeExec {
* @param partitioner the partitioner for the shuffle
* @return true if rows should be copied before being shuffled, false otherwise
*/
- private def needToCopyObjectsBeforeShuffle(partitioner: Partitioner): Boolean = {
+ private def needToCopyObjectsBeforeShuffle(
+ partitioner: Partitioner,
+ pipelined: Boolean): Boolean = {
+ if (pipelined) {
+ return SparkEnv.get.pipelinedShuffleManager.requiresDetachedRecords
+ }
// Note: even though we only use the partitioner's `numPartitions` field, we require it to be
// passed instead of directly passing the number of partitions in order to guard against
// corner-cases where a partitioner constructed with `numPartitions` partitions may output
// fewer partitions (like RangePartitioner, for example).
val conf = SparkEnv.get.conf
- // This decision concerns the regular (materialized) shuffle path only. A pipelined shuffle is
- // served by a separate pipelined manager (see SparkEnv.shuffleManagerFor) and does not go
- // through here, so inspect the blocking manager's type directly.
+ // The remaining cases concern the regular shuffle manager.
val shuffleManager = SparkEnv.get.blockingShuffleManager
val sortBasedShuffleOn = shuffleManager.isInstanceOf[SortShuffleManager]
val bypassMergeThreshold = conf.get(config.SHUFFLE_SORT_BYPASS_MERGE_THRESHOLD)
@@ -562,7 +564,7 @@ object ShuffleExchangeExec {
// would reject a chain of round-robin repartitions rather than protect anything.
val isOrderSensitive = (isRoundRobin || isNullAwareHashPartitioning) &&
!SQLConf.get.sortBeforeRepartition && !pipelined
- if (needToCopyObjectsBeforeShuffle(part)) {
+ if (needToCopyObjectsBeforeShuffle(part, pipelined)) {
newRdd.mapPartitionsWithIndexInternal((_, iter) => {
val getPartitionKey = getPartitionKeyExtractor()
iter.map { row => (part.getPartition(getPartitionKey(row)), row.copy()) }
@@ -616,10 +618,7 @@ object ShuffleExchangeExec {
dependency
}
- /**
- * Create a customized [[ShuffleWriteProcessor]] for SQL which wrap the default metrics reporter
- * with [[SQLShuffleWriteMetricsReporter]] as new reporter for [[ShuffleWriteProcessor]].
- */
+ /** Create the SQL shuffle metrics reporter shared by both shuffle transports. */
def createShuffleWriteProcessor(metrics: Map[String, SQLMetric]): ShuffleWriteProcessor = {
new ShuffleWriteProcessor {
override protected def createMetricsReporter(
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffleRuleSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffleRuleSuite.scala
new file mode 100644
index 000000000000..4d4a0d93c826
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffleRuleSuite.scala
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.adaptive
+
+import org.apache.spark.sql.QueryTest
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
+import org.apache.spark.sql.execution.{SparkPlan, UnionExec}
+import org.apache.spark.sql.execution.exchange.ShuffleExchangeExec
+import org.apache.spark.sql.execution.joins.SortMergeJoinExec
+import org.apache.spark.sql.test.SharedSparkSession
+
+/** Plan-level coverage of the conservative AQE channel eligibility policy. */
+class AQEEnablePipelinedShuffleRuleSuite extends QueryTest with SharedSparkSession {
+
+ private def exchangesWithPipelined(plan: SparkPlan): Seq[Boolean] =
+ plan.collect { case s: ShuffleExchangeExec => s.pipelined }
+
+ test("a regular sibling prevents a mixed pipelined job") {
+ // A free candidate and its blocked twin would form a mixed job. The regular sibling must
+ // remain recoverable across actions, so the entire plan must retain regular shuffles.
+ withSQLConf("spark.sql.exchange.reuse" -> "false") {
+ import testImplicits._
+ val leaf = spark.range(10).select($"id" as Symbol("k")).queryExecution.executedPlan
+ val hp = HashPartitioning(leaf.output, 4)
+
+ val otherLeaf = spark.range(10).select($"id" as Symbol("k")).queryExecution.executedPlan
+
+ // E1: free twin as a UnionExec child
+ val freeTwin = ShuffleExchangeExec(hp, leaf)
+
+ // E2: blocked twin inside the join's left input (same partitioning, same leaf child)
+ val blockedTwin = ShuffleExchangeExec(hp, leaf)
+ // Join with E2 on the left, otherLeaf on the right (asymmetric, so no join-paired flip)
+ val join = SortMergeJoinExec(
+ leaf.output, otherLeaf.output, Inner, None, blockedTwin, otherLeaf)
+
+ // A candidate and a blocked sibling must not become a mixed result job.
+ val root = UnionExec(Seq(freeTwin, join))
+
+ val rule = AQEEnablePipelinedShuffle
+ val flipped = rule.flipEligibleExchanges(root)
+
+ val flippedUnion = flipped match {
+ case u: UnionExec => u
+ case other => fail(s"expected a top UnionExec; got:\n$other")
+ }
+ assert(exchangesWithPipelined(flippedUnion) == Seq(false, false),
+ s"both branches must stay regular so the sibling can recover lost outputs: $flipped")
+ }
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEPipelinedShuffleSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEPipelinedShuffleSuite.scala
new file mode 100644
index 000000000000..417c6cdeb4cd
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/adaptive/AQEPipelinedShuffleSuite.scala
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.adaptive
+
+import java.util.concurrent.{Executors, TimeUnit}
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.execution.exchange.{PipelinedShuffleTestSession, ShuffleExchangeExec}
+
+/** End-to-end coverage of channel eligibility and regular-shuffle fallbacks under AQE. */
+class AQEPipelinedShuffleSuite extends SparkFunSuite
+ with AdaptiveSparkPlanHelper with PipelinedShuffleTestSession {
+
+ private def withAqePipelinedSession(body: SparkSession => Unit): Unit =
+ withPipelinedSession("aqe-pipelined-shuffle", aqe = true)(body)
+
+ private def pipelinedExchanges(plan: org.apache.spark.sql.execution.SparkPlan) =
+ collect(plan) { case s: ShuffleExchangeExec if s.pipelined => s }
+
+ private def materializedStages(plan: org.apache.spark.sql.execution.SparkPlan) =
+ collect(plan) { case q: ShuffleQueryStageExec => q }
+
+ test("single-exchange aggregate pipelines the whole final job under AQE") {
+ withAqePipelinedSession { spark =>
+ import spark.implicits._
+ // Keep ONE Dataset for both execution and plan inspection: .as[...] creates a new
+ // QueryExecution, and asserting on an unexecuted sibling would see the initial
+ // adaptive plan (isFinalPlan=false), not the executed one.
+ val ds = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 7))
+ .groupBy($"k").count().as[(Long, Long)]
+
+ val counts = ds.collect().toMap
+ val plan = ds.queryExecution.executedPlan
+ assert(pipelinedExchanges(plan).nonEmpty,
+ s"expected the sole exchange pipelined; plan:\n$plan")
+ assert(materializedStages(plan).isEmpty,
+ s"no exchange should have materialized as a stage; plan:\n$plan")
+ val expected = (0L until 1000L).groupBy(_ % 7).map { case (k, vs) => (k, vs.size.toLong) }
+ assert(counts === expected)
+ }
+ }
+
+ test("an AQE regular prefix remains recoverable across repeated actions") {
+ withAqePipelinedSession { spark =>
+ import spark.implicits._
+ val ds = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 7))
+ .groupBy($"k").count().orderBy($"k").as[(Long, Long)]
+
+ val rows = ds.collect()
+ val plan = ds.queryExecution.executedPlan
+ assert(pipelinedExchanges(plan).isEmpty,
+ s"a regular prefix must not feed a pipelined tail; plan:\n$plan")
+ assert(materializedStages(plan).nonEmpty,
+ s"expected the groupBy exchange materialized as a regular stage; plan:\n$plan")
+ val expected = (0L until 1000L).groupBy(_ % 7).map { case (k, vs) => (k, vs.size.toLong) }
+ .toSeq.sortBy(_._1)
+ assert(rows.toSeq === expected)
+ // Local cleanup unregisters the output; the next action recomputes unavailable stages.
+ // This exercises repeated regular execution, not a FetchFailed retry.
+ assert(ds.collect().toSeq === expected)
+ assert(ds.collect().toSeq === expected)
+ }
+ }
+
+ test("shuffled join inputs flip as a symmetric pair under AQE") {
+ withAqePipelinedSession { spark =>
+ import spark.implicits._
+ // Keep the join a shuffled join: disable both static and adaptive broadcast switching.
+ spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ spark.conf.set("spark.sql.adaptive.autoBroadcastJoinThreshold", "-1")
+ val left = spark.range(0, 200, 1, 2).withColumn("k", ($"id" % 10))
+ .select($"k", $"id".as("lv"))
+ val right = spark.range(0, 120, 1, 2).withColumn("k", ($"id" % 6))
+ .select($"k", $"id".as("rv"))
+ val joined = left.join(right, "k")
+ .select($"k", $"lv", $"rv").as[(Long, Long, Long)]
+
+ val rows = joined.collect()
+ val plan = joined.queryExecution.executedPlan
+ assert(pipelinedExchanges(plan).size === 2,
+ s"expected both join inputs pipelined as a pair; plan:\n$plan")
+
+ val l = (0L until 200L).map(i => (i % 10, i))
+ val r = (0L until 120L).map(i => (i % 6, i))
+ val expected = (for ((lk, lv) <- l; (rk, rv) <- r if lk == rk) yield (lk, lv, rv)).toSet
+ assert(rows.toSet === expected)
+ }
+ }
+
+ test("default shuffle width retains regular AQE execution") {
+ withPipelinedSession("aqe-pipelined-default-width", aqe = true, cores = 8) { spark =>
+ import spark.implicits._
+ spark.conf.unset("spark.sql.shuffle.partitions")
+ assert(spark.conf.get("spark.sql.shuffle.partitions") === "200")
+ val ds = spark.range(0, 1000, 1, 2).groupBy(($"id" % 7).as("k")).count()
+ assert(ds.collect().map(_.getLong(1)).sum === 1000L)
+ assert(pipelinedExchanges(ds.queryExecution.executedPlan).isEmpty)
+ assert(materializedStages(ds.queryExecution.executedPlan).nonEmpty)
+ }
+ }
+
+ test("results match the regular AQE baseline on the prefix + tail shape") {
+ withAqePipelinedSession { spark =>
+ import spark.implicits._
+ def run(): Seq[(Long, Long)] = {
+ spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 13))
+ .groupBy($"k").count().orderBy($"k".desc)
+ .as[(Long, Long)].collect().toSeq
+ }
+ spark.conf.set("spark.sql.shuffle.localPipelined.enabled", "false")
+ val baseline = run()
+ spark.conf.set("spark.sql.shuffle.localPipelined.enabled", "true")
+ val pipelined = run()
+ assert(pipelined === baseline)
+ }
+ }
+
+ test("coalesce over a shuffle stays regular under AQE") {
+ // A CoalesceExec reading from a shuffle drains several reduce partitions per task (a
+ // CoalescedRDD over the ShuffledRowRDD), which the channel transport cannot serve without
+ // deadlocking (see EnablePipelinedShuffle / ChannelShuffleReader). AQEEnablePipelinedShuffle
+ // blocks below a CoalesceExec (it is stats-sensitive for this purpose), so the shuffle it
+ // reads -- and everything deeper -- stays regular. The query still runs correctly. Guard with
+ // a deadline so a regression (the shuffle went pipelined and the coalesced read hung) surfaces
+ // as a failure rather than a hung suite.
+ val pool = Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new Runnable {
+ override def run(): Unit = withAqePipelinedSession { spark =>
+ import spark.implicits._
+ // Enough rows that a regression would fill a bounded queue and truly deadlock, not fit.
+ val ds = spark.range(0, 2000000L, 1, 4).withColumn("k", ($"id" % 10))
+ .groupBy($"k").count().coalesce(2).as[(Long, Long)]
+ val n = ds.collect().length
+ require(n == 10, s"expected 10 groups, got $n")
+ val plan = ds.queryExecution.executedPlan
+ require(pipelinedExchanges(plan).isEmpty,
+ s"coalesce over a shuffle must stay regular under AQE; found a pipelined exchange:" +
+ s"\n$plan")
+ }
+ })
+ try {
+ fut.get(90, TimeUnit.SECONDS)
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ fail("coalesce over a pipelined shuffle hung under AQE: the shuffle was pipelined " +
+ "despite a coalesce reading it, and the coalesced read deadlocked the writer")
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedLimitHangSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedLimitHangSuite.scala
new file mode 100644
index 000000000000..43b7ab18d638
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedLimitHangSuite.scala
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import java.util.concurrent.{Executors, TimeUnit}
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+
+/**
+ * SQL-level acceptance tests for LIMIT over a plan that CONTAINS a pipelined-eligible shuffle
+ * (SPARK-57399).
+ *
+ * IMPORTANT -- what these tests do and do NOT cover. A LIMIT operator
+ * (`CollectLimitExec` / `CollectTailExec` / `TakeOrderedAndProjectExec`) builds a hidden REGULAR
+ * shuffle inside its `doExecute` (`prepareShuffleDependency` with `pipelined = false`) that no plan
+ * walk can see. A pipelined exchange beneath it would sit under an unmaterialized regular boundary
+ * and the job would hard-fail at submission, so `EnablePipelinedShuffle` /
+ * `AQEEnablePipelinedShuffle` refuse to pipeline a plan containing such an operator above a
+ * shuffle. Consequently these LIMIT shapes now run as REGULAR shuffles, and these tests assert
+ * exactly that (fallback + correct results) -- they can no longer exercise the writer/reader
+ * early-stop machinery.
+ *
+ * The early-stop and live-reduce-set machinery (`ChannelShuffleWriter.putUnlessAbandoned` /
+ * `ChannelShuffleRendezvous.abandon` / `DAGScheduler.liveReduceSet`) is covered instead by the
+ * RDD-level partial-read tests in `PipelinedChannelShuffleSuite` ("partial read ... completes"),
+ * which drive a real partial read over a pipelined shuffle without a LIMIT operator in the way.
+ *
+ * Each test builds and stops its OWN SparkSession (withSession), so they do not share process
+ * state and one test's timeout/cancel cannot affect the other.
+ */
+class PipelinedLimitHangSuite extends SparkFunSuite
+ with AdaptiveSparkPlanHelper with PipelinedShuffleTestSession {
+
+ private def withSession(aqe: Boolean)(body: SparkSession => Unit): Unit =
+ withPipelinedSession("pipelined-limit-hang", aqe)(body)
+
+ /**
+ * Runs `query(spark)` on a background thread under a deadline, returning true iff it both
+ * COMPLETES (no writer hang) and produces 10 rows. Each query is a partial read (LIMIT) over one
+ * Each shape asserts BOTH that the plan fell back to a regular shuffle (no exchange is
+ * pipelined -- a LIMIT operator's hidden shuffle makes pipelining unsafe, see the class doc) and
+ * that the query returns the right rows. The deadline stays so that a regression which DID
+ * pipeline such a plan surfaces as a timeout (the hidden-shuffle hard-fail or a writer hang)
+ * rather than a hung suite.
+ */
+ private def completesWithin(seconds: Int, aqe: Boolean)(
+ query: SparkSession => Int): Boolean = {
+ val pool = Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new Runnable {
+ override def run(): Unit = withSession(aqe) { spark =>
+ val rows = query(spark)
+ require(rows == 10, s"expected 10 rows, got $rows")
+ }
+ })
+ try {
+ fut.get(seconds.toLong, TimeUnit.SECONDS)
+ true
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ false
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+
+ /** Assert no exchange in `df`'s executed plan is pipelined (the LIMIT fallback). */
+ private def requireNotPipelined(df: org.apache.spark.sql.DataFrame): Unit = {
+ val pipelined = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ require(pipelined.isEmpty,
+ s"a plan with a LIMIT operator above a shuffle must stay regular; plan:" +
+ s"\n${df.queryExecution.executedPlan}")
+ }
+
+ // Many input rows per partition so a regression that pipelined this would really park a writer.
+ private def repartitionLimit(spark: SparkSession): Int = {
+ import spark.implicits._
+ val df = spark.range(0, 5000000L, 1, 4).withColumn("k", ($"id" % 100))
+ .repartition($"k").limit(10)
+ val n = df.collect().length
+ requireNotPipelined(df)
+ n
+ }
+
+ // union() over two pipelined shuffles: the result RDD reaches each shuffle through a
+ // RangeDependency whose getParents applies a per-branch offset, and it fans in over two
+ // branches -- liveReduceSet must map the live set through both branches' offsets.
+ private def unionLimit(spark: SparkSession): Int = {
+ import spark.implicits._
+ val a = spark.range(0, 2500000L, 1, 4).withColumn("k", ($"id" % 100)).repartition($"k")
+ val b = spark.range(0, 2500000L, 1, 4).withColumn("k", ($"id" % 100)).repartition($"k")
+ val df = a.union(b).limit(10)
+ val n = df.collect().length
+ requireNotPipelined(df)
+ n
+ }
+
+ // join() over two pipelined shuffles: the result RDD fans in over a ZippedPartitionsRDD, one
+ // OneToOne branch per side down to that side's shuffle -- liveReduceSet must contribute the live
+ // set from every branch that reaches a given shuffle.
+ private def joinLimit(spark: SparkSession): Int = {
+ import spark.implicits._
+ val a = spark.range(0, 2500000L, 1, 4).withColumn("k", ($"id" % 100))
+ val b = spark.range(0, 2500000L, 1, 4).withColumn("k2", ($"id" % 100))
+ val df = a.join(b, a("k") === b("k2")).limit(10)
+ val n = df.collect().length
+ requireNotPipelined(df)
+ n
+ }
+
+ for (aqe <- Seq(false, true)) {
+ val mode = if (aqe) "AQE on" else "AQE off"
+
+ test(s"LIMIT over a shuffle falls back to regular and is correct ($mode)") {
+ assert(completesWithin(90, aqe)(repartitionLimit),
+ "LIMIT over a shuffle should fall back to regular and complete correctly")
+ }
+
+ test(s"union + LIMIT falls back to regular and is correct ($mode)") {
+ assert(completesWithin(90, aqe)(unionLimit),
+ "union + LIMIT should fall back to regular and complete correctly")
+ }
+
+ test(s"join + LIMIT falls back to regular and is correct ($mode)") {
+ assert(completesWithin(90, aqe)(joinLimit),
+ "join + LIMIT should fall back to regular and complete correctly")
+ }
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleBenchmark.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleBenchmark.scala
new file mode 100644
index 000000000000..102ea50bf5e9
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleBenchmark.scala
@@ -0,0 +1,459 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.benchmark.Benchmark
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.execution.benchmark.SqlBasedBenchmark
+
+/**
+ * Benchmark to compare the in-process pipelined channel shuffle against the regular
+ * (materializing) shuffle on simple batch queries (SPARK-57399).
+ *
+ * Fair-comparison constraints, read before trusting any number:
+ * - Runs on `local[N]` with N the core count the shape is sized for (the machine's, or the
+ * -Dspark.pipelinedBenchmark.cores override), and the workload shapes are derived so every
+ * query's pipelined whole-group slot demand is <= N -- so the concurrently-scheduled pipelined
+ * stages do NOT oversubscribe the cores. A demand > N run would measure thread thrash, not the
+ * transport, and is intentionally avoided here.
+ * - Pipelined overlaps map+reduce stages (uses more concurrent slots) vs the baseline's
+ * sequential map-then-reduce; with demand <= cores neither is slot-limited, so the delta
+ * reflects stage overlap minus channel overhead, which is the honest comparison.
+ *
+ * To run this benchmark:
+ * {{{
+ * 1. build/sbt "sql/Test/runMain
+ * org.apache.spark.sql.execution.exchange.PipelinedShuffleBenchmark"
+ * 2. generate result: SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt
+ * "sql/Test/runMain
+ * org.apache.spark.sql.execution.exchange.PipelinedShuffleBenchmark"
+ * Results will be written to
+ * "sql/core/benchmarks/PipelinedShuffleBenchmark-jdk<version>-results.txt".
+ * Add -Dspark.pipelinedBenchmark.cores=4 to size the shape as the benchmark workflow's
+ * runner does.
+ * }}}
+ */
+object PipelinedShuffleBenchmark extends SqlBasedBenchmark {
+
+ override def getSparkSession: SparkSession = {
+ SparkSession.builder()
+ .master("local[1]")
+ .appName(this.getClass.getCanonicalName)
+ .config("spark.ui.enabled", "false")
+ .getOrCreate()
+ }
+
+ // Cores the shape is sized for. Defaults to the machine, but can be pinned with
+ // -Dspark.pipelinedBenchmark.cores=N to reproduce the checked-in results (generated at the 4
+ // cores the benchmark workflow's runner provides) on a larger machine.
+ private val cores =
+ sys.props.get("spark.pipelinedBenchmark.cores").map(_.toInt)
+ .getOrElse(Runtime.getRuntime.availableProcessors())
+ private val numRows = 20000000L // 20M: large enough that transport cost dominates startup
+
+ // A pipelined group gang-schedules every member stage at once, so the whole-group slot demand
+ // must fit the machine or the run does not just get slower -- it fails admission with
+ // CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT. The demand is the FINAL stage's partition count plus
+ // the MAP-side width of every distinct pipelined shuffle in the job (see
+ // DAGScheduler.pipelinedJobConcurrentTaskDemand), so it depends on the workload's shape, not
+ // just on one exchange: the widest shape below is a two-exchange chain
+ // (groupBy(k).count+orderBy(k)), whose second exchange takes the first's reduce side as its map
+ // side, giving
+ // inputParts + shufflePartitions (groupBy map) + shufflePartitions (orderBy map) + 1
+ // Size both knobs off that worst case so EVERY workload in this file is admissible, and derive
+ // them from the machine so the standard benchmark workflow (ubuntu-latest, 4 cores) can
+ // regenerate this file: on 4 cores the shape is 1 + 1 + 1 + 1 = 4. A bigger machine gets a wider
+ // shape, capped so the numbers stay about the transport rather than about thread count.
+ private val shufflePartitions = math.max(1, math.min(8, (cores - 2) / 3))
+ private val inputParts =
+ math.max(1, math.min(6, cores - 2 * shufflePartitions - 1))
+
+ private val channelManagerClass =
+ "org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager"
+
+ private def buildSession(
+ pipelined: Boolean,
+ shufflePartitions: Int,
+ master: String,
+ aqe: Boolean): SparkSession = {
+ val b = SparkSession.builder()
+ .master(master)
+ .appName("pipelined-shuffle-benchmark")
+ .config("spark.sql.adaptive.enabled", aqe.toString)
+ .config("spark.speculation", "false")
+ .config("spark.sql.shuffle.partitions", shufflePartitions.toString)
+ .config("spark.ui.enabled", "false")
+ if (pipelined) {
+ b.config("spark.shuffle.manager.incremental", channelManagerClass)
+ .config("spark.sql.shuffle.localPipelined.enabled", "true")
+ }
+ b.getOrCreate()
+ }
+
+ private def buildTransportSession(
+ mode: String, shufflePartitions: Int): SparkSession = {
+ val b = SparkSession.builder()
+ .master(s"local[$cores]")
+ .appName("pipelined-transport-benchmark")
+ .config("spark.sql.adaptive.enabled", "false")
+ .config("spark.speculation", "false")
+ .config("spark.sql.shuffle.partitions", shufflePartitions.toString)
+ .config("spark.ui.enabled", "false")
+ mode match {
+ case "regular" =>
+ case "streaming" =>
+ b.config("spark.sql.shuffle.localPipelined.enabled", "true")
+ case "channel" =>
+ b.config("spark.sql.shuffle.localPipelined.enabled", "true")
+ .config("spark.shuffle.manager.incremental", channelManagerClass)
+ }
+ b.getOrCreate()
+ }
+
+ // Each transport runs under its OWN SparkSession, because the shuffle manager and the
+ // pipelined flag are SparkContext-level and fixed at startup -- they cannot be switched with
+ // setConf on a shared session. So a case cannot reuse the base trait's session; it builds its
+ // own. Two consequences handled here:
+ // - Session build/teardown must be EXCLUDED from the measured time (it is seconds of fixed
+ // cost that would swamp the workload). addTimerCase gives manual timing: the session is
+ // built before startTiming() and stopped after stopTiming(), so only the workload is timed
+ // while the framework still runs its own warm-up + best-of-N iterations.
+ // - Any lingering active session (the base trait eagerly creates a throwaway one, and a prior
+ // case leaves none but be defensive) must be stopped first, or getOrCreate would REUSE it
+ // and silently ignore this case's master/manager config.
+ private def addModeCase(
+ benchmark: Benchmark,
+ caseName: String,
+ buildSession: => SparkSession)(workload: SparkSession => Unit): Unit = {
+ benchmark.addTimerCase(caseName) { timer =>
+ // Stop whatever session is around (active or default -- the base trait's throwaway is set
+ // as the default) so the fresh build below is not short-circuited by getOrCreate reuse.
+ SparkSession.getActiveSession.orElse(SparkSession.getDefaultSession).foreach(_.stop())
+ SparkSession.clearActiveSession()
+ SparkSession.clearDefaultSession()
+ val sparkSession = buildSession
+ try {
+ timer.startTiming()
+ workload(sparkSession)
+ timer.stopTiming()
+ } finally {
+ sparkSession.stop()
+ SparkSession.clearActiveSession()
+ SparkSession.clearDefaultSession()
+ }
+ }
+ }
+
+ private def transportComparison(): Unit = {
+ runBenchmark(
+ "Transport comparison: regular vs RPC-streaming vs in-process channel") {
+ // repartition(k)+count
+ val repartitionWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).repartition($"k").count()
+ }
+
+ val b1 = new Benchmark(
+ "repartition(k)+count",
+ numRows,
+ output = output)
+ addModeCase(b1, "regular", buildTransportSession("regular", shufflePartitions))(
+ repartitionWorkload)
+ addModeCase(b1, "streaming", buildTransportSession("streaming", shufflePartitions))(
+ repartitionWorkload)
+ addModeCase(b1, "channel", buildTransportSession("channel", shufflePartitions))(
+ repartitionWorkload)
+ b1.run()
+
+ // groupBy(k).count
+ val groupByWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).groupBy($"k").count().count()
+ }
+
+ val b2 = new Benchmark(
+ "groupBy(k).count",
+ numRows,
+ output = output)
+ addModeCase(b2, "regular", buildTransportSession("regular", shufflePartitions))(
+ groupByWorkload)
+ addModeCase(b2, "streaming", buildTransportSession("streaming", shufflePartitions))(
+ groupByWorkload)
+ addModeCase(b2, "channel", buildTransportSession("channel", shufflePartitions))(
+ groupByWorkload)
+ b2.run()
+
+ // join 10M x 10M on unique k+count
+ val joinWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ val left = spark.range(0, 10000000L, 1, 2)
+ .select($"id".as("k"), $"id".as("lv"))
+ val right = spark.range(0, 10000000L, 1, 2)
+ .select($"id".as("k"), $"id".as("rv"))
+ left.join(right, "k").count()
+ }
+
+ val b3 = new Benchmark(
+ "join 10M x 10M on unique k+count",
+ 10000000L,
+ output = output)
+ addModeCase(b3, "regular", buildTransportSession("regular", shufflePartitions))(
+ joinWorkload)
+ addModeCase(b3, "streaming", buildTransportSession("streaming", shufflePartitions))(
+ joinWorkload)
+ addModeCase(b3, "channel", buildTransportSession("channel", shufflePartitions))(
+ joinWorkload)
+ b3.run()
+
+ // prototype 1M uniq
+ val prototypeWorkload: SparkSession => Unit = { spark =>
+ import org.apache.spark.sql.functions.{col, lit, repeat, sum}
+ spark.range(0L, 100000000L, 100L, inputParts)
+ .select(
+ col("id"),
+ col("id").cast("string").as("id2"),
+ (col("id") + 1).as("id3"),
+ repeat((col("id") + 1).cast("string"), 100000).as("id4"))
+ .repartition(col("id")).agg(sum(lit(1L))).collect()
+ }
+
+ val b4 = new Benchmark(
+ "prototype 1M uniq",
+ 100000000L,
+ output = output)
+ addModeCase(b4, "regular", buildTransportSession("regular", shufflePartitions))(
+ prototypeWorkload)
+ addModeCase(b4, "streaming", buildTransportSession("streaming", shufflePartitions))(
+ prototypeWorkload)
+ addModeCase(b4, "channel", buildTransportSession("channel", shufflePartitions))(
+ prototypeWorkload)
+ b4.run()
+ }
+ }
+
+ private def aqeOffComparison(): Unit = {
+ runBenchmark("Regular vs channel, AQE off") {
+ // repartition(k)+count
+ val repartitionWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).repartition($"k").count()
+ }
+
+ val b1 = new Benchmark(
+ "repartition(k)+count",
+ numRows,
+ output = output)
+ addModeCase(b1, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = false))(
+ repartitionWorkload)
+ addModeCase(b1, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = false))(
+ repartitionWorkload)
+ b1.run()
+
+ // groupBy(k).count
+ val groupByWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).groupBy($"k").count().count()
+ }
+
+ val b2 = new Benchmark(
+ "groupBy(k).count",
+ numRows,
+ output = output)
+ addModeCase(b2, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = false))(
+ groupByWorkload)
+ addModeCase(b2, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = false))(
+ groupByWorkload)
+ b2.run()
+
+ // repartitionByRange(k)+count
+ val repartitionByRangeWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).repartitionByRange($"k").count()
+ }
+
+ val b3 = new Benchmark(
+ "repartitionByRange(k)+count",
+ numRows,
+ output = output)
+ addModeCase(b3, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = false))(
+ repartitionByRangeWorkload)
+ addModeCase(b3, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = false))(
+ repartitionByRangeWorkload)
+ b3.run()
+
+ // groupBy(k).count+orderBy(k)
+ val groupByOrderByWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).groupBy($"k").count().orderBy($"k")
+ .collect()
+ }
+
+ val b4 = new Benchmark(
+ "groupBy(k).count+orderBy(k)",
+ numRows,
+ output = output)
+ addModeCase(b4, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = false))(
+ groupByOrderByWorkload)
+ addModeCase(b4, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = false))(
+ groupByOrderByWorkload)
+ b4.run()
+
+ // prototype: repartition(id)+count, 1M uniq
+ val prototypeWorkload: SparkSession => Unit = { spark =>
+ import org.apache.spark.sql.functions.{col, lit, repeat, sum}
+ spark.range(0L, 100000000L, 100L, inputParts)
+ .select(
+ col("id"),
+ col("id").cast("string").as("id2"),
+ (col("id") + 1).as("id3"),
+ repeat((col("id") + 1).cast("string"), 100000).as("id4"))
+ .repartition(col("id")).agg(sum(lit(1L))).collect()
+ }
+
+ val b5 = new Benchmark(
+ "prototype: repartition(id)+count, 1M uniq",
+ 100000000L,
+ output = output)
+ addModeCase(b5, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = false))(
+ prototypeWorkload)
+ addModeCase(b5, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = false))(
+ prototypeWorkload)
+ b5.run()
+ }
+ }
+
+ private def aqeOnComparison(): Unit = {
+ runBenchmark("Regular vs channel, AQE on") {
+ // repartition(k)+count (AQE)
+ val repartitionWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).repartition($"k").count()
+ }
+
+ val b1 = new Benchmark(
+ "repartition(k)+count (AQE)",
+ numRows,
+ output = output)
+ addModeCase(b1, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = true))(
+ repartitionWorkload)
+ addModeCase(b1, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = true))(
+ repartitionWorkload)
+ b1.run()
+
+ // groupBy(k).count (AQE)
+ val groupByWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).groupBy($"k").count().count()
+ }
+
+ val b2 = new Benchmark(
+ "groupBy(k).count (AQE)",
+ numRows,
+ output = output)
+ addModeCase(b2, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = true))(
+ groupByWorkload)
+ addModeCase(b2, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = true))(
+ groupByWorkload)
+ b2.run()
+
+ // groupBy(k).count+orderBy(k) (AQE)
+ val groupByOrderByWorkload: SparkSession => Unit = { spark =>
+ import spark.implicits._
+ spark.range(0, numRows, 1, inputParts)
+ .withColumn("k", $"id" % 1000).groupBy($"k").count().orderBy($"k")
+ .collect()
+ }
+
+ val b3 = new Benchmark(
+ "groupBy(k).count+orderBy(k) (AQE)",
+ numRows,
+ output = output)
+ addModeCase(b3, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = true))(
+ groupByOrderByWorkload)
+ addModeCase(b3, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = true))(
+ groupByOrderByWorkload)
+ b3.run()
+
+ // prototype 1M uniq (AQE)
+ val prototypeWorkload: SparkSession => Unit = { spark =>
+ import org.apache.spark.sql.functions.{col, lit, repeat, sum}
+ spark.range(0L, 100000000L, 100L, inputParts)
+ .select(
+ col("id"),
+ col("id").cast("string").as("id2"),
+ (col("id") + 1).as("id3"),
+ repeat((col("id") + 1).cast("string"), 100000).as("id4"))
+ .repartition(col("id")).agg(sum(lit(1L))).collect()
+ }
+
+ val b4 = new Benchmark(
+ "prototype 1M uniq (AQE)",
+ 100000000L,
+ output = output)
+ addModeCase(b4, "regular", buildSession(
+ pipelined = false, shufflePartitions, s"local[$cores]", aqe = true))(
+ prototypeWorkload)
+ addModeCase(b4, "pipelined", buildSession(
+ pipelined = true, shufflePartitions, s"local[$cores]", aqe = true))(
+ prototypeWorkload)
+ b4.run()
+ }
+ }
+
+ override def runBenchmarkSuite(mainArgs: Array[String]): Unit = {
+ // The minimum shape (all knobs at 1) demands 1 + 1 + 1 + 1 = 4 slots for the widest workload,
+ // so 4 cores suffice -- which is what the standard benchmark workflow provides. Below that the
+ // gang cannot fit and the run would die with an insufficient-slot error rather than produce a
+ // slower number, so skip loudly instead.
+ if (cores < 4) {
+ // scalastyle:off println
+ println(s"[skip] PipelinedShuffleBenchmark needs >= 4 cores for the gang to fit; " +
+ s"this machine has $cores. Skipping.")
+ // scalastyle:on println
+ return
+ }
+ transportComparison()
+ aqeOffComparison()
+ aqeOnComparison()
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleSqlSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleSqlSuite.scala
new file mode 100644
index 000000000000..758aa27bda34
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleSqlSuite.scala
@@ -0,0 +1,792 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import java.util.concurrent.{Callable, CountDownLatch, Executors, TimeUnit}
+
+import org.apache.spark.{PipelinedShuffleDependency, SparkEnv, SparkFunSuite}
+import org.apache.spark.rdd.RDD
+import org.apache.spark.shuffle.local.pipelined.ChannelShuffleRendezvous
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper
+import org.apache.spark.storage.{RDDBlockId, StorageLevel}
+
+/**
+ * End-to-end SQL coverage of the pipelined channel path: a batch query whose hash
+ * exchange is rewritten to a pipelined shuffle (EnablePipelinedShuffle) and served by the
+ * in-process channel manager (PipelinedChannelShuffleManager), run through the
+ * concurrent-stage scheduler on a single executor. Self-manages its SparkSession because the
+ * shuffle manager and AQE-off gate are start-up configs.
+ */
+class PipelinedShuffleSqlSuite extends SparkFunSuite
+ with AdaptiveSparkPlanHelper with PipelinedShuffleTestSession {
+
+ private def withPipelinedSession(body: SparkSession => Unit): Unit =
+ withPipelinedSession("pipelined-shuffle-sql", aqe = false)(body)
+
+ test("batch repartition($k) runs end-to-end through the pipelined channel shuffle") {
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 10)).repartition($"k")
+
+ // Single action only: a pipelined shuffle is single-shot, so collect exactly once and
+ // derive everything from that one result.
+ val rows = df.select($"id").as[Long].collect()
+ val ids = rows.toSet
+
+ // The rule fired and the exchange is pipelined.
+ val pipelinedExchanges = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ assert(pipelinedExchanges.nonEmpty,
+ s"expected a pipelined ShuffleExchangeExec; plan was:\n${df.queryExecution.executedPlan}")
+
+ // Correctness: the same 1000 ids, repartitioned, all present exactly once.
+ assert(rows.length === 1000, s"expected 1000 rows, got ${rows.length}")
+ assert(ids === (0L until 1000L).toSet)
+ }
+ }
+
+ test("a single keyed groupBy runs end-to-end through the pipelined channel shuffle") {
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 7))
+ .groupBy($"k").count()
+
+ // Single action only (pipelined shuffle is single-shot).
+ val counts = df.as[(Long, Long)].collect().toMap
+ val pipelined = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ assert(pipelined.nonEmpty,
+ s"expected pipelined exchange; plan:\n${df.queryExecution.executedPlan}")
+ // Each residue class 0..6 of 0..999.
+ val expected = (0L until 1000L).groupBy(_ % 7).map { case (k, vs) => (k, vs.size.toLong) }
+ assert(counts === expected)
+ }
+ }
+
+ test("groupBy with ORDER BY (hash + range exchanges) is all-pipelined") {
+ // A trailing ORDER BY adds a RANGE exchange (global sort with 4 shuffle partitions ->
+ // RangePartitioning) on top of the groupBy's hash exchange. The relaxed rule pipelines
+ // BOTH (a mixed pipelined/regular job would be rejected). Range is the interesting case:
+ // RangePartitioner construction runs a SAMPLE job over the exchange's child -- which here
+ // reads the pipelined hash shuffle -- before the main job runs, so this also exercises
+ // two successive jobs over the same single-shot pipelined producer.
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 7))
+ .groupBy($"k").count().orderBy($"k")
+
+ val rows = df.as[(Long, Long)].collect()
+ val exchanges = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }
+ assert(exchanges.nonEmpty && exchanges.forall(_.pipelined),
+ s"every exchange should be pipelined; plan:\n${df.queryExecution.executedPlan}")
+ // Pin the partitioning shapes so this test can't silently stop covering range.
+ val partitionings = exchanges.map(_.outputPartitioning.getClass.getSimpleName).sorted
+ assert(exchanges.exists(_.outputPartitioning.isInstanceOf[
+ org.apache.spark.sql.catalyst.plans.physical.RangePartitioning]),
+ s"expected a RangePartitioning exchange, got: $partitionings; " +
+ s"plan:\n${df.queryExecution.executedPlan}")
+ // Result is correct AND globally ordered by k.
+ val expected = (0L until 1000L).groupBy(_ % 7).map { case (k, vs) => (k, vs.size.toLong) }
+ .toSeq.sortBy(_._1)
+ assert(rows.toSeq === expected)
+ }
+ }
+
+ test("repartitionByRange (pure range exchange) runs through the pipelined channel shuffle") {
+ // A range exchange directly over the scan: RangePartitioner samples the scan (a job with
+ // no shuffle at all), then the main job runs the pipelined range shuffle. Verifies the
+ // channel transport is agnostic to the partitioner kind, and rows land range-partitioned.
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 100))
+ .repartitionByRange($"k")
+ // spark_partition_id() records which output partition each row landed in without
+ // leaving the DataFrame API (Dataset.rdd would execute a separate QueryExecution).
+ .select($"k", org.apache.spark.sql.functions.spark_partition_id().as("p"))
+
+ val partitioned = df.as[(Long, Int)].collect().map { case (k, p) => (p, k) }
+ val exchanges = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }
+ assert(exchanges.nonEmpty && exchanges.forall(_.pipelined),
+ s"expected a pipelined exchange; plan:\n${df.queryExecution.executedPlan}")
+ assert(exchanges.exists(_.outputPartitioning.isInstanceOf[
+ org.apache.spark.sql.catalyst.plans.physical.RangePartitioning]),
+ s"expected RangePartitioning; plan:\n${df.queryExecution.executedPlan}")
+
+ // No rows lost, and the partitioning is a genuine range split: key ranges of distinct
+ // partitions must not overlap.
+ assert(partitioned.length === 1000)
+ val ranges = partitioned.groupBy(_._1).map { case (p, rows) =>
+ (p, rows.map(_._2).min, rows.map(_._2).max)
+ }.toSeq.sortBy(_._2)
+ ranges.sliding(2).foreach {
+ case Seq((p1, _, max1), (p2, min2, _)) =>
+ assert(max1 <= min2, s"partitions $p1 and $p2 overlap: max($p1)=$max1 > min($p2)=$min2")
+ case _ =>
+ }
+ }
+ }
+
+ test("sort-merge join (both sides hash-exchanged) is all-pipelined and correct") {
+ // A shuffled join is the last TPC-DS transport shape not yet covered: both join inputs
+ // get a hash ShuffleExchangeExec. Disable broadcast so the join is a SortMergeJoin with
+ // two real shuffles; the relaxed rule pipelines both, and the concurrent-stage group
+ // (two producers + the join stage) runs together.
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ // Two structurally DIFFERENT inputs so exchange reuse does not collapse them into one
+ // ReusedExchange (which the rule would skip). Different ranges + key expressions.
+ val left = spark.range(0, 200, 1, 2).withColumn("k", ($"id" % 10))
+ .select($"k", $"id".as("lv"))
+ val right = spark.range(0, 120, 1, 2).withColumn("k", ($"id" % 6))
+ .select($"k", $"id".as("rv"))
+ val joined = left.join(right, "k")
+
+ val rows = joined.select($"k", $"lv", $"rv").as[(Long, Long, Long)].collect()
+ val exchanges = collect(joined.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }
+ assert(exchanges.length >= 2 && exchanges.forall(_.pipelined),
+ s"both join inputs should be pipelined; plan:\n${joined.queryExecution.executedPlan}")
+
+ // Ground truth: an equi-join on k over the two relations.
+ val l = (0L until 200L).map(i => (i % 10, i))
+ val r = (0L until 120L).map(i => (i % 6, i))
+ val expected = (for ((lk, lv) <- l; (rk, rv) <- r if lk == rk) yield (lk, lv, rv)).toSet
+ assert(rows.toSet === expected)
+ }
+ }
+
+ test("global aggregate (single-partition exchange) runs through the pipelined channel") {
+ // An ungrouped aggregate requires AllTuples, planned as a SinglePartition exchange: the
+ // channel's numPartitions == 1 degenerate case (everything routes to queue 0).
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).agg(org.apache.spark.sql.functions.sum($"id"))
+
+ val result = df.as[Long].collect()
+ val exchanges = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }
+ assert(exchanges.nonEmpty && exchanges.forall(_.pipelined),
+ s"expected a pipelined exchange; plan:\n${df.queryExecution.executedPlan}")
+ assert(exchanges.exists(_.outputPartitioning ==
+ org.apache.spark.sql.catalyst.plans.physical.SinglePartition),
+ s"expected a SinglePartition exchange; plan:\n${df.queryExecution.executedPlan}")
+ assert(result.toSeq === Seq((0L until 1000L).sum))
+ }
+ }
+
+ private def assertRegularRDD(root: RDD[_]): Unit = {
+ val visited = scala.collection.mutable.Set.empty[Int]
+ val pending = scala.collection.mutable.Stack[RDD[_]](root)
+ while (pending.nonEmpty) {
+ val rdd = pending.pop()
+ if (visited.add(rdd.id)) {
+ rdd.dependencies.foreach { dep =>
+ assert(!dep.isInstanceOf[PipelinedShuffleDependency[_, _, _]])
+ pending.push(dep.rdd)
+ }
+ }
+ }
+ }
+
+ for (aqe <- Seq(false, true)) {
+ test(s"regular fallback is reused and avoids cloning shuffle-free plans with AQE=$aqe") {
+ withPipelinedSession("pipelined-fallback-reuse", aqe) { spark =>
+ val plain = spark.range(10).queryExecution
+ assert(plain.withRegularShuffle eq plain)
+ val qe = spark.range(0, 100, 1, 2).repartition(4).queryExecution
+ val regular = qe.withRegularShuffle
+ assert(regular ne qe)
+ assert(regular.sparkSession ne qe.sparkSession)
+ assert(qe.withRegularShuffle eq regular)
+ }
+ }
+
+ test(s"RDD-backed SQL actions remain regular with AQE=$aqe") {
+ withPipelinedSession("pipelined-rdd-input", aqe) { spark =>
+ val input = spark.sparkContext.parallelize(0 until 1000, 2)
+ .map(i => (i % 4, 1L)).reduceByKey(_ + _)
+ val df = spark.createDataFrame(input).toDF("k", "v").groupBy("k").sum("v")
+ assert(df.collect().map(_.getLong(1)).sum === 1000L)
+ assert(collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.isEmpty)
+ }
+ }
+
+ test(s"recursive CTE retains regular iteration shuffles with AQE=$aqe") {
+ withPipelinedSession("pipelined-recursive-cte", aqe,
+ channelBatchSize = 8, channelQueueCapacity = 1) { spark =>
+ spark.conf.set("spark.sql.cteRecursionAnchorRowsLimitToConvertToLocalRelation", "0")
+ val df = spark.sql(
+ """WITH RECURSIVE t(n) AS (
+ | SELECT /*+ REPARTITION(4) */ id FROM range(100)
+ | UNION ALL
+ | SELECT /*+ REPARTITION(4) */ n + 100 FROM t WHERE n < 200
+ |) SELECT n FROM t""".stripMargin)
+ assertRegularRDD(df.queryExecution.toRdd)
+ assert(df.collect().map(_.getLong(0)).sorted === (0L until 300L).toArray)
+ }
+ }
+
+ test(s"ordinary file scans retain regular shuffles with AQE=$aqe") {
+ withPipelinedSession("pipelined-file-scan", aqe) { spark =>
+ withTempDir { dir =>
+ val path = new java.io.File(dir, "data")
+ spark.range(100).write.parquet(path.getCanonicalPath)
+ val df = spark.read.parquet(path.getCanonicalPath).repartition(4)
+ assert(df.collect().map(_.getLong(0)).sorted === (0L until 100L).toArray)
+ assert(collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.isEmpty)
+ }
+ }
+ }
+
+ test(s"typed and Python RDD exports retain regular shuffle lineage with AQE=$aqe") {
+ withPipelinedSession("pipelined-rdd-exports", aqe) { spark =>
+ import spark.implicits._
+ val df = spark.range(0, 4000, 1, 2).repartition(4)
+ assert(df.collect().length === 4000)
+ val typed = df.groupByKey(_ % 4).mapGroups { (key, rows) =>
+ (key, rows.size.toLong)
+ }
+ val rdd = typed.rdd
+ assertRegularRDD(rdd)
+ assert(rdd.coalesce(1).collect().map(_._2).sum === 4000L)
+ val pythonRDD = df.asInstanceOf[org.apache.spark.sql.classic.Dataset[Long]]
+ .javaToPython.rdd
+ assertRegularRDD(pythonRDD)
+ assert(pythonRDD.coalesce(1).count() > 0)
+ val fromRDD = spark.createDataFrame(rdd).repartition(4).rdd
+ assertRegularRDD(fromRDD)
+ assert(fromRDD.coalesce(1).count() === 4L)
+ }
+ }
+
+ test(s"lazy checkpoints retain regular shuffle lineage with AQE=$aqe") {
+ withPipelinedSession("pipelined-checkpoint", aqe) { spark =>
+ withTempDir { dir =>
+ spark.sparkContext.setCheckpointDir(dir.getCanonicalPath)
+ for (reliable <- Seq(false, true)) {
+ val df = spark.range(0, 4000, 1, 2).repartition(4)
+ assert(df.collect().length === 4000)
+ val checkpointed = if (reliable) {
+ df.checkpoint(eager = false)
+ } else {
+ df.localCheckpoint(eager = false)
+ }
+ val rdd = checkpointed.rdd
+ assertRegularRDD(rdd)
+ assert(rdd.coalesce(1).count() === 4000L)
+ assert(checkpointed.collect().sorted === (0L until 4000L).toArray)
+ }
+ }
+ }
+ }
+
+ test(s"SQL cursor computes its producer once with AQE=$aqe") {
+ withPipelinedSession("pipelined-cursor", aqe) { spark =>
+ spark.conf.set("spark.sql.scripting.enabled", "true")
+ spark.conf.set("spark.sql.scripting.cursorEnabled", "true")
+ spark.conf.set("spark.sql.classic.shuffleDependency.fileCleanup.enabled", "false")
+ val evaluated = spark.sparkContext.longAccumulator("cursor producer rows")
+ spark.udf.register("record_cursor_row", (id: Long) => {
+ evaluated.add(1)
+ id
+ })
+ val result = spark.sql(
+ """BEGIN
+ | DECLARE v BIGINT;
+ | DECLARE total BIGINT DEFAULT 0;
+ | DECLARE i INT DEFAULT 0;
+ | DECLARE c CURSOR FOR
+ | SELECT /*+ REPARTITION(4) */ record_cursor_row(id) FROM range(100);
+ | OPEN c;
+ | WHILE i < 100 DO
+ | FETCH c INTO v;
+ | SET total = total + v;
+ | SET i = i + 1;
+ | END WHILE;
+ | CLOSE c;
+ | VALUES (total);
+ |END""".stripMargin)
+ assert(result.collect().head.getLong(0) === (0L until 100L).sum)
+ assert(evaluated.value === 100L)
+ }
+ }
+
+ test(s"Dataset.rdd supports narrow and shuffle consumers with AQE=$aqe") {
+ withPipelinedSession("pipelined-rdd-boundary", aqe) { spark =>
+ val rdd = spark.range(0, 4000, 1, 2).repartition(4).toDF().rdd
+ // Assert eligibility before executing a shape that would hang with the channel.
+ assertRegularRDD(rdd)
+ assert(rdd.coalesce(2).count() === 4000L)
+ assert(rdd.union(rdd).count() === 8000L)
+ assert(rdd.zip(rdd).count() === 4000L)
+ val grouped = rdd.map(r => (r.getLong(0) % 2, 1L)).reduceByKey(_ + _)
+ assert(grouped.collect().toMap === Map(0L -> 2000L, 1L -> 2000L))
+ assert(rdd.repartition(2).count() === 4000L)
+ }
+ }
+
+ test(s"cache construction and partial eviction use regular shuffles with AQE=$aqe") {
+ withPipelinedSession("pipelined-cache", aqe,
+ channelBatchSize = 8, channelQueueCapacity = 1) { spark =>
+ import spark.implicits._
+ val evaluated = spark.sparkContext.longAccumulator("cached rows evaluated")
+ val record = org.apache.spark.sql.functions.udf { id: Long =>
+ evaluated.add(1)
+ id
+ }
+ val df = spark.range(0, 4000, 1, 2).repartition(4)
+ .select(record($"id").as("id")).as[Long].persist(StorageLevel.MEMORY_ONLY)
+ try {
+ val classicDf = df.asInstanceOf[org.apache.spark.sql.classic.Dataset[_]]
+ val cached = spark.sharedState.cacheManager.lookupCachedData(classicDf).get
+ .cachedRepresentation.cacheBuilder
+ assert(collect(cached.cachedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.isEmpty)
+ val expected = (0L until 4000L).toArray
+ assert(df.collect().sorted === expected)
+ assert(evaluated.value === 4000L)
+ val buffers = cached.cachedColumnBuffers
+ assert(buffers.getNumPartitions === 4)
+ SparkEnv.get.blockManager.removeBlock(RDDBlockId(buffers.id, 0))
+ assert(df.collect().sorted === expected)
+ assert(evaluated.value === 5000L, "only the evicted partition must be recomputed")
+ assert(df.collect().sorted === expected)
+ assert(evaluated.value === 5000L)
+ val consumer = df.repartition(2)
+ assert(consumer.collect().sorted === expected)
+ assert(collect(consumer.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.isEmpty)
+ } finally {
+ df.unpersist(blocking = true)
+ }
+ }
+ }
+
+ test(s"toLocalIterator uses regular output across jobs with AQE=$aqe") {
+ withPipelinedSession("pipelined-local-iterator", aqe) { spark =>
+ import scala.jdk.CollectionConverters._
+ import spark.implicits._
+ spark.conf.set("spark.sql.classic.shuffleDependency.fileCleanup.enabled", "false")
+ val expected = (0L until 1000L).toArray
+ for (collectFirst <- Seq(false, true)) {
+ val evaluated = spark.sparkContext.longAccumulator("producer rows")
+ val recordEvaluation = org.apache.spark.sql.functions.udf { id: Long =>
+ evaluated.add(1)
+ id
+ }
+ val df = spark.range(0, 1000, 1, 2).select(recordEvaluation($"id").as("id"))
+ .repartition(4).as[Long]
+ val initialRuns = if (collectFirst) {
+ assert(df.collect().sorted === expected)
+ 1
+ } else {
+ 0
+ }
+ for (run <- 1 to 3) {
+ val iterator = df.toLocalIterator()
+ assert(spark.conf.get("spark.sql.shuffle.localPipelined.enabled") === "true")
+ assert(iterator.asScala.toArray.sorted === expected)
+ // Four output-partition jobs reuse regular shuffle output: the producer runs once.
+ assert(evaluated.value === (initialRuns + 1) * 1000L)
+ }
+ assert(df.collect().sorted === expected)
+ assert(evaluated.value === (initialRuns + 2) * 1000L)
+ val exchanges = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ assert(exchanges.nonEmpty, "collect must still use the original pipelined plan")
+ exchanges.foreach { s =>
+ assert(!ChannelShuffleRendezvous.holdsShuffle(s.shuffleDependency.shuffleId))
+ }
+ }
+ }
+ }
+
+ test(s"capacity fallback preserves explicit repartition width with AQE=$aqe") {
+ withPipelinedSession("pipelined-explicit-width", aqe, cores = 8) { spark =>
+ val df = spark.range(0, 1000, 1, 2).repartition(200)
+ assert(df.collect().sorted === (0L until 1000L).toArray)
+ val exchanges = collect(df.queryExecution.executedPlan) { case s: ShuffleExchangeExec => s }
+ assert(exchanges.nonEmpty)
+ assert(exchanges.forall(!_.pipelined))
+ assert(exchanges.exists(_.outputPartitioning.numPartitions == 200))
+ }
+ }
+
+ test(s"capacity accounts for all stages of the group with AQE=$aqe") {
+ withPipelinedSession("pipelined-group-width", aqe, cores = 8) { spark =>
+ import spark.implicits._
+ spark.conf.set("spark.sql.shuffle.partitions", "6")
+ val grouped = spark.range(0, 1000, 1, 2).groupBy(($"id" % 7).as("k")).count()
+ assert(grouped.collect().map(_.getLong(1)).sum === 1000L)
+ assert(collect(grouped.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.nonEmpty, "two producer tasks plus six consumer tasks fit exactly")
+
+ val total = grouped.agg(org.apache.spark.sql.functions.max("count"))
+ assert(total.collect().head.getLong(0) === 143L)
+ val exchanges = collect(total.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }
+ assert(exchanges.size >= 2)
+ assert(exchanges.forall(!_.pipelined), "the full group needs 2 + 6 + 1 slots")
+ }
+ }
+ }
+
+ test("concurrent non-AQE actions on one pipelined Dataset fail without affecting its owner") {
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ spark.conf.set("spark.sql.classic.shuffleDependency.fileCleanup.enabled", "true")
+ PipelinedShuffleSqlSuite.started = new CountDownLatch(1)
+ PipelinedShuffleSqlSuite.release = new CountDownLatch(1)
+ val waitForRelease = org.apache.spark.sql.functions.udf(
+ PipelinedShuffleSqlSuite.waitForRelease _)
+ val df = spark.range(0, 1000, 1, 2).select(waitForRelease($"id").as("id"))
+ .repartition(4).as[Long]
+ val pool = Executors.newSingleThreadExecutor()
+ val first = pool.submit(new Callable[Array[Long]] {
+ override def call(): Array[Long] = df.collect()
+ })
+ try {
+ assert(PipelinedShuffleSqlSuite.started.await(30, TimeUnit.SECONDS))
+ val error = intercept[Exception] { df.collect() }
+ val messages = Iterator.iterate(error: Throwable)(_.getCause).takeWhile(_ != null)
+ .map(_.getMessage).mkString(" ")
+ assert(messages.contains("PIPELINED_SHUFFLE_CROSS_JOB_REUSE"))
+ PipelinedShuffleSqlSuite.release.countDown()
+ assert(first.get(30, TimeUnit.SECONDS).sorted === (0L until 1000L).toArray)
+ assert(df.collect().sorted === (0L until 1000L).toArray)
+ } finally {
+ PipelinedShuffleSqlSuite.release.countDown()
+ spark.sparkContext.cancelAllJobs()
+ pool.shutdownNow()
+ }
+ }
+ }
+
+ test("default shuffle width falls back to regular execution in local mode") {
+ withPipelinedSession("pipelined-default-width", aqe = false, cores = 8) { spark =>
+ import spark.implicits._
+ spark.conf.unset("spark.sql.shuffle.partitions")
+ assert(spark.conf.get("spark.sql.shuffle.partitions") === "200")
+ val df = spark.range(0, 1000, 1, 2).groupBy(($"id" % 7).as("k")).count()
+ assert(df.collect().map(_.getLong(1)).sum === 1000L)
+ assert(collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.isEmpty)
+ }
+ }
+
+ test("cross-subquery exchange reuse cannot create a shared pipelined exchange") {
+ // The no-reuse gate checks subquery plans too (collectWithSubqueries). Probing every
+ // SQL route to a reused PIPELINED exchange showed each is closed by a different layer,
+ // and this test pins the observed facts so a change in any layer surfaces here:
+ // 1. Same-tree reuse: the gate skips the plan (also covered by the join/q68 shapes).
+ // 2. Main-vs-subquery reuse: never fires -- each subquery runs its own preparation
+ // pass (PlanSubqueries -> prepareExecutedPlan, which includes
+ // EnablePipelinedShuffle), so its exchanges are already pipelined=true when the
+ // outer ReuseExchangeAndSubquery compares canonical forms against the outer
+ // not-yet-pipelined exchange: no match.
+ // 3. Subquery-vs-subquery duplication: collapsed into ONE subquery by
+ // MergeScalarSubqueries / subquery reuse before exchange reuse is considered.
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 7)).createOrReplaceTempView("t")
+
+ // Main plan and subquery share an identical inner groupBy (route 2).
+ val df = spark.sql("""
+ SELECT k, COUNT(*) AS c FROM t GROUP BY k
+ HAVING COUNT(*) > (SELECT AVG(c2) FROM (SELECT COUNT(*) AS c2 FROM t GROUP BY k) s)
+ """)
+ // Two DIFFERENT subqueries share an identical inner groupBy (routes 2 + 3).
+ val df2 = spark.sql("""
+ SELECT k, COUNT(*) AS c FROM t GROUP BY k
+ HAVING COUNT(*) > (SELECT AVG(c2) FROM (SELECT COUNT(*) AS c2 FROM t GROUP BY k) a)
+ AND COUNT(*) <= (SELECT MAX(c3) FROM (SELECT COUNT(*) AS c3 FROM t GROUP BY k) b)
+ """)
+
+ Seq(df, df2).foreach { d =>
+ val plan = d.queryExecution.executedPlan
+ // No reused exchange materializes anywhere (main tree or subqueries)...
+ assert(plan.collectWithSubqueries { case r: ReusedExchangeExec => r }.isEmpty,
+ s"unexpected reused exchange; plan:\n$plan")
+ // ... so the gate does not fire and the plan (and its independently-prepared
+ // subqueries) pipeline.
+ assert(collect(plan) { case s: ShuffleExchangeExec if s.pipelined => s }.nonEmpty,
+ s"main plan should be pipelined; plan:\n$plan")
+ assert(plan.collectWithSubqueries {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }.size > collect(plan) { case s: ShuffleExchangeExec => s }.size,
+ s"subquery exchanges should be pipelined by their own preparation; plan:\n$plan")
+ }
+
+ // Both execute correctly: 1000 = 7*142 + 6, so keys 0..5 have 143 rows (> avg
+ // 142.86) and key 6 has 142.
+ assert(df.collect().length === 6)
+ assert(df2.collect().length === 6)
+ }
+ }
+
+ test("a reader RDD reports the reduce partition its index reads, not the index itself") {
+ // The scheduler derives a pipelined producer's live reduce-partition set from the result
+ // partitions a partial read runs, so it must know how a reader partition index maps to a REDUCE
+ // index. Equal partition counts do not imply identity (a skew-split plus a coalesce has the
+ // same
+ // count and a different mapping), and a wrong answer here is not a hang but SILENTLY dropped
+ // records. So the mapping is asked of the reader RDD. This pins the three spec shapes.
+ withPipelinedSession { spark =>
+ import org.apache.spark.sql.execution.{CoalescedPartitionSpec, PartialReducerPartitionSpec,
+ ShuffledRowRDD}
+ import spark.implicits._
+ val df = spark.range(0, 1000, 1, 2).withColumn("k", ($"id" % 4)).repartition($"k")
+ val exchange = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec => s
+ }.head
+ val dep = exchange.shuffleDependency
+
+ // width-1 coalesced spec: names exactly one reducer, in spec order (NOT the partition index).
+ val widthOne = new ShuffledRowRDD(dep, exchange.metrics,
+ Array(CoalescedPartitionSpec(3, 4), CoalescedPartitionSpec(1, 2)))
+ assert(widthOne.reducePartitionIndex(0) === Some(3),
+ "partition 0 reads reducer 3 here, so the mapping must not return the index")
+ assert(widthOne.reducePartitionIndex(1) === Some(1))
+
+ // a coalesced RANGE covers several reducers: no single reduce id -> uncomputable.
+ val ranged = new ShuffledRowRDD(dep, exchange.metrics,
+ Array(CoalescedPartitionSpec(0, 2), CoalescedPartitionSpec(2, 4)))
+ assert(ranged.reducePartitionIndex(0).isEmpty,
+ "a multi-reducer range has no single reduce partition")
+
+ // a skew-split spec names its reducer explicitly.
+ val split = new ShuffledRowRDD(dep, exchange.metrics,
+ Array(PartialReducerPartitionSpec(2, 0, 1, 0L)))
+ assert(split.reducePartitionIndex(0) === Some(2))
+
+ // out-of-range index is uncomputable rather than an exception.
+ assert(widthOne.reducePartitionIndex(99).isEmpty)
+ }
+ }
+
+ test("a streaming query is left untouched in a feature-on session") {
+ // IncrementalExecution.preparations inherits QueryExecution's list, so this batch-only rule
+ // would otherwise run on streaming plans and flip every micro-batch exchange (state-store
+ // shuffles, the static side of a stream-static join) to pipelined -- before
+ // MarkPipelinedShuffleForRealTimeMode gets to make that decision, and against what it
+ // deliberately does for the static side (leaving it regular so the gang does not demand slots
+ // for stages that must finish first). The streaming engine owns that marking.
+ withPipelinedSession { spark =>
+ import spark.implicits._
+ import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+ implicit val ctx = spark.sqlContext
+ val input = MemoryStream[Int]
+ val agg = input.toDF().selectExpr("value % 10 AS k").groupBy($"k").count()
+ val q = agg.writeStream.format("memory").queryName("pipelined_stream_probe")
+ .outputMode("complete").start()
+ try {
+ input.addData(1 to 200: _*)
+ q.processAllAvailable()
+ val plan = q.asInstanceOf[
+ org.apache.spark.sql.execution.streaming.runtime.StreamingQueryWrapper]
+ .streamingQuery.lastExecution.executedPlan
+ val flipped = collect(plan) { case s: ShuffleExchangeExec if s.pipelined => s }
+ val all = collect(plan) { case s: ShuffleExchangeExec => s }
+ assert(all.nonEmpty,
+ s"precondition: the streaming plan should contain a state-store shuffle; plan:\n$plan")
+ assert(flipped.isEmpty,
+ s"a streaming plan must not be rewritten by the batch rule; plan:\n$plan")
+ } finally {
+ q.stop()
+ spark.sql("DROP VIEW IF EXISTS pipelined_stream_probe")
+ }
+ }
+ }
+
+ test("coalesce over a shuffle falls back to a regular (non-pipelined) shuffle") {
+ // A CoalesceExec (user .coalesce(n), a narrow no-shuffle partition reduction) reading from a
+ // shuffle makes ONE reduce task drain SEVERAL reduce partitions sequentially -- a core
+ // CoalescedRDD over the ShuffledRowRDD. The channel transport cannot serve that: the map-side
+ // writer interleaves all partitions on one thread and parks on a full bounded queue, so a
+ // reader draining partition `start` to completion before touching `start + 1` deadlocks the
+ // parked writer, with no timeout escape. `coalesce`'s API contract is a narrow dependency that
+ // merges adjacent partitions, which we cannot honor by re-hashing to `n` partitions either. So
+ // EnablePipelinedShuffle leaves the WHOLE plan regular when any shuffle is read by a coalesce
+ // (leaving only that exchange regular would put a pipelined exchange below a regular boundary,
+ // which the scheduler rejects). The query still runs correctly, just not pipelined. Guard with
+ // a deadline so a regression (a coalesce that DID go pipelined and hung) surfaces as a failure,
+ // not a hung suite.
+ val pool = Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new Runnable {
+ override def run(): Unit = withPipelinedSession { spark =>
+ import spark.implicits._
+ // Enough rows that, had this gone pipelined, the writer would fill a bounded queue and
+ // park -- so a regression is a real deadlock, not a too-small case that happens to fit.
+ val df = spark.range(0, 2000000L, 1, 4).withColumn("k", ($"id" % 10))
+ .groupBy($"k").count().coalesce(2)
+ val n = df.collect().length
+ require(n == 10, s"expected 10 groups, got $n")
+
+ // The fallback fired: NO exchange in the plan is pipelined.
+ val pipelined = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ require(pipelined.isEmpty,
+ s"coalesce over a shuffle must leave the plan regular; found a pipelined exchange in:" +
+ s"\n${df.queryExecution.executedPlan}")
+ }
+ })
+ try {
+ fut.get(90, TimeUnit.SECONDS)
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ fail("coalesce over a pipelined shuffle hung: the shuffle was pipelined despite a " +
+ "coalesce reading it, and the coalesced multi-partition read deadlocked the writer")
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+
+ /**
+ * Run `body` on a fresh pipelined session under a deadline, failing (not hanging the suite) on
+ * timeout. Used by the unsupported-consumer fallback tests, where a regression is a deadlock or
+ * a hard-fail rather than a wrong answer.
+ */
+ private def withDeadline(seconds: Int, onTimeout: String)(
+ body: SparkSession => Unit): Unit = {
+ val pool = Executors.newSingleThreadExecutor()
+ val fut = pool.submit(new Runnable {
+ override def run(): Unit = withPipelinedSession(body)
+ })
+ try {
+ fut.get(seconds.toLong, TimeUnit.SECONDS)
+ } catch {
+ case _: java.util.concurrent.TimeoutException =>
+ fut.cancel(true)
+ fail(onTimeout)
+ } finally {
+ pool.shutdownNow()
+ }
+ }
+
+ private def assertNotPipelined(df: org.apache.spark.sql.DataFrame, why: String): Unit = {
+ val pipelined = collect(df.queryExecution.executedPlan) {
+ case s: ShuffleExchangeExec if s.pipelined => s
+ }
+ require(pipelined.isEmpty, s"$why; found a pipelined exchange in:" +
+ s"\n${df.queryExecution.executedPlan}")
+ }
+
+ test("coalesce over a union of shuffles falls back to regular (binary-child guard)") {
+ // A CoalesceExec above a UnionExec (a BinaryExecNode) whose branches contain shuffles: the
+ // guard walk must descend through the union's children, not only unary ones. With the old
+ // unary-only walk both branch exchanges flip, and CoalescedRDD's task then drains SEVERAL
+ // reduce partitions of the SAME pipelined shuffle in order while the single-threaded writer
+ // parks on a later partition's full queue -- a hang with no timeout escape.
+ //
+ // Two details are load-bearing for this to reproduce the hazard at all (an earlier version of
+ // this test had neither and passed even with the buggy guard):
+ // - the branches must be STRUCTURALLY DIFFERENT shuffles (groupBy vs repartition). Two
+ // identical branches canonicalize alike, exchange reuse collapses them, and the rule's
+ // reuse gate then bails out first -- leaving the plan regular for the wrong reason.
+ // - each reduce partition needs more rows than a queue holds (queueCapacity 64 batches x
+ // batchSize 1024 ~= 65K rows), or the writer never parks and nothing deadlocks.
+ withDeadline(90,
+ "coalesce over a union of pipelined shuffles hung: the guard missed the union's shuffle " +
+ "children and the coalesced read deadlocked the writer") { spark =>
+ import spark.implicits._
+ val a = spark.range(0, 2000000L, 1, 4).withColumn("k", ($"id" % 1000))
+ .groupBy($"k").count().select($"k")
+ val b = spark.range(0, 2000000L, 1, 4).withColumn("k2", ($"id" % 1000))
+ .repartition($"k2").select($"k2".as("k"))
+ val df = a.union(b).coalesce(2)
+ val n = df.count()
+ require(n == 1000L + 2000000L, s"expected ${1000L + 2000000L} rows, got $n")
+ assertNotPipelined(df, "coalesce over a union must leave the plan regular")
+ }
+ }
+
+ test("crossJoin over a shuffle falls back to regular (N-to-1 cartesian read)") {
+ // A CartesianProductExec reads its child once PER right partition, so N reduce tasks would mint
+ // N readers on one rendezvous queue -- rows/markers split and the writer is abandoned mid-run.
+ // The guard must leave a shuffle read by a cartesian product regular.
+ withDeadline(90,
+ "crossJoin over a pipelined shuffle hung or corrupted: the shuffle was pipelined and the " +
+ "N-to-1 cartesian read split it across concurrent readers") { spark =>
+ import spark.implicits._
+ spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "-1")
+ val left = spark.range(0, 100000L, 1, 4).withColumn("k", ($"id" % 10)).repartition($"k")
+ val right = spark.range(0, 20L, 1, 2)
+ val df = left.crossJoin(right)
+ val n = df.count()
+ require(n == 100000L * 20L, s"expected ${100000L * 20L} rows, got $n")
+ assertNotPipelined(df, "a shuffle read by a cartesian product must stay regular")
+ }
+ }
+
+ test("a limit operator that builds a hidden shuffle in doExecute stays regular") {
+ // CollectLimitExec/CollectTailExec/TakeOrderedAndProjectExec build a regular (pipelined=false)
+ // shuffle inside doExecute, invisible to the plan walk. A flipped exchange below one of them
+ // would sit under an unmaterialized regular boundary and the job would hard-fail at submission.
+ // .collect() on a limit takes executeTake and dodges doExecute; a non-root position (feeding a
+ // write) forces doExecute. Marking these operators blocking keeps the exchange below regular.
+ withDeadline(90,
+ "a limit operator's hidden shuffle made the job hard-fail: the exchange below it was " +
+ "pipelined and landed under an unmaterialized regular boundary") { spark =>
+ import spark.implicits._
+ withTempDir { dir =>
+ val out = new java.io.File(dir, "limit-out").getAbsolutePath
+ val df = spark.range(0, 1000000L, 1, 4).withColumn("k", ($"id" % 100))
+ .groupBy($"k").count().orderBy($"count").limit(5)
+ // .write forces TakeOrderedAndProjectExec.doExecute (its hidden SinglePartition shuffle),
+ // rather than the executeTake path .collect() would take.
+ df.write.parquet(out)
+ val readBack = spark.read.parquet(out).count()
+ require(readBack == 5L, s"expected 5 rows written, got $readBack")
+ assertNotPipelined(df, "an exchange below a hidden-shuffle limit op must stay regular")
+ }
+ }
+ }
+}
+
+private object PipelinedShuffleSqlSuite {
+ @volatile var started = new CountDownLatch(1)
+ @volatile var release = new CountDownLatch(1)
+
+ def waitForRelease(id: Long): Long = {
+ started.countDown()
+ require(release.await(30, TimeUnit.SECONDS), "Timed out waiting for concurrent action")
+ id
+ }
+}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleTestSession.scala b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleTestSession.scala
new file mode 100644
index 000000000000..af1c23521fc3
--- /dev/null
+++ b/sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleTestSession.scala
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.execution.exchange
+
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Builds the feature-on [[SparkSession]] the pipelined-shuffle suites need (SPARK-57399).
+ *
+ * The feature is gated on session configs that must be present when the session is CREATED (the
+ * shuffle manager is instantiated once per SparkContext), so these suites cannot use
+ * `SharedSparkSession` + `withSQLConf`; each builds its own session instead. This trait is that
+ * one builder, shared so the gate configs cannot drift between suites.
+ */
+trait PipelinedShuffleTestSession {
+
+ /**
+ * Runs `body` against a fresh session with the in-process channel shuffle enabled.
+ *
+ * `aqe` picks the rule under test: the non-AQE `EnablePipelinedShuffle` preparation rule (false)
+ * or the adaptive `AQEEnablePipelinedShuffle` (true).
+ */
+ protected def withPipelinedSession(
+ appName: String,
+ aqe: Boolean,
+ cores: Int = 16,
+ channelBatchSize: Int = 1024,
+ channelQueueCapacity: Int = 64)(body: SparkSession => Unit): Unit = {
+ // sql/core suites share a JVM. If an earlier suite left an active/default SparkSession behind,
+ // getOrCreate() below would return THAT session and silently ignore every .config() here, so
+ // no exchange would be flipped and the assertions would fail pointing nowhere near the cause.
+ // Stop and clear any pre-existing session first so this harness gets a fresh one.
+ //
+ // Stopping a session this trait did not create is deliberate: these suites need the configs
+ // above to take effect at session creation, which is impossible while another session owns the
+ // JVM's SparkContext. Suites that share a session (SharedSparkSession) recreate it on demand,
+ // so the one being stopped here is replaced rather than lost.
+ SparkSession.getActiveSession.orElse(SparkSession.getDefaultSession).foreach(_.stop())
+ SparkSession.clearActiveSession()
+ SparkSession.clearDefaultSession()
+ val spark = SparkSession.builder()
+ // High task-concurrency cap so the pipelined group's whole-group slot demand (the sum of
+ // every concurrent stage's partitions) is admitted. These are correctness harnesses, not perf
+ // ones: on a smaller physical machine these logical slots oversubscribe the cores, which is
+ // fine for verifying results but meaningless for timing.
+ .master(s"local[$cores]")
+ .appName(appName)
+ .config("spark.shuffle.manager.incremental",
+ "org.apache.spark.shuffle.local.pipelined.PipelinedChannelShuffleManager")
+ .config("spark.shuffle.channel.batchSize", channelBatchSize)
+ .config("spark.shuffle.channel.queueCapacity", channelQueueCapacity)
+ .config(SQLConf.ADAPTIVE_EXECUTION_ENABLED.key, aqe.toString)
+ .config(SQLConf.LOCAL_PIPELINED_SHUFFLE_ENABLED.key, "true")
+ .config("spark.speculation", "false")
+ .config(SQLConf.SHUFFLE_PARTITIONS.key, "4")
+ .getOrCreate()
+ try {
+ body(spark)
+ } finally {
+ spark.stop()
+ SparkSession.clearActiveSession()
+ SparkSession.clearDefaultSession()
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org