dongjoon-hyun commented on code in PR #59523:
URL: https://github.com/apache/spark/pull/59523#discussion_r4518328003


##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -9499,6 +9554,165 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     assertDataStructuresEmpty()
   }
 
+  for ((cacheState, cachedPartitions) <- Seq(
+      "cold" -> Seq.empty[Int], "partial" -> Seq(0), "full" -> Seq(0, 1))) {
+    test(s"pipelined cache preflight: reject a persisted consumer before 
admission " +
+        s"(cache=$cacheState)") {
+      val producer = new MyRDD(sc, 2, Nil)
+      val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+      val consumer = new MyRDD(sc, 2, List(dependency)).cache()
+      cachedPartitions.foreach { partition =>
+        cacheLocations(consumer.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+      }
+      scheduler.asInstanceOf[MyDAGScheduler].maxConcurrentTasksForTest = 3
+
+      assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    }
+  }
+
+  test("pipelined cache preflight: reject persisted consumers with slot 
checking disabled") {
+    conf.set(config.PIPELINED_GROUP_SLOT_CHECK_ENABLED, false)
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: reject a persisted narrow descendant inside 
a consumer stage") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val reads = new MyRDD(sc, 2, List(dependency))
+    val cached = new MyRDD(sc, 2, List(new OneToOneDependency(reads))).cache()
+    val result = new MyRDD(sc, 2, List(new OneToOneDependency(cached)))
+    cacheLocations(cached.id -> 0) = Seq(makeBlockManagerId("hostA"))
+
+    assertPersistedPipelinedConsumerRejected(result, cached, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: name the persisted consumer among cached 
producer inputs") {

Review Comment:
   **24. Since item 14 made `persisted` follow the traversal order, this test 
can no longer show that the check skips the allowed caches.** The submitted RDD 
is `consumer` itself, so it is always the first entry of `persisted` 
(`DAGScheduler.scala:1524-1528`), and `find` stops there without searching 
`producer` or `input`. No other cache-preflight test puts an allowed cache 
ahead of an offender either. So a regression that checks only `persisted.head`, 
or names it, passes every test. For `result = 
MyRDD(List(OneToOne(consumer.persist()), OneToOne(sibling.cache())))`, the 
first kind would admit the persisted consumer, and the second would name 
`sibling`. My item 2 asked for this property, and [the 
reply](https://github.com/apache/spark/pull/59523#discussion_r4408196498) 
points to this test for it.
   
   Could the test submit an uncached result whose last narrow dependency is an 
allowed cache? `enqueue` prepends, so that cache is visited first:
   
   ```scala
   val sibling = new MyRDD(sc, 2, Nil).cache()
   val result = new MyRDD(sc, 2,
     List(new OneToOneDependency(consumer), new OneToOneDependency(sibling)))
   assertPersistedPipelinedConsumerRejected(result, consumer, 
Seq(dependency.shuffleId))
   ```



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleEligibility.scala:
##########
@@ -45,10 +46,16 @@ private[sql] object PipelinedShuffleEligibility extends 
Logging {
   // every query planned in the session.
   private val mismatchWarned = new AtomicBoolean(false)
 
-  /** Operators whose consumers cannot safely drain a bounded, single-reader 
channel. */
+  /**
+   * Operators that cannot safely consume a bounded, single-reader channel, 
including those
+   * that can persist a channel reader.
+   */
   def isUnsupportedConsumer(plan: SparkPlan): Boolean = plan match {
     case _: CoalesceExec | _: CartesianProductExec | _: 
DeserializeToObjectExec |
         _: CollectLimitExec | _: CollectTailExec | _: 
TakeOrderedAndProjectExec => true
+    // Caching can persist a shuffle reader before zipWithIndex submits its 
counting job.
+    // Use cache intent so eligibility does not depend on a mutable 
pandas-on-Spark setting.
+    case a: AttachDistributedSequenceExec if a.cache => true

Review Comment:
   **25. This case also decides AQE's shuffled-join pairing, and no test covers 
that path.** `isStatsSensitive` feeds `immediateShuffleInput` 
([AQEEnablePipelinedShuffle.scala 
L148-L164](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7fcb7/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffle.scala#L148-L164)),
 which looks through unary nodes for a shuffled join's input exchanges. 
`AttachDistributedSequenceExec` reports its child's partitioning 
([AttachDistributedSequenceExec.scala 
L48](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7fcb7/sql/core/src/main/scala/org/apache/spark/sql/execution/python/AttachDistributedSequenceExec.scala#L48)),
 so when that child is an exchange that already satisfies the join, no exchange 
is added above it. For example, with broadcast joins off, 
`distributedSequence(spark.range(0, 4000, 1, 2).repartition(4, 
col("id")).toDF(), cache = true).join(spark.range(0, 2000, 1, 
 2).toDF(), "id")` should plan a sort-merge join whose left input is `Sort`, 
`Project`, the cached Attach, and then the exchange.
   
   Under AQE, the only thing that keeps that left exchange regular is `case p 
if isStatsSensitive(p) => None` coming before the unary look-through in 
`immediateShuffleInput`. If those two cases were swapped, both inputs would 
flip and the counting job would hit the new scheduler rejection, yet every 
current test would still pass: the new SQL tests use single-input plans, and 
`EnablePipelinedShuffleSuite` covers only the non-AQE walk. Could 
`PipelinedShuffleSqlSuite` get a join case like this one, with AQE on and off?



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -1520,13 +1519,39 @@ private[spark] class DAGScheduler(
     checkPipelinedStageCreation(finalRDD, partitions, jobId)
   }
 
+  /** Reject persistence that could bypass a native pipelined shuffle reader. 
*/
+  private def checkPipelinedCacheSupported(finalRDD: RDD[_]): Unit = {
+    val persisted = new ListBuffer[RDD[_]]
+    traverseRDDGraph(finalRDD) { (rdd, enqueue) =>
+      if (rdd.getStorageLevel != StorageLevel.NONE || 
rdd.isLocallyCheckpointed) {
+        persisted += rdd
+      }
+      rdd.dependencies.foreach {
+        case pd: PipelinedShuffleDependency[_, _, _] => enqueue(pd.rdd)
+        case _: ShuffleDependency[_, _, _] =>
+          // Shape validation excludes pipelined readers below a regular 
boundary.
+        case dep => enqueue(dep.rdd)
+      }
+    }
+    // Cache locations cannot establish a stable cut: eviction can revive an 
upstream producer,
+    // and a partial cache hit skips a reader whose producer still needs its 
termination ACK.
+    // Check storage intent instead, including pending local checkpoints and 
narrow descendants.
+    val visited = new HashSet[RDD[_]]
+    persisted.find(rdd => rddChainReadsPipelinedShuffle(rdd, visited)).foreach 
{ rdd =>
+      throw pipelinedUnsupportedError(
+        s"cache/persist/localCheckpoint on RDD $rdd in a pipelined consumer's 
within-stage chain " +

Review Comment:
   **23. For a consumer that is also marked with `checkpoint()`, this advice 
cannot help, and the next submission fails with a different reason.** 
`RDD.checkpoint` recommends persisting the RDD first (`RDD.scala:1726-1727`), 
so `sc.setCheckpointDir(dir); c.cache(); c.checkpoint(); c.count()` is a 
natural sequence for an RDD-level pipelined consumer `c`. Since this check runs 
before admission and before `checkPipelinedJobSupported`, the first submission 
now fails here and suggests unpersisting `c`. After `c.unpersist()`, 
`c.count()` fails again, either at admission with 
`CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT` or with "a reliable RDD checkpoint in 
a pipelined-group member's within-stage chain" (L1513-L1516), because 
`unpersist()` leaves the pending `ReliableRDDCheckpointData` in place. At the 
merge base, the first submission already failed with that reliable-checkpoint 
reason.
   
   Could the reason say so when `rdd.checkpointData` holds a 
`ReliableRDDCheckpointData`, e.g. "rebuild it without checkpoint() and 
persistence", with a test for the combined case? The sentence "Ordinary cached 
consumers can be unpersisted and resubmitted." in the description could mention 
this exception too.



##########
core/src/test/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleSuite.scala:
##########
@@ -685,6 +686,64 @@ class PipelinedChannelShuffleSuite extends SparkFunSuite {
     }
   }
 
+  for (cachedPartitions <- Seq(0, 1, 2)) {
+    test(s"consumer cache is rejected before channel tasks start 
(cached=$cachedPartitions)") {
+      withPipelinedSparkContext(cores = 4) { sc =>
+        val input = sc.parallelize(0 until 1000, 2).map(i => (i, i))
+        val consumer = new PipelinedShuffledRDD[Int, Int, Int](input, new 
HashPartitioner(2))
+          .cache()
+        val blocks = consumer.partitions.indices.map(RDDBlockId(consumer.id, 
_))
+        val blockManager = sc.env.blockManager
+        // Populate blocks without running the shuffle so a partial cache 
cannot leave a
+        // producer waiting for a reader during setup.
+        blocks.take(cachedPartitions).foreach { block =>
+          assert(blockManager.putIterator(
+            block, Iterator((block.splitIndex, block.splitIndex)),
+            StorageLevel.MEMORY_ONLY, tellMaster = true))
+        }
+        
assert(blockManager.master.getLocations(blocks.toArray[BlockId]).map(_.nonEmpty).toSeq
 ===
+          blocks.indices.map(_ < cachedPartitions))
+
+        val events = new JobEvents
+        sc.addSparkListener(events)
+        val error = intercept[SparkException](consumer.collect())
+        checkError(
+          exception = error,
+          condition = "PIPELINED_SHUFFLE_UNSUPPORTED",
+          sqlState = Some("0A000"),
+          parameters = Map("reason" ->
+            (s"cache/persist/localCheckpoint on RDD $consumer in a pipelined 
consumer's " +
+              "within-stage chain (unpersist this RDD or rebuild it without 
localCheckpoint " +
+              "before submitting the job; persist only RDDs that do not read a 
pipelined " +
+              "shuffle within their stage)")))
+        sc.listenerBus.waitUntilEmpty()
+        assert(events.taskStarts.isEmpty)
+        assert(events.stageEnds.isEmpty)
+        assert(ChannelShuffleRendezvous.numQueuesForTesting === 0)
+        assert(consumer.getStorageLevel === StorageLevel.MEMORY_ONLY)
+
+        consumer.unpersist(blocking = true)
+        for (_ <- 0 until 2) {
+          assert(consumer.collect().map(_._1).sorted === (0 until 
1000).toArray)
+          assert(ChannelShuffleRendezvous.numQueuesForTesting === 0)
+        }
+      }
+    }
+  }
+
+  test("pipelined actions recompute an evicted producer-input cache") {
+    withPipelinedSparkContext(cores = 4) { sc =>
+      val input = sc.parallelize(0 until 1000, 2).map(i => (i, i)).cache()
+      assert(input.count() === 1000)
+      val shuffled = new PipelinedShuffledRDD[Int, Int, Int](input, new 
HashPartitioner(2))
+      assert(shuffled.collect().map(_._1).sorted === (0 until 1000).toArray)
+      sc.env.blockManager.master.removeRdd(input.id, blocking = true)

Review Comment:
   **27. nit: nothing here shows that the blocks were evicted or that the 
second action recomputed `input`.** A cache hit and a recompute return the same 
1000 keys, so L742 passes either way, and so does the whole test if `removeRdd` 
left the blocks in place or a later change read surviving blocks. The name I 
suggested in item 21 promises more than the body checks. Could it assert that 
`blockManager.master.getLocations(RDDBlockId(input.id, p))` is empty for both 
partitions after L740, or count evaluations with an accumulator in the `map` 
(1000, then 1000, then 2000)?



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -9499,6 +9554,165 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     assertDataStructuresEmpty()
   }
 
+  for ((cacheState, cachedPartitions) <- Seq(
+      "cold" -> Seq.empty[Int], "partial" -> Seq(0), "full" -> Seq(0, 1))) {
+    test(s"pipelined cache preflight: reject a persisted consumer before 
admission " +
+        s"(cache=$cacheState)") {
+      val producer = new MyRDD(sc, 2, Nil)
+      val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+      val consumer = new MyRDD(sc, 2, List(dependency)).cache()
+      cachedPartitions.foreach { partition =>
+        cacheLocations(consumer.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+      }
+      scheduler.asInstanceOf[MyDAGScheduler].maxConcurrentTasksForTest = 3
+
+      assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    }
+  }
+
+  test("pipelined cache preflight: reject persisted consumers with slot 
checking disabled") {
+    conf.set(config.PIPELINED_GROUP_SLOT_CHECK_ENABLED, false)
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: reject a persisted narrow descendant inside 
a consumer stage") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val reads = new MyRDD(sc, 2, List(dependency))
+    val cached = new MyRDD(sc, 2, List(new OneToOneDependency(reads))).cache()
+    val result = new MyRDD(sc, 2, List(new OneToOneDependency(cached)))
+    cacheLocations(cached.id -> 0) = Seq(makeBlockManagerId("hostA"))
+
+    assertPersistedPipelinedConsumerRejected(result, cached, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: name the persisted consumer among cached 
producer inputs") {
+    val input = new MyRDD(sc, 2, Nil).cache()
+    val producer = new MyRDD(sc, 2, List(new 
OneToOneDependency(input))).cache()
+    val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    assert(input.getStorageLevel === StorageLevel.MEMORY_ONLY)
+    assert(producer.getStorageLevel === StorageLevel.MEMORY_ONLY)
+  }
+
+  for ((consumerHash, descendantHash) <- Seq(0 -> 1, 1 -> 0)) {
+    test(s"pipelined cache preflight: name the first persisted offender in 
traversal order " +
+        s"(hashes=$consumerHash,$descendantHash)") {
+      val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), 
new HashPartitioner(2))
+      // Exercise both hash orders without depending on object identity hashes.
+      val consumer = new MyRDD(sc, 2, List(dependency)) {
+        override def equals(other: Any): Boolean = super.equals(other)
+        override def hashCode(): Int = consumerHash
+      }.cache()
+      val descendant = new MyRDD(sc, 2, List(new 
OneToOneDependency(consumer))) {
+        override def equals(other: Any): Boolean = super.equals(other)
+        override def hashCode(): Int = descendantHash
+      }.cache()
+
+      assertPersistedPipelinedConsumerRejected(descendant, descendant, 
Seq(dependency.shuffleId))
+      descendant.unpersist(blocking = true)
+      assertPersistedPipelinedConsumerRejected(descendant, consumer, 
Seq(dependency.shuffleId))
+    }
+  }
+
+  test("pipelined cache preflight: reject a persisted stage that consumes and 
produces shuffles") {
+    val first = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val middle = new MyRDD(sc, 2, List(first)).cache()
+    val second = new PipelinedShuffleDependency(middle, new HashPartitioner(2))
+    val result = new MyRDD(sc, 2, List(second))
+    for (partition <- 0 until 2) {
+      cacheLocations(middle.id -> partition) = Seq(makeBlockManagerId("hostA"))
+    }
+
+    assertPersistedPipelinedConsumerRejected(
+      result, middle, Seq(first.shuffleId, second.shuffleId))
+  }
+
+  test("pipelined cache preflight: reject a pending local checkpoint in a 
consumer") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, List(dependency)).localCheckpoint()
+    assert(!consumer.isCheckpointed)
+    assert(consumer.getStorageLevel != StorageLevel.NONE)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: unpersisting a pending local checkpoint 
still requires " +
+      "rebuilding the consumer") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, List(dependency)).localCheckpoint()
+    consumer.unpersist(blocking = true)
+    assert(consumer.getStorageLevel === StorageLevel.NONE)
+    assert(consumer.isLocallyCheckpointed)
+    assert(!consumer.isCheckpointed)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  for (cachedProducerRoot <- Seq(false, true)) {
+    test(s"pipelined cache preflight: allow cached producer input " +
+        s"(producerRoot=$cachedProducerRoot)") {
+      val input = new MyRDD(sc, 2, Nil)
+      val producer = new MyRDD(sc, 2, List(new OneToOneDependency(input)))
+      val cached = if (cachedProducerRoot) producer else input
+      cached.cache()
+      for (partition <- 0 until 2) {
+        cacheLocations(cached.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+      }
+      val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+      val result = new MyRDD(sc, 2, List(dependency))
+      scheduler.asInstanceOf[MyDAGScheduler].maxConcurrentTasksForTest = 4
+
+      submit(result, Array(0, 1))
+      assert(failure === null)
+      assert(taskSets.size === 2)
+      assert(taskSets.forall(_.isPipelined))
+      completeShuffleMapStageSuccessfully(taskSets.head.stageId, 0, 2)
+      complete(taskSets.last, Seq((Success, 42), (Success, 43)))
+      assert(results === Map(0 -> 42, 1 -> 43))
+      assertDataStructuresEmpty()
+    }
+  }
+
+  test("pipelined cache preflight: persistence changes are checked on every 
submission") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, List(dependency))
+    submit(consumer, Array(0, 1))
+    completeShuffleMapStageSuccessfully(taskSets.head.stageId, 0, 2)
+    complete(taskSets.last, Seq((Success, 42), (Success, 43)))
+    assertDataStructuresEmpty()
+
+    consumer.persist(StorageLevel.MEMORY_AND_DISK)
+    for (partition <- 0 until 2) {
+      cacheLocations(consumer.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+    }
+    clearInvocations(scheduler, mapOutputTracker)
+    checkError(
+      exception = submitAndCaptureFailure(consumer, Array(0, 1))

Review Comment:
   **26. nit: this skips the null and type guard that 
`assertPipelinedRejectedBeforeStageRegistration` applies first.** If a 
regression let this resubmission run, `submitAndCaptureFailure` would return 
`null`, and `checkError` would fail with a `NullPointerException` (or a 
`ClassCastException` for another failure type) instead of "the job must fail 
fast on the unsupported pipelined idiom" from `assertPipelinedUnsupported` 
(L10423-L10436). 59136c1a1a6 still called `assertPipelinedUnsupported` here.
   
   Similarly, the invalid-config test copies the helper's state checks at 
L7737-L7742. One of them, `assert(!sc.isStopped)`, cannot fail in this suite, 
because the tester's `onError` (L94-L98) stops only the scheduler and rethrows, 
and the rethrow already fails `submitAndCaptureFailure` there. I listed that 
check as a strength of the helper in item 6, which was wrong. Could the helper 
be split into the rejection check and the no-leftover-state check, so that both 
tests reuse them?



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -1520,13 +1519,39 @@ private[spark] class DAGScheduler(
     checkPipelinedStageCreation(finalRDD, partitions, jobId)
   }
 
+  /** Reject persistence that could bypass a native pipelined shuffle reader. 
*/
+  private def checkPipelinedCacheSupported(finalRDD: RDD[_]): Unit = {
+    val persisted = new ListBuffer[RDD[_]]

Review Comment:
   **31. nit: `persisted` only feeds one `find` after the walk.** Running the 
search when the walk visits a persisted RDD, with the same shared set, names 
the same first offender, needs no buffer, stops the walk at that offender, and 
keeps the order from item 14 by construction rather than through the collection 
type. The search still needs its own visited set, as L1539 has. Optional:
   
   ```scala
   val searched = new HashSet[RDD[_]]
   traverseRDDGraph(finalRDD) { (rdd, enqueue) =>
     if ((rdd.getStorageLevel != StorageLevel.NONE || 
rdd.isLocallyCheckpointed) &&
         rddChainReadsPipelinedShuffle(rdd, searched)) {
       throw pipelinedUnsupportedError(...) // same reason
     }
     rdd.dependencies.foreach { ... } // unchanged
   }
   ```



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -1520,13 +1519,39 @@ private[spark] class DAGScheduler(
     checkPipelinedStageCreation(finalRDD, partitions, jobId)
   }
 
+  /** Reject persistence that could bypass a native pipelined shuffle reader. 
*/
+  private def checkPipelinedCacheSupported(finalRDD: RDD[_]): Unit = {
+    val persisted = new ListBuffer[RDD[_]]
+    traverseRDDGraph(finalRDD) { (rdd, enqueue) =>

Review Comment:
   **30. nit: with the slot check on, which is the default, admission walks the 
same pipelined shuffles again right after this walk.** 
`pipelinedJobConcurrentTaskDemand` (L2357-L2374) only adds up the producer 
widths of the distinct pipelined shuffles, and it also descends the 
materialized prefix. Since the shape check has already rejected any pipelined 
shuffle below a regular boundary, this walk sees exactly the same pipelined 
shuffles. It could collect the producers by shuffle ID and hand them to 
admission. That removes one walk per pipelined submission and brings the pinned 
counts back: `DAGSchedulerSuite.scala:7541` from 3 to 2, 
`DAGSchedulerSuite.scala:9840` from 5 and 6 to 4 and 5, and 
`DAGSchedulerSuite.scala:7011` from 3 to 2. Unlike the larger option in item 
10, this keeps the check before admission and with the slot check off. The 
absolute cost is small, so feel free to leave it.



##########
core/src/test/scala/org/apache/spark/shuffle/local/pipelined/PipelinedChannelShuffleSuite.scala:
##########
@@ -685,6 +686,64 @@ class PipelinedChannelShuffleSuite extends SparkFunSuite {
     }
   }
 
+  for (cachedPartitions <- Seq(0, 1, 2)) {

Review Comment:
   **34. nit: `cached=1` and the second collect after `unpersist` add little 
here.** The rejection is decided from storage intent before any block lookup, 
so the three variants take the same scheduler path. `cached=0` would catch an 
exemption for cold caches and `cached=2` one for full caches, since the fake 
rows would come back, but `cached=1` catches nothing the other two miss, and 
`DAGSchedulerSuite` already covers cold, partial and full. The two collects 
after `unpersist` repeat L678-L687, which runs five. Could this drop `cached=1` 
and run one collect, saving a `local[4]` SparkContext and four pipelined jobs 
per run?



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -9499,6 +9554,165 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     assertDataStructuresEmpty()
   }
 
+  for ((cacheState, cachedPartitions) <- Seq(
+      "cold" -> Seq.empty[Int], "partial" -> Seq(0), "full" -> Seq(0, 1))) {
+    test(s"pipelined cache preflight: reject a persisted consumer before 
admission " +
+        s"(cache=$cacheState)") {
+      val producer = new MyRDD(sc, 2, Nil)
+      val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+      val consumer = new MyRDD(sc, 2, List(dependency)).cache()
+      cachedPartitions.foreach { partition =>
+        cacheLocations(consumer.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+      }
+      scheduler.asInstanceOf[MyDAGScheduler].maxConcurrentTasksForTest = 3
+
+      assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    }
+  }
+
+  test("pipelined cache preflight: reject persisted consumers with slot 
checking disabled") {
+    conf.set(config.PIPELINED_GROUP_SLOT_CHECK_ENABLED, false)
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: reject a persisted narrow descendant inside 
a consumer stage") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val reads = new MyRDD(sc, 2, List(dependency))
+    val cached = new MyRDD(sc, 2, List(new OneToOneDependency(reads))).cache()
+    val result = new MyRDD(sc, 2, List(new OneToOneDependency(cached)))
+    cacheLocations(cached.id -> 0) = Seq(makeBlockManagerId("hostA"))
+
+    assertPersistedPipelinedConsumerRejected(result, cached, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: name the persisted consumer among cached 
producer inputs") {
+    val input = new MyRDD(sc, 2, Nil).cache()
+    val producer = new MyRDD(sc, 2, List(new 
OneToOneDependency(input))).cache()
+    val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    assert(input.getStorageLevel === StorageLevel.MEMORY_ONLY)
+    assert(producer.getStorageLevel === StorageLevel.MEMORY_ONLY)
+  }
+
+  for ((consumerHash, descendantHash) <- Seq(0 -> 1, 1 -> 0)) {

Review Comment:
   **33. nit: the second hash order adds no coverage.** With the `ListBuffer`, 
the hashes cannot change the outcome. With the earlier `HashSet`, only `0 -> 1` 
fails: Scala 2.13's `mutable.HashSet` iterates from bucket 0, so hash 0 comes 
first, and with `1 -> 0` the old collector also named the descendant first. 
Could this keep only `0 -> 1`, with a comment that the consumer gets the lower 
hash, and drop the hashes from the test name? That saves one 
SparkContext-backed test in each of the two suites.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleSqlSuite.scala:
##########
@@ -213,7 +216,86 @@ class PipelinedShuffleSqlSuite extends SparkFunSuite
     }
   }
 
+  private def distributedSequence(input: DataFrame, cache: Boolean): DataFrame 
=
+    input.select(Column.internalFn("distributed_sequence_id", 
lit(cache)).as("index"), col("*"))
+
+  private def assertDistributedSequenceResult(df: DataFrame): Unit = {
+    val rows = df.collect()
+    assert(rows.map(_.getLong(0)).sorted === (0L until 4000L).toArray)
+    assert(rows.map(_.getLong(1)).sorted === (0L until 4000L).toArray)
+  }
+
   for (aqe <- Seq(false, true)) {
+    test(s"distributed sequence cache construction retains regular shuffles 
with AQE=$aqe") {
+      withPipelinedSession("pipelined-distributed-sequence-cache", aqe,
+          channelBatchSize = 8, channelQueueCapacity = 1) { spark =>
+        val cacheKey = "pandas_on_Spark.compute.default_index_cache"
+        for {
+          storage <- Seq(None, Some("MEMORY_ONLY"), Some("LOCAL_CHECKPOINT"), 
Some("NONE"))

Review Comment:
   **35. nit: the storage dimension multiplies executions without reaching new 
code.** Eligibility reads only `cache`, the pandas-on-Spark setting is read 
only at execution in `cacheRDD`, and once every exchange is regular the jobs 
have no pipelined dependency, so the new scheduler check never runs. The absent 
default and `MEMORY_ONLY` even take the same `persist` branch. So 16 executions 
of the indexing job, each with its own counting job, cover what 4 do. Could the 
plan assertions up to L257 stay for all four settings, with 
`assertDistributedSequenceResult(df)` and the check after it only for the 
default?



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/EnablePipelinedShuffle.scala:
##########
@@ -127,24 +132,19 @@ object EnablePipelinedShuffle extends Rule[SparkPlan] {
    * 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.
+   * `CollectTailExec` / `TakeOrderedAndProjectExec`, plus cached 
`AttachDistributedSequenceExec`.
+   * A shuffle above an unsupported operator with shuffle-free input does not 
disqualify the plan.

Review Comment:
   **22. This does not hold for `TakeOrderedAndProjectExec`: a shuffle above a 
non-root top-N makes the query fail instead of falling back to regular.** Both 
rules look for exchanges only below an unsupported consumer. But 
`TakeOrderedAndProjectExec.doExecute` builds its own regular `SinglePartition` 
shuffle whenever its child has more than one partition ([limit.scala 
L354-L373](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7fcb7/sql/core/src/main/scala/org/apache/spark/sql/execution/limit.scala#L354-L373)),
 since `prepareShuffleDependency` defaults to `pipelined = false` 
([ShuffleExchangeExec.scala 
L359-L365](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7fcb7/sql/core/src/main/scala/org/apache/spark/sql/execution/exchange/ShuffleExchangeExec.scala#L359-L365)).
 `SpecialLimits` also plans a non-root `Limit(Sort)` as this operator 
([SparkStrategies.scala 
L131](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7f
 
cb7/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala#L131)).
 For example, with the settings of `PipelinedShuffleSqlSuite`, `spark.range(0, 
4000, 1, 2).orderBy("id").limit(10).repartition(2).collect()` plans a 
round-robin exchange over `TakeOrderedAndProject` over a 2-partition `Range`:
   
   - Without AQE, `readsShuffleThroughUnsupportedConsumer` finds no exchange 
below the top-N, `fitsLocalCapacity` sees widths 2 and 1, and the exchange is 
flipped.
   - With AQE, `collectCandidates` flips the same exchange, and 
`hasRegularPrefix` ([AQEEnablePipelinedShuffle.scala 
L72-L79](https://github.com/apache/spark/blob/ec018f385fd4aab72933658c976a1bd2c8f7fcb7/sql/core/src/main/scala/org/apache/spark/sql/execution/adaptive/AQEEnablePipelinedShuffle.scala#L72-L79))
 cannot see the hidden shuffle.
   - At submission, the job holds the pipelined shuffle plus the top-N's 
unmaterialized regular one, so `isUnsupportedMix` 
(`DAGScheduler.scala:1214-1215`) is true and the query fails with "A job that 
mixes a pipelined shuffle dependency with a regular shuffle dependency ..." 
(`DAGScheduler.scala:2690-2693`).
   
   I traced this statically and didn't run it. Only the top-N is affected, 
since `CollectLimitExec` and `CollectTailExec` are planned only at the root. 
The gap is older than this PR, because the old `plan.exists` version also 
looked only below the operator. But this sentence and the new test at 
`EnablePipelinedShuffleSuite.scala:87-91` now state that a shuffle above a 
shuffle-free limit operator is fine, and the class doc at L69-L75 only covers 
an exchange below one. Could the limit operators keep the whole plan regular 
whenever it has any shuffle, for example in `hasUnsupportedBoundary` 
(`PipelinedShuffleEligibility.scala:112-117`), which both rules call first? 
This sentence, the class doc and the test would then change with it, and an 
end-to-end test like the query above would pin it. If you'd rather keep this PR 
focused, a separate JIRA works too, but then could this sentence and the 
limit-operator part of the new test be left out for now?



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -2669,27 +2694,18 @@ private[spark] class DAGScheduler(
       return
     }
 
-    // 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)) {
-      // Clear the slot-check retry count an earlier deferral may have left.
-      barrierJobIdToNumTasksCheckFailures.remove(jobId)
-      return
-    }
     var finalStage: ResultStage = null
     try {
-      // Reject unsupported pipelined idioms and cross-job reuse from the RDD 
graph, before
-      // any stage is created, so a rejection leaves no partial scheduler 
state. Gated on
-      // hasPipelined: every idiom this checks concerns a pipelined group, so 
it must not run for a
-      // job with no pipelined dependency (the resource-profile check in 
particular is not keyed on
-      // a pipelined dependency and would otherwise reject an ordinary job 
that merely uses a
-      // non-default profile via RDD.withResources). Inside this try so any 
incidental exception
-      // from the graph walk is handled by the same listener.jobFailed path as 
stage creation.
       if (hasPipelined) {
+        // Validate cache semantics before counting tasks: a cached consumer 
could suppress
+        // producers included in the demand, or skip readers needed by a 
running producer.
+        checkPipelinedCacheSupported(finalRDD)
+        if (rejectUnadmittablePipelinedGroup(jobId, finalRDD, partitions, 
listener)) {

Review Comment:
   **28. nit: the code no longer says why admission has to stay inside the 
`try`.** The base comment ended with "Inside this try so any incidental 
exception from the graph walk is handled by the same listener.jobFailed path as 
stage creation.", and e360a917c26 dropped it while merging the blocks. 
Admission now depends on exactly that: an invalid 
`spark.scheduler.pipelinedGroup.slotCheck.enabled` fails only this job instead 
of reaching `onError` and stopping the SparkContext, and only the new test at 
`DAGSchedulerSuite.scala:7722` guards it. Such a failure is also logged by the 
generic arm as "Creating new stage failed due to exception" (L2762-L2763), 
although no stage was created, while the comment at L2752-L2754 calls that 
message misleading for up-front rejections. Could a one-line comment above this 
block say why it is inside the `try`? Rewording the log is optional, since 
failures like cross-job reuse already end up there at the base.



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -9499,6 +9554,165 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     assertDataStructuresEmpty()
   }
 
+  for ((cacheState, cachedPartitions) <- Seq(
+      "cold" -> Seq.empty[Int], "partial" -> Seq(0), "full" -> Seq(0, 1))) {
+    test(s"pipelined cache preflight: reject a persisted consumer before 
admission " +
+        s"(cache=$cacheState)") {
+      val producer = new MyRDD(sc, 2, Nil)
+      val dependency = new PipelinedShuffleDependency(producer, new 
HashPartitioner(2))
+      val consumer = new MyRDD(sc, 2, List(dependency)).cache()
+      cachedPartitions.foreach { partition =>
+        cacheLocations(consumer.id -> partition) = 
Seq(makeBlockManagerId("hostA"))
+      }
+      scheduler.asInstanceOf[MyDAGScheduler].maxConcurrentTasksForTest = 3
+
+      assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+    }
+  }
+
+  test("pipelined cache preflight: reject persisted consumers with slot 
checking disabled") {
+    conf.set(config.PIPELINED_GROUP_SLOT_CHECK_ENABLED, false)
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val consumer = new MyRDD(sc, 2, 
List(dependency)).persist(StorageLevel.MEMORY_AND_DISK)
+
+    assertPersistedPipelinedConsumerRejected(consumer, consumer, 
Seq(dependency.shuffleId))
+  }
+
+  test("pipelined cache preflight: reject a persisted narrow descendant inside 
a consumer stage") {
+    val dependency = new PipelinedShuffleDependency(new MyRDD(sc, 2, Nil), new 
HashPartitioner(2))
+    val reads = new MyRDD(sc, 2, List(dependency))
+    val cached = new MyRDD(sc, 2, List(new OneToOneDependency(reads))).cache()
+    val result = new MyRDD(sc, 2, List(new OneToOneDependency(cached)))
+    cacheLocations(cached.id -> 0) = Seq(makeBlockManagerId("hostA"))

Review Comment:
   **32. nit: like the line removed for item 20, these cache locations are 
never read.** The same holds at L9627-L9629 and L9690-L9692. `cacheLocations` 
is read only through `getCacheLocs`, whose callers (`getMissingParentStages` 
and the preferred-location lookup) run after `createResultStage`, and every 
submission in these tests is rejected before that. The last, successful 
submission in "persistence changes are checked on every submission" runs after 
`unpersist`, where `getCacheLocs` returns without asking the block manager 
(`DAGScheduler.scala:645-646`). The cold/partial/full loop already covers cache 
state. Could these lines go too?



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/exchange/PipelinedShuffleSqlSuite.scala:
##########
@@ -213,7 +216,86 @@ class PipelinedShuffleSqlSuite extends SparkFunSuite
     }
   }
 
+  private def distributedSequence(input: DataFrame, cache: Boolean): DataFrame 
=
+    input.select(Column.internalFn("distributed_sequence_id", 
lit(cache)).as("index"), col("*"))
+
+  private def assertDistributedSequenceResult(df: DataFrame): Unit = {
+    val rows = df.collect()
+    assert(rows.map(_.getLong(0)).sorted === (0L until 4000L).toArray)
+    assert(rows.map(_.getLong(1)).sorted === (0L until 4000L).toArray)
+  }
+
   for (aqe <- Seq(false, true)) {
+    test(s"distributed sequence cache construction retains regular shuffles 
with AQE=$aqe") {
+      withPipelinedSession("pipelined-distributed-sequence-cache", aqe,
+          channelBatchSize = 8, channelQueueCapacity = 1) { spark =>
+        val cacheKey = "pandas_on_Spark.compute.default_index_cache"
+        for {
+          storage <- Seq(None, Some("MEMORY_ONLY"), Some("LOCAL_CHECKPOINT"), 
Some("NONE"))
+          upperShuffle <- Seq(false, true)
+        } {
+          // An absent setting exercises pandas-on-Spark's default 
MEMORY_AND_DISK_SER.
+          storage match {
+            case Some(level) => spark.conf.set(cacheKey, "\"" + level + "\"")
+            case None => spark.conf.unset(cacheKey)
+          }
+          val indexed = distributedSequence(
+            spark.range(0, 4000, 1, 2).repartition(4).toDF(), cache = true)
+          // SinglePartition lets AQE inspect the cached operator below the 
upper exchange.
+          val df = if (upperShuffle) indexed.repartition(1) else indexed
+          val plan = df.queryExecution.executedPlan
+          val attach = collect(plan) { case a: AttachDistributedSequenceExec 
=> a }
+          assert(attach.size === 1)
+          assert(attach.head.cache)
+          assert(attach.head.child.outputPartitioning.numPartitions === 4)
+          val exchanges = collect(plan) { case s: ShuffleExchangeExec => s }
+          assert(exchanges.size === (if (upperShuffle) 2 else 1))
+          if (upperShuffle) {
+            assert(exchanges.exists(_.outputPartitioning == SinglePartition))
+          }
+          // Check before execute() constructs the persisted RDD and 
zipWithIndex counting job.
+          assert(exchanges.forall(!_.pipelined), s"cache=$storage; 
plan:\n$plan")
+          assertDistributedSequenceResult(df)
+          assert(collect(df.queryExecution.executedPlan) {

Review Comment:
   **36. nit: this re-implements `assertNotPipelined` (L785-L791) without its 
message.** Inside the 8-iteration loop, a failure here wouldn't say which 
setting failed, while L257 does. `assertNotPipelined(df, s"cache=$storage, 
upperShuffle=$upperShuffle")` would.



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -5572,12 +5588,14 @@ private[spark] object DAGScheduler {
 private[spark] case class CancelledJobInfo(jobId: Int, properties: Properties)
 
 /**
- * Thrown when a job uses a pipelined-shuffle idiom that is not supported 
(fan-out, a barrier /
- * indeterminate / checksum-retry / push-merge producer, a reliable checkpoint 
in a member's chain,
- * or a non-default resource profile on a member). `handleJobSubmitted` 
matches on this
+ * Thrown for unsupported pipelined-shuffle idioms: fan-out, repeated 
consumption, a map-stage
+ * job with pipelined ancestry, a barrier / indeterminate / checksum-retry / 
push-merge producer,
+ * a reliable checkpoint in a member's chain, cache/persist/localCheckpoint in 
a consumer's
+ * within-stage chain, or a non-default resource profile on a member.
+ * `handleJobSubmitted` matches on this

Review Comment:
   **29. nit: this line is left over from rewrapping, and the map-stage case is 
reported, not thrown.** The sentence breaks after "matches on this". Also, 
`handleMapStageSubmitted` builds this exception for a map-stage job with 
pipelined ancestry and passes it straight to `listener.jobFailed` 
(L2850-L2853), so it never reaches the typed catch arm that the next sentence 
describes. Could the paragraph be rewrapped and say something like "Thrown (or, 
for a map-stage job, reported) for ..."?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to