cloud-fan commented on code in PR #58437:
URL: https://github.com/apache/spark/pull/58437#discussion_r4505326103


##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -4832,23 +4798,26 @@ private[spark] class DAGScheduler(
    * Responds to an executor being lost. This is called inside the event loop, 
so it assumes it can
    * modify the scheduler's internal state. Use executorLost() to post a loss 
event from outside.
    *
-   * We will also assume that we've lost all shuffle blocks associated with 
the executor if the
-   * executor serves its own blocks (i.e., we're not using an external shuffle 
service), or the
-   * entire Standalone worker is lost.
+   * We will also assume that we've lost the non-reliably-stored shuffle 
blocks associated with the
+   * executor if the executor serves its own blocks (i.e., we're not using an 
external shuffle
+   * service), or the entire Standalone worker is lost. Output marked reliably 
stored lives
+   * off-executor and is left registered.
    */
   private[scheduler] def handleExecutorLost(
       execId: String,
       workerHost: Option[String]): Unit = {
-    // if the cluster manager explicitly tells us that the entire worker was 
lost, then
-    // we know to unregister shuffle output.  (Note that "worker" specifically 
refers to the process
-    // from a Standalone cluster, where the shuffle service lives in the 
Worker.)
-    val fileLost = !sc.shuffleDriverComponents.supportsReliableStorage() &&
-      (workerHost.isDefined || !env.blockManager.externalShuffleServiceEnabled)
+    // Whether these outputs are candidates for removal at all; reliability is 
then honored per
+    // shuffle via respectReliablyStored below. workerHost.isDefined means the 
whole Standalone
+    // worker (which hosts the shuffle service) is gone.
+    val fileLost = workerHost.isDefined || 
!env.blockManager.externalShuffleServiceEnabled

Review Comment:
   **Non-blocking (P2):** For an application whose 
`ShuffleDriverComponents.supportsReliableStorage()` returns `true` and whose 
handles leave `reliablyStored` as `None`, every shuffle registers as reliably 
stored, so this pass can never remove map output. On the base branch `fileLost` 
was `false` for these applications, so an executor loss touched neither the 
tracker nor the epoch. Now an executor loss without an external shuffle service 
(the usual dynamic-allocation removal) and any loss that names a worker host 
run the selective pass: it scans every registered map status under that 
status's write lock and stamps `shuffleFileLostEpoch` for the executor. When 
the lost executor or host held no map or merge output, `CleanupOutcome(false, 
false)` makes `shouldBumpEpoch` true, and the epoch bump makes every executor 
drop its cached map statuses and refetch them from the driver on its next task. 
Results stay correct, but these deployments now pay a scan and a cluster-wide 
refetch on each 
 idle-executor removal, and no test runs a globally reliable plugin with a 
`None` handle through such a loss. The epoch-fencing reason for bumping on an 
empty pass applies to applications that already ran this cleanup on the base 
branch, not to these.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/58437#issuecomment-6711788369), 
[2](https://github.com/apache/spark/pull/58437#discussion_r3904591194), 
[3](https://github.com/apache/spark/pull/58437#discussion_r3968978557).
   
   **Recommended change:** In handleExecutorLost, restore the base behavior 
when the plugin reports reliable storage and no registered shuffle resolves 
unreliable (MapOutputTrackerMaster.hasUnreliablyStoredShuffle is false): for an 
executor-level loss (no worker host), and, when push-based shuffle is off, for 
a loss that names a worker host. Treat those outputs as not lost, so the 
tracker is not scanned, the executor fence is not stamped, and the epoch does 
not move. Every other loss keeps this PR's selective cleanup: the plugin 
reports no reliable storage, some registered shuffle resolves unreliable, or a 
worker host is lost while push-based shuffle is on. Add scheduler tests that 
use the globally reliable test plugin with None handles.
   
   **Why this works:** Under a globally reliable plugin with no unreliable 
registered shuffle, every map status on the lost executor or host takes the 
preserve branch. Merge results never carry an executor id, and with push-based 
shuffle off the tracker holds no merge results at all. The skipped pass 
therefore could never have changed tracker metadata, so skipping it leaves the 
same statuses while removing the scan, the epoch bump and the fence stamp the 
base branch never made. A later FetchFailed against that executor then passes 
the executor fence as on the base branch, and its cleanup still clears the 
failed shuffle through failedShuffleId.
   
   **Scope:** One condition in the scheduler's executor-loss handler, plus 
tests for globally reliable plugins with None handles.
   
   **Compatibility:** Worker removal, a loss that names a worker host while 
push-based shuffle is on, FetchFailed cleanup, TaskSetManager reruns, and every 
application whose plugin reports no reliable storage keep this PR's behavior.
   
   **Risks:** Applications in this configuration no longer get this PR's 
executor-fence stamp on executor loss, so FetchFailed admission for that 
executor behaves as on the base branch. Until the tracker change named in the 
exclusions lands, a whole-host loss with push-based shuffle on in such an 
application still makes every executor refetch map statuses when the host held 
nothing.
   
   **Constraints:** With push-based shuffle on, a loss that names a worker host 
must keep running host cleanup, so push-merge results on a lost host are still 
dropped. Applications whose plugin reports no reliable storage, and 
applications with any registered shuffle that resolves unreliable, keep the 
selective cleanup and the epoch rule unchanged. The tracker-level rule that a 
pass which changed and kept nothing still bumps the epoch stays as it is, 
because tracker callers that register shuffles directly rely on it.
   
   **Exclusions:**
   - Executor retirement (dynamic-allocation scale-down and holdExecutors()) 
keeps reading the application-wide flag, as this PR scopes it; the stacked 
follow-ups make it per-shuffle.
   - With push-based shuffle on, a whole-host loss in such an application still 
runs the host pass so stale push-merge results are dropped; when that host held 
no map or merge output, the pass also advances the epoch, which the base branch 
did not. Avoiding that bump needs the tracker to report an empty pass before it 
bumps, a separate change; leave a TODO at that condition naming it.
   
   **Success:** With a plugin that reports reliable storage, None handles and 
no external shuffle service, an executor-level loss of an executor that held no 
map output leaves the map-output epoch unchanged and runs no tracker cleanup. 
With push-based shuffle off, a loss that names a worker host in the same 
configuration also runs no tracker cleanup and leaves the epoch unchanged. The 
same losses leave no shuffle-file-lost fence for that executor, and a later 
map-output FetchFailed against it clears the failed shuffle's output there. 
Executor loss under a plugin that reports no reliable storage, or with a 
registered shuffle that resolves unreliable, behaves as it does in this PR.
   
   **Verification:**
   - **Regression:** Run a job under a globally reliable test plugin with None 
handles and the external shuffle service off, lose an executor that held no map 
output, and assert that the map-output epoch is unchanged and no tracker 
cleanup was requested.
   - **Regression:** In the same setup with push-based shuffle off, lose an 
executor whose loss names its worker host, and assert that the epoch is 
unchanged and no host cleanup was requested.
   - **Behavior:** In the same setup, lose an executor that holds map output, 
then deliver a map-output FetchFailed against it, and assert that the failed 
shuffle's output on that executor is cleared while another shuffle's output 
survives.
   - **Compatibility:** With push-based shuffle on and only None handles under 
a globally reliable plugin, assert that a loss that names a worker host still 
drops that host's push-merge results and keeps the reliable map output.
   - **Compatibility:** Under a globally reliable plugin with one handle 
returning Some(false), assert that executor loss still removes that shuffle's 
output on the executor.



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -4940,27 +4930,55 @@ private[spark] class DAGScheduler(
       clearCacheLocs()
     }
     if (fileLost) {
-      // When the fetch failure is for a merged shuffle chunk, 
ignoreShuffleFileLostEpoch is true
-      // and so all the files will be removed.
-      val remove = if (ignoreShuffleFileLostEpoch) {
-        true
-      } else if (!shuffleFileLostEpoch.contains(execId) ||
-        shuffleFileLostEpoch(execId) < currentEpoch) {
-        shuffleFileLostEpoch(execId) = currentEpoch
-        true
-      } else {
-        false
+      // ignoreShuffleFileLostEpoch (set from host-decommission state) 
bypasses the fence, but
+      // reliability filtering still applies. A FetchFailed for a 
reliably-stored shuffle is exempt
+      // once per epoch even when the executor fence rejects it: the executor 
loss preserved that
+      // shuffle, so its cleanup must still run when it is proven gone.
+      val passesExecutorFence = ignoreShuffleFileLostEpoch ||
+        !shuffleFileLostEpoch.contains(execId) ||
+        shuffleFileLostEpoch(execId) < currentEpoch
+      val reliableFetchFailedBypass = !passesExecutorFence && 
failedShuffleId.exists { id =>
+        mapOutputTracker.isReliablyStored(id) &&
+          reliableShuffleFileLostEpoch.get((execId, id)).forall(_ < 
currentEpoch)
       }
-      if (remove) {
+      if (passesExecutorFence || reliableFetchFailedBypass) {
+        // A bypass-only admission touches just the failed shuffle: only it is 
proven gone, so
+        // co-located shuffles (their freshly recomputed maps) must not be 
swept.
         hostToUnregisterOutputs match {
           case Some(host) =>
             logInfo(log"Shuffle files lost for host: ${MDC(HOST, host)} (epoch 
" +
               log"${MDC(EPOCH, currentEpoch)}")
-            mapOutputTracker.removeOutputsOnHost(host)
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored, failed,
+                  restrictToFailedShuffle = reliableFetchFailedBypass)
+            }
           case None =>
-              logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
-                log"(epoch ${MDC(EPOCH, currentEpoch)})")
-            mapOutputTracker.removeOutputsOnExecutor(execId)
+            logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
+              log"(epoch ${MDC(EPOCH, currentEpoch)})")
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored, failed,
+                  restrictToFailedShuffle = reliableFetchFailedBypass)
+            }
+        }
+        // A genuine executor-wide cleanup advances the executor fence 
(monotonically) to dedup
+        // same-epoch duplicates. A bypass-only admission must not move it (it 
did not clean the
+        // executor); it only records the per-shuffle fence so that shuffle's 
own duplicates are
+        // deduped. Both stamps are monotonic. Match prior behavior: skip 
under ignore. Skip the
+        // per-shuffle stamp once the map stage is gone (e.g. this FetchFailed 
aborted the job):
+        // stage cleanup already retired its fences and nothing would retire a 
new one.
+        if (!ignoreShuffleFileLostEpoch) {
+          if (passesExecutorFence) {
+            shuffleFileLostEpoch(execId) = currentEpoch
+          }
+          failedShuffleId.filter(shuffleIdToMapStage.contains).foreach { id =>
+            val key = (execId, id)
+            val prev = reliableShuffleFileLostEpoch.getOrElse(key, 
Long.MinValue)
+            reliableShuffleFileLostEpoch(key) = math.max(prev, currentEpoch)

Review Comment:
   **Nit (P3):** On a bypass-only admission `shuffleFileLostEpoch(execId)` is 
already at or above `currentEpoch`, yet this records `currentEpoch`, the 
straggler's own task epoch. For example, reliable shuffles S1 and S2 both have 
output on executor A. A FetchFailed for S2 at epoch 10 does a genuine cleanup 
and sets the executor fence to 10. A FetchFailed for S1 at epoch 7 is rejected 
by that fence, takes the bypass, clears S1 on A, and records (A, S1) = 7. A 
FetchFailed for S1 at epoch 9 from another stage that read S1 is rejected by 
the executor fence but passes the bypass because 7 < 9, so it clears S1 on A 
again, dropping any output recomputed there, and bumps the epoch. Both S1 
failures came from tasks launched before S1's cleanup, so the second is a 
duplicate. Recording `math.max(prev, shuffleFileLostEpoch(execId))` would fence 
it, and equals `currentEpoch` after a genuine cleanup.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58437#discussion_r4085168428).
   
   See **Shared repair plan 1** in the review body.



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -4940,27 +4930,55 @@ private[spark] class DAGScheduler(
       clearCacheLocs()
     }
     if (fileLost) {
-      // When the fetch failure is for a merged shuffle chunk, 
ignoreShuffleFileLostEpoch is true
-      // and so all the files will be removed.
-      val remove = if (ignoreShuffleFileLostEpoch) {
-        true
-      } else if (!shuffleFileLostEpoch.contains(execId) ||
-        shuffleFileLostEpoch(execId) < currentEpoch) {
-        shuffleFileLostEpoch(execId) = currentEpoch
-        true
-      } else {
-        false
+      // ignoreShuffleFileLostEpoch (set from host-decommission state) 
bypasses the fence, but
+      // reliability filtering still applies. A FetchFailed for a 
reliably-stored shuffle is exempt
+      // once per epoch even when the executor fence rejects it: the executor 
loss preserved that
+      // shuffle, so its cleanup must still run when it is proven gone.
+      val passesExecutorFence = ignoreShuffleFileLostEpoch ||
+        !shuffleFileLostEpoch.contains(execId) ||
+        shuffleFileLostEpoch(execId) < currentEpoch
+      val reliableFetchFailedBypass = !passesExecutorFence && 
failedShuffleId.exists { id =>
+        mapOutputTracker.isReliablyStored(id) &&
+          reliableShuffleFileLostEpoch.get((execId, id)).forall(_ < 
currentEpoch)
       }
-      if (remove) {
+      if (passesExecutorFence || reliableFetchFailedBypass) {
+        // A bypass-only admission touches just the failed shuffle: only it is 
proven gone, so
+        // co-located shuffles (their freshly recomputed maps) must not be 
swept.
         hostToUnregisterOutputs match {
           case Some(host) =>
             logInfo(log"Shuffle files lost for host: ${MDC(HOST, host)} (epoch 
" +
               log"${MDC(EPOCH, currentEpoch)}")
-            mapOutputTracker.removeOutputsOnHost(host)
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored, failed,
+                  restrictToFailedShuffle = reliableFetchFailedBypass)
+            }
           case None =>
-              logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
-                log"(epoch ${MDC(EPOCH, currentEpoch)})")
-            mapOutputTracker.removeOutputsOnExecutor(execId)
+            logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
+              log"(epoch ${MDC(EPOCH, currentEpoch)})")
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored, failed,
+                  restrictToFailedShuffle = reliableFetchFailedBypass)
+            }
+        }
+        // A genuine executor-wide cleanup advances the executor fence 
(monotonically) to dedup
+        // same-epoch duplicates. A bypass-only admission must not move it (it 
did not clean the
+        // executor); it only records the per-shuffle fence so that shuffle's 
own duplicates are
+        // deduped. Both stamps are monotonic. Match prior behavior: skip 
under ignore. Skip the
+        // per-shuffle stamp once the map stage is gone (e.g. this FetchFailed 
aborted the job):
+        // stage cleanup already retired its fences and nothing would retire a 
new one.
+        if (!ignoreShuffleFileLostEpoch) {
+          if (passesExecutorFence) {
+            shuffleFileLostEpoch(execId) = currentEpoch
+          }
+          failedShuffleId.filter(shuffleIdToMapStage.contains).foreach { id =>

Review Comment:
   **Nit (P3):** This writes `reliableShuffleFileLostEpoch` for every failed 
shuffle, even in an application with no reliable shuffle at all, but 
`reliableFetchFailedBypass` reads an entry only after 
`mapOutputTracker.isReliablyStored(id)` is true, and that bit is fixed at 
registration. An entry for a shuffle that is not reliably stored is therefore 
never consulted. It only costs a `filterInPlace` pass on each map-stage removal 
and executor registration, and it contradicts the field doc, which says the map 
holds the epoch of a FetchFailed "for a reliably-stored shuffle". Adding 
`mapOutputTracker.isReliablyStored(id)` to this filter keeps the map to the 
state the bypass can use.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58437#discussion_r4085168340).
   
   See **Shared repair plan 1** in the review body.



##########
core/src/test/scala/org/apache/spark/MapOutputTrackerSuite.scala:
##########
@@ -136,6 +136,172 @@ class MapOutputTrackerSuite extends SparkFunSuite with 
LocalSparkContext {
     rpcEnv.shutdown()
   }
 
+  test("SPARK-59138: executor loss skips reliably-stored shuffles but not 
local-disk ones") {
+    val rpcEnv = createRpcEnv("test")
+    val tracker = newTrackerMaster()
+    tracker.trackerEndpoint = 
rpcEnv.setupEndpoint(MapOutputTracker.ENDPOINT_NAME,
+      new MapOutputTrackerMasterEndpoint(rpcEnv, tracker, conf))
+
+    val size = MapStatus.compressSize(1000L)
+    // Shuffle 0: local-disk (not reliably stored). Shuffle 1: reliably stored 
off-executor.
+    tracker.registerShuffle(0, 1, MergeStatus.SHUFFLE_PUSH_DUMMY_NUM_REDUCES)
+    tracker.registerShuffle(1, 1, MergeStatus.SHUFFLE_PUSH_DUMMY_NUM_REDUCES,
+      isReliablyStored = true)
+    tracker.registerMapOutput(0, 0, MapStatus(BlockManagerId("a", "hostA", 
1000), Array(size), 5))
+    tracker.registerMapOutput(1, 0, MapStatus(BlockManagerId("a", "hostA", 
1000), Array(size), 6))
+
+    assert(tracker.isReliablyStored(0) === false)
+    assert(tracker.isReliablyStored(1) === true)
+
+    // Executor loss: skip reliably-stored shuffles. Shuffle 0 drops, shuffle 
1 stays.
+    tracker.removeOutputsOnExecutor("a", respectReliablyStored = true)
+    assert(tracker.getNumAvailableOutputs(0) === 0)
+    assert(tracker.getNumAvailableOutputs(1) === 1)
+
+    // Losing an executor when only reliably-stored shuffles remain removes 
nothing, so the
+    // epoch must not bump (a bump would needlessly invalidate every 
executor's cached statuses).
+    tracker.unregisterShuffle(0)
+    val epochBeforeNoOp = tracker.getEpoch
+    tracker.removeOutputsOnExecutor("a", respectReliablyStored = true)
+    assert(tracker.getEpoch === epochBeforeNoOp)
+
+    // Fetch failure (skip = false): even the reliably-stored shuffle's output 
is removed, and
+    // because something was removed the epoch bumps.
+    val epochBeforeRemoval = tracker.getEpoch
+    tracker.removeOutputsOnExecutor("a", respectReliablyStored = false)
+    assert(tracker.getNumAvailableOutputs(1) === 0)
+    assert(tracker.getEpoch > epochBeforeRemoval)
+
+    tracker.stop()
+    rpcEnv.shutdown()
+  }
+
+  test("SPARK-59138: hasUnreliablyStoredShuffle reflects active shuffle 
reliability") {
+    val rpcEnv = createRpcEnv("test")
+    val tracker = newTrackerMaster()
+    tracker.trackerEndpoint = 
rpcEnv.setupEndpoint(MapOutputTracker.ENDPOINT_NAME,
+      new MapOutputTrackerMasterEndpoint(rpcEnv, tracker, conf))
+
+    assert(!tracker.hasUnreliablyStoredShuffle)
+    tracker.registerShuffle(0, 1, MergeStatus.SHUFFLE_PUSH_DUMMY_NUM_REDUCES,
+      isReliablyStored = true)
+    assert(!tracker.hasUnreliablyStoredShuffle)
+    tracker.registerShuffle(1, 1, MergeStatus.SHUFFLE_PUSH_DUMMY_NUM_REDUCES)
+    assert(tracker.hasUnreliablyStoredShuffle)
+    tracker.unregisterShuffle(1)
+    assert(!tracker.hasUnreliablyStoredShuffle)
+
+    tracker.stop()
+    rpcEnv.shutdown()
+  }
+
+  test("SPARK-59138: host loss drops merge results but keeps reliably-stored 
map output") {
+    val pushConf = new SparkConf()
+    pushConf.set(PUSH_BASED_SHUFFLE_ENABLED, true)
+    pushConf.set(IS_TESTING, true)
+    pushConf.set(SERIALIZER, "org.apache.spark.serializer.KryoSerializer")
+    val rpcEnv = createRpcEnv("test")
+    val tracker = newTrackerMaster(pushConf)
+    tracker.trackerEndpoint = 
rpcEnv.setupEndpoint(MapOutputTracker.ENDPOINT_NAME,
+      new MapOutputTrackerMasterEndpoint(rpcEnv, tracker, pushConf))
+
+    val size = MapStatus.compressSize(1000L)
+    // Reliably-stored shuffle whose map output lives off-executor, but which 
also has a host-local
+    // push-merge result on the same host. Losing the host must keep the 
reliable map output while
+    // still dropping the merge result, whose merged chunks physically lived 
on that host.
+    tracker.registerShuffle(0, 1, MergeStatus.SHUFFLE_PUSH_DUMMY_NUM_REDUCES,
+      isReliablyStored = true)
+    tracker.registerMapOutput(0, 0, MapStatus(BlockManagerId("a", "hostA", 
1000), Array(size), 5))
+    val bitmap = new RoaringBitmap()
+    bitmap.add(0)
+    tracker.registerMergeResult(0, 0, MergeStatus(BlockManagerId(
+      BlockManagerId.SHUFFLE_MERGER_IDENTIFIER, "hostA", 1000), 0, bitmap, 
1000L))
+    assert(tracker.getNumAvailableOutputs(0) === 1)
+    assert(tracker.getNumAvailableMergeResults(0) === 1)
+
+    tracker.removeOutputsOnHost("hostA", respectReliablyStored = true)

Review Comment:
   **Nit (P3):** Here `removeMergeResultsByFilter` removes the merge result, 
and that change reaches `CleanupOutcome` only through the `alreadyChanged` 
argument, because the reliable map output takes the preserve branch. If that 
argument were dropped, the outcome would be `(false, true)` and 
`shouldBumpEpoch` would be `false`, so executors would keep cached 
`MergeStatus` entries pointing at the lost merger host. Both count assertions 
would still pass, and no other test checks the epoch on this path. Capturing 
`tracker.getEpoch` before the call and asserting that it advances closes the 
gap.
   
   **Verification:**
   - **Regression:** A selective host cleanup on a reliable shuffle that 
removes only a merge result must advance the map-output epoch.



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -7057,11 +7399,10 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
 
   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.
+    // The materialized-prefix mixed shape is admitted only by adaptive 
execution; an all-pipelined

Review Comment:
   **Nit (P3):** The original text said this shape is "produced only by 
adaptive execution" while classification "keys purely off dependency TYPE". 
"Admitted only by adaptive execution" now claims the scheduler gates the shape 
on adaptive execution, but `classifyJobShuffleShape` accepts it for any job 
whose regular boundaries are materialized, and the neighboring test 'a 
fully-materialized regular prefix below the suffix is accepted' builds it from 
plain `MyRDD`s and is accepted. Restoring "produced" keeps the comment true.
   
   **Verification:**
   - **Inspection:** Confirm the comment agrees with the neighboring test that 
builds the materialized-prefix shape without adaptive execution and is accepted.



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -1116,11 +1130,347 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     completeShuffleMapStageSuccessfully(0, 0, 1)
     runEvent(ExecutorLost("hostA-exec", event))
     verify(blockManagerMaster, times(1)).removeExecutorAsync("hostA-exec")
-    verify(mapOutputTracker, times(0)).removeOutputsOnExecutor("hostA-exec")
+    verify(mapOutputTracker, times(0)).removeOutputsOnExecutor("hostA-exec", 
true)
     assert(mapOutputTracker.getMapSizesByExecutorId(shuffleId, 
0).map(_._1).toSet ===
       HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
   }
 
+  /**
+   * Submit a job over a single reliably-stored shuffle (service off) and 
complete its map stage,
+   * returning the job id and shuffle dependency. Shared by the fence/bypass 
tests that start alike.
+   */
+  private def submitReliableShuffleJob(
+      numMaps: Int,
+      numReduces: Int,
+      hostNames: Seq[String] = Nil): (Int, ReliablyStoredShuffleDependency) = {
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+    val shuffleMapRdd = new MyRDD(sc, numMaps, Nil)
+    val shuffleDep =
+      new ReliablyStoredShuffleDependency(shuffleMapRdd, new 
HashPartitioner(numReduces))
+    val reduceRdd = new MyRDD(sc, numReduces, List(shuffleDep), tracker = 
mapOutputTracker)
+    val jobId = submit(reduceRdd, (0 until numReduces).toArray)
+    val stageId = scheduler.shuffleIdToMapStage(shuffleDep.shuffleId).id
+    completeShuffleMapStageSuccessfully(stageId, 0, numReduces, hostNames = 
hostNames)
+    (jobId, shuffleDep)
+  }
+
+  test("SPARK-59138: executor loss keeps a reliably-stored shuffle but drops a 
local-disk one") {
+    // No external shuffle service, so a plain (local-disk) shuffle's outputs 
are lost on executor
+    // loss, but a per-shuffle reliably-stored one survives.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(1))
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(1))
+    val reduceRdd = new MyRDD(sc, 1, List(reliableDep, localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    // Two independent map stages, one per shuffle; complete both on hostA / 
hostB.
+    completeShuffleMapStageSuccessfully(0, 0, 1)
+    completeShuffleMapStageSuccessfully(1, 0, 1)
+
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+    verify(mapOutputTracker, times(1)).removeOutputsOnExecutor("hostA-exec", 
true)
+
+    // Reliable shuffle keeps hostA's output; local-disk shuffle loses it.
+    assert(mapOutputTracker.getMapSizesByExecutorId(reliableDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(localDep.shuffleId, 0)
+    }
+  }
+
+  test("SPARK-59138: per-shuffle reliablyStored=false overrides a global 
supportsReliableStorage") {
+    // Global flag true, but one shuffle reports Some(false); the per-shuffle 
value must win.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+    conf.set(config.SHUFFLE_IO_PLUGIN_CLASS.key,
+      classOf[TestShuffleDataIOWithMockedComponents].getName)
+    when(sc.shuffleDriverComponents.supportsReliableStorage()).thenReturn(true)
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(1))
+    val fallbackRdd = new MyRDD(sc, 2, Nil)
+    val fallbackDep =
+      new ReliablyStoredShuffleDependency(fallbackRdd, new HashPartitioner(1), 
Some(false))
+    val reduceRdd = new MyRDD(sc, 1, List(reliableDep, fallbackDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    completeShuffleMapStageSuccessfully(0, 0, 1)
+    completeShuffleMapStageSuccessfully(1, 0, 1)
+
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+
+    // Some(true) keeps hostA's output despite the global flag; Some(false) 
loses it despite it.
+    assert(mapOutputTracker.getMapSizesByExecutorId(reliableDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(fallbackDep.shuffleId, 0)
+    }
+  }
+
+  test("SPARK-59138: a duplicate same-epoch FetchFailed for a reliable shuffle 
is fenced by the " +
+    "per-shuffle bypass") {
+    // Executor loss preserves the reliable shuffle but stamps the executor 
fence. The first
+    // same-epoch reliable FetchFailed takes the per-shuffle bypass, cleans 
the failed shuffle, and
+    // records its reliableShuffleFileLostEpoch entry. A duplicate at the same 
epoch must be fenced
+    // by that entry, or repeated failures would re-clean and sweep freshly 
recomputed output.
+    val shuffleDep = submitReliableShuffleJob(numMaps = 2, numReduces = 2)._2
+    val shuffleId = shuffleDep.shuffleId
+
+    // Executor loss preserves the reliable shuffle and stamps the executor 
fence.
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+
+    // First same-epoch reliable FetchFailed: fence rejects it, per-shuffle 
bypass cleans.
+    runEvent(makeCompletionEvent(taskSets(1).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), shuffleId, 0L, 0, 0, 
"ignored"), null))
+
+    // Duplicate at the same epoch: fenced by the per-shuffle entry, no 
re-clean.
+    runEvent(makeCompletionEvent(taskSets(1).tasks(1),
+      FetchFailed(makeBlockManagerId("hostA"), shuffleId, 0L, 0, 1, 
"ignored"), null))
+
+    verify(mapOutputTracker, times(1))
+      .removeOutputsOnExecutor("hostA-exec", true, Some(shuffleId), true)
+  }
+
+  test("SPARK-59138: map-output FetchFailed clears the failed shuffle's 
co-located maps in one " +
+    "pass while an unrelated reliable shuffle on the same executor survives") {
+    // A FetchFailed against a reliably-stored map output is evidence that 
shuffle's output on the
+    // host is actually gone, so the failed shuffle is exempted from reliable 
preservation and all
+    // its maps on hostA clear together. A different reliable shuffle on hostA 
has no such evidence
+    // and stays registered.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val failedRdd = new MyRDD(sc, 2, Nil)
+    val failedDep = new ReliablyStoredShuffleDependency(failedRdd, new 
HashPartitioner(1))
+    val otherRdd = new MyRDD(sc, 1, Nil)
+    val otherDep = new ReliablyStoredShuffleDependency(otherRdd, new 
HashPartitioner(1))
+    val reduceRdd = new MyRDD(sc, 1, List(failedDep, otherDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    // Both shuffles' maps land on hostA; the failed shuffle's two maps must 
clear, the other's not.
+    completeShuffleMapStageSuccessfully(0, 0, 1, hostNames = Seq("hostA", 
"hostA"))
+    completeShuffleMapStageSuccessfully(1, 0, 1, hostNames = Seq("hostA", 
"hostA"))
+
+    complete(taskSets(2), Seq(
+      (FetchFailed(makeBlockManagerId("hostA"), failedDep.shuffleId, 0L, 0, 0, 
"ignored"), null)))
+
+    // The failed shuffle loses both hostA maps in one pass (it is exempted 
from preservation).
+    // getNumAvailableOutputs proves both are gone: the old per-map behavior 
would leave one.
+    assert(mapOutputTracker.getNumAvailableOutputs(failedDep.shuffleId) === 0)
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(failedDep.shuffleId, 0)
+    }
+    // The unrelated reliable shuffle keeps hostA's output.
+    assert(mapOutputTracker.getMapSizesByExecutorId(otherDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA")))
+  }
+
+  test("SPARK-59138: a delayed same-epoch FetchFailed is fenced after a local 
shuffle's retry " +
+    "re-registers output") {
+    // After a local shuffle's retry re-registers map 0, a delayed same-epoch 
FetchFailed for the
+    // still-missing map 1 must be fenced by the executor fence, or it 
bulk-deletes the recomputed
+    // map 0.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(2))
+    val localShuffleId = localDep.shuffleId
+    val reduceRdd = new MyRDD(sc, 2, List(localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0, 1))
+
+    val localStageId = scheduler.shuffleIdToMapStage(localShuffleId).id
+    completeShuffleMapStageSuccessfully(localStageId, 0, 2, hostNames = 
Seq("hostA", "hostA"))
+
+    // First FetchFailed for L clears both hostA maps and stamps the executor 
fence; L resubmits.
+    runEvent(makeCompletionEvent(taskSets(0).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), localShuffleId, 0L, 0, 0, 
"ignored"), null))
+    assert(mapOutputTracker.getNumAvailableOutputs(localShuffleId) === 0)
+    scheduler.resubmitFailedStages()
+
+    // Retry re-registers L's map 0 on the still-live hostA; map 1 stays 
pending.
+    val retry = taskSets.last
+    assert(retry.stageId === localStageId)
+    runEvent(makeCompletionEvent(retry.tasks(0), Success,
+      makeMapStatus("hostA", reduceRdd.partitions.length)))
+    assert(mapOutputTracker.getNumAvailableOutputs(localShuffleId) === 1)
+
+    // Delayed same-epoch duplicate FetchFailed for L's still-missing map 1 
must be fenced: no
+    // second cleanup, and map 0 survives.
+    runEvent(makeCompletionEvent(taskSets(0).tasks(1),
+      FetchFailed(makeBlockManagerId("hostA"), localShuffleId, 1L, 1, 1, 
"ignored"), null))
+
+    verify(mapOutputTracker, times(1))
+      .removeOutputsOnExecutor("hostA-exec", true, Some(localShuffleId), false)
+    assert(mapOutputTracker.getNumAvailableOutputs(localShuffleId) === 1)
+  }
+
+  test("SPARK-59138: a reliable-shuffle FetchFailed bypass cleans only the 
failed shuffle, " +
+    "leaving a co-located shuffle's recomputed output intact") {
+    // A delayed original FetchFailed for reliable R bypasses the executor 
fence but must stay
+    // restricted to R: it clears R's maps while a co-located local shuffle's 
recomputed output
+    // lives.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(2))
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(2))
+    val reduceRdd = new MyRDD(sc, 2, List(reliableDep, localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0, 1))
+
+    val reliableStageId = 
scheduler.shuffleIdToMapStage(reliableDep.shuffleId).id
+    val localStageId = scheduler.shuffleIdToMapStage(localDep.shuffleId).id
+    completeShuffleMapStageSuccessfully(reliableStageId, 0, 2, hostNames = 
Seq("hostA", "hostA"))
+    completeShuffleMapStageSuccessfully(localStageId, 0, 2, hostNames = 
Seq("hostA", "hostA"))
+    assert(mapOutputTracker.getNumAvailableOutputs(reliableDep.shuffleId) === 
2)
+
+    // FetchFailed for L's map 0 clears both its hostA maps and stamps the 
executor fence; L's map
+    // stage resubmits both maps.
+    runEvent(makeCompletionEvent(taskSets(2).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), localDep.shuffleId, 0L, 0, 0, 
"ignored"), null))
+    assert(mapOutputTracker.getNumAvailableOutputs(localDep.shuffleId) === 0)
+    scheduler.resubmitFailedStages()
+
+    // A real retry task re-registers L's map 0 on the still-live hostA; map 1 
stays pending, so the
+    // map stage is incomplete and the reducer attempt has not restarted.
+    val retry = taskSets.last
+    assert(retry.stageId === localStageId)
+    runEvent(makeCompletionEvent(retry.tasks(0), Success,
+      makeMapStatus("hostA", reduceRdd.partitions.length)))
+    assert(mapOutputTracker.getNumAvailableOutputs(localDep.shuffleId) === 1)
+
+    // Delayed original-attempt FetchFailed for R bypasses the executor fence, 
restricted to R.
+    taskSets(2).tasks(1).epoch = 0
+    runEvent(makeCompletionEvent(taskSets(2).tasks(1),
+      FetchFailed(makeBlockManagerId("hostA"), reliableDep.shuffleId, 0L, 0, 
1, "ignored"), null))
+
+    // Both R maps on hostA are cleared; L's recomputed map survives.
+    assert(mapOutputTracker.getNumAvailableOutputs(reliableDep.shuffleId) === 
0)
+    assert(mapOutputTracker.getNumAvailableOutputs(localDep.shuffleId) === 1)
+  }
+
+  test("SPARK-59138: an older reliable-shuffle FetchFailed bypass does not 
lower the executor " +
+    "fence, so a later same-epoch duplicate stays fenced") {
+    // A genuine executor-wide cleanup for local L stamps the executor fence 
at a high epoch E2. A
+    // later but older (epoch E1 < E2) reliable-shuffle FetchFailed bypasses 
the fence, yet must not
+    // move it backward to E1. Otherwise a duplicate L failure at E2 would 
pass the bulk gate again.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(2))
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(2))
+    val localShuffleId = localDep.shuffleId
+    val reduceRdd = new MyRDD(sc, 2, List(reliableDep, localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0, 1))
+
+    completeShuffleMapStageSuccessfully(0, 0, 2)
+    completeShuffleMapStageSuccessfully(1, 0, 2)
+
+    // Genuine executor-wide failure for L at epoch E2 stamps the fence at E2.
+    taskSets(2).tasks(0).epoch = 100
+    runEvent(makeCompletionEvent(taskSets(2).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), localShuffleId, 0L, 0, 0, 
"ignored"), null))
+
+    // Older reliable failure for R at epoch E1 < E2 bypasses the fence but 
must not lower it.
+    taskSets(2).tasks(1).epoch = 50
+    runEvent(makeCompletionEvent(taskSets(2).tasks(1),
+      FetchFailed(makeBlockManagerId("hostA"), reliableDep.shuffleId, 0L, 0, 
1, "ignored"), null))
+
+    // Duplicate L failure at E2: the fence is still E2, so it stays fenced 
(no second cleanup).
+    taskSets(2).tasks(0).epoch = 100
+    runEvent(makeCompletionEvent(taskSets(2).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), localShuffleId, 0L, 0, 0, 
"ignored"), null))
+
+    verify(mapOutputTracker, times(1))
+      .removeOutputsOnExecutor("hostA-exec", true, Some(localShuffleId), false)
+    verify(mapOutputTracker, times(1))
+      .removeOutputsOnExecutor("hostA-exec", true, 
Some(reliableDep.shuffleId), true)
+  }
+
+  test("SPARK-59138: reliable-loss fence entries are retired when their 
shuffle is cleaned up") {
+    // A reliable FetchFailed records a (executor, shuffleId) fence entry. 
These must be bounded by
+    // live shuffles: cleaning up the shuffle's map stage must drop its 
entries, otherwise replaced
+    // executors (new ids) leave them to accumulate for the life of the 
application.
+    val (jobId, reliableDep) =
+      submitReliableShuffleJob(numMaps = 2, numReduces = 2, hostNames = 
Seq("hostA", "hostA"))
+
+    // Reliable FetchFailed bypasses the executor fence and records a 
per-shuffle fence entry.
+    runEvent(makeCompletionEvent(taskSets(1).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), reliableDep.shuffleId, 0L, 0, 
0, "ignored"), null))
+    assert(scheduler.reliableShuffleFileLostEpochSize === 1)
+
+    // Cancelling the job tears down its stages; the shuffle's fence entries 
must be retired.
+    cancel(jobId)
+    assert(scheduler.reliableShuffleFileLostEpochSize === 0)
+  }
+
+  for (reliable <- Seq(true, false)) {
+    test(s"SPARK-59138: a FetchFailed that aborts the job leaves no fence 
entry " +
+      s"(reliable=$reliable)") {
+      // The abort tears the map stage down (retiring its fences) before the 
FetchFailed handler
+      // unregisters outputs, so the handler must not re-create a fence for 
the retired shuffle.
+      conf.set(config.STAGE_MAX_CONSECUTIVE_ATTEMPTS, 1)
+      conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+      val shuffleMapRdd = new MyRDD(sc, 2, Nil)
+      val partitioner = new HashPartitioner(2)
+      val shuffleDep = if (reliable) {
+        new ReliablyStoredShuffleDependency(shuffleMapRdd, partitioner)
+      } else {
+        new ShuffleDependency(shuffleMapRdd, partitioner)
+      }
+      val reduceRdd = new MyRDD(sc, 2, List(shuffleDep), tracker = 
mapOutputTracker)
+      submit(reduceRdd, Array(0, 1))
+      completeShuffleMapStageSuccessfully(0, 0, 2)
+
+      runEvent(makeCompletionEvent(taskSets(1).tasks(0),
+        FetchFailed(makeBlockManagerId("hostA"), shuffleDep.shuffleId, 0L, 0, 
0, "ignored"),
+        null))
+
+      assert(failure != null && failure.getMessage.contains("maximum 
allowable"))
+      assert(!scheduler.shuffleIdToMapStage.contains(shuffleDep.shuffleId))
+      assert(scheduler.reliableShuffleFileLostEpochSize === 0)
+    }
+  }
+
+  test("SPARK-59138: a merged-chunk FetchFailed for a reliable shuffle keeps 
its reliable map " +
+    "output") {
+    // A merged-chunk failure (mapIndex == -1) says nothing about the reliable 
original map output,
+    // so it must not take the reliable bypass (failedShuffleId stays None). 
The stale merge result
+    // is dropped, but the reliable map output survives as valid fallback.
+    initPushBasedShuffleConfs(conf)
+    DAGSchedulerSuite.clearMergerLocs()
+    DAGSchedulerSuite.addMergerLocs(Seq("host1", "host2", "host3", "host4", 
"host5"))
+    scheduler = new MyDAGScheduler(
+      sc, taskScheduler, sc.listenerBus, mapOutputTracker, blockManagerMaster, 
sc.env,
+      shuffleMergeFinalize = false, shuffleMergeRegister = false)
+    dagEventProcessLoopTester = new 
DAGSchedulerEventProcessLoopTester(scheduler)
+
+    val shuffleMapRdd = new MyRDD(sc, 2, Nil)
+    val shuffleDep = new ReliablyStoredShuffleDependency(shuffleMapRdd, new 
HashPartitioner(2))
+    val shuffleId = shuffleDep.shuffleId
+    val reduceRdd = new MyRDD(sc, 2, List(shuffleDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0, 1))
+
+    completeShuffleMapStageSuccessfully(0, 0, 2)
+    val shuffleMapStage = 
scheduler.stageIdToStage(0).asInstanceOf[ShuffleMapStage]
+    scheduler.handleRegisterMergeStatuses(shuffleMapStage,
+      Seq((0, makeMergeStatus("hostA", shuffleDep.shuffleMergeId, 
isShufflePushMerger = true))))
+    scheduler.handleShuffleMergeFinalized(shuffleMapStage, 
shuffleDep.shuffleMergeId)
+    assert(mapOutputTracker.getNumAvailableMergeResults(shuffleId) == 1)
+    assert(mapOutputTracker.getNumAvailableOutputs(shuffleId) === 2)
+
+    // Merged-chunk FetchFailed (mapIndex == -1) against the merger id: drops 
the merge result but
+    // the reliable map output is preserved (no reliable bypass on a 
merged-chunk failure).
+    val mergerId = Some(BlockManagerId.SHUFFLE_MERGER_IDENTIFIER)
+    runEvent(makeCompletionEvent(taskSets(1).tasks(0),

Review Comment:
   **Nit (P3):** With `spark.files.fetchFailure.unRegisterOutputOnHost` left at 
`false`, `unregisterOutputsOnFetchFailedExecutor` cleans at executor scope for 
`shuffle-push-merger`, and no map status is registered under that id; the maps 
are on `hostA-exec` and `hostB-exec`. If the `mapIndex != -1` guard always 
passed `Some(shuffleId)`, `removeOutputsOnExecutor("shuffle-push-merger", true, 
Some(shuffleId))` would still match nothing, and `getNumAvailableOutputs === 2` 
would still hold. The guard only changes behavior under host-scope cleanup, 
where `removeOutputsOnHost("hostA", true, Some(shuffleId))` would drop the 
reliable hostA map. Setting `unRegisterOutputOnHost` to `true` before the 
scheduler is constructed would make the test fail on that regression.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58437#discussion_r4085168402).
   
   **Verification:**
   - **Regression:** With host-scope cleanup, a merged-chunk FetchFailed for a 
reliable push-based shuffle must drop the merge result and keep both map 
outputs, and the assertion must fail when the merged-chunk path passes the 
failed shuffle id.



##########
core/src/main/scala/org/apache/spark/MapOutputTracker.scala:
##########
@@ -46,6 +46,26 @@ import org.apache.spark.util._
 import org.apache.spark.util.ArrayImplicits._
 import org.apache.spark.util.io.{ChunkedByteBuffer, 
ChunkedByteBufferOutputStream}
 
+/**
+ * Aggregate result of an executor/host cleanup on the 
`MapOutputTrackerMaster`.
+ * `metadataChanged`: any status removed (drives the epoch bump). 
`preservedReliable`: a
+ * reliably-stored shuffle was skipped, so the cleanup was selective rather 
than complete.

Review Comment:
   **Nit (P3):** `preservedReliable` is the OR of 
`ShuffleRemovalResult.mapPreservedReliable`, which 
`removeMapOutputsSelectively` sets only when a live map status of a reliable 
shuffle matched the target. A reliable shuffle whose output is all on other 
executors is skipped by the preserve branch but leaves the flag `false`, so the 
epoch still advances; the test 'losing an executor with no output for a 
reliable shuffle still bumps epoch' pins exactly that. Read literally, "a 
reliably-stored shuffle was skipped" describes the whole-shuffle verdict that 
would suppress the bump. Wording it as "reliable map output on the cleanup 
target was kept", as the `ShuffleRemovalResult` doc does, avoids inviting that 
regression.
   
   **Verification:**
   - **Inspection:** Confirm that the CleanupOutcome and ShuffleRemovalResult 
docs describe the same target-scoped condition that sets the flag.



##########
core/src/main/scala/org/apache/spark/MapOutputTracker.scala:
##########
@@ -1043,21 +1096,66 @@ private[spark] class MapOutputTrackerMaster(
 
   /**
    * Removes all shuffle outputs associated with this host. Note that this 
will also remove
-   * outputs which are served by an external shuffle server (if one exists).
+   * outputs which are served by an external shuffle server (if one exists). 
Unconditional cleanup:
+   * every shuffle's output on the host is dropped. See the two-argument 
overload for the selective
+   * (reliable-storage-preserving) variant.
    */
-  def removeOutputsOnHost(host: String): Unit = {
-    shuffleStatuses.valuesIterator.foreach { _.removeOutputsOnHost(host) }
-    incrementEpoch()
+  def removeOutputsOnHost(host: String): Unit =
+    removeOutputsOnHost(host, respectReliablyStored = false)
+
+  /**
+   * Removes shuffle outputs associated with this host, returning the 
aggregate cleanup outcome.
+   *
+   * When `respectReliablyStored` is true (executor/worker loss rather than a 
fetch failure),

Review Comment:
   Thanks, the tracker's descriptions of these flags read correctly now. A few 
comments still use the old framing: the comments at the executor-loss and 
worker-removal call sites contrast the flag with a fetch failure, although both 
fetch-failure paths also pass respectReliablyStored = true, and the helper's 
respectReliablyStored doc says the failed map is already unregistered, which 
the pipelined-group fetch-failure path does not do first. One test comment also 
still calls the unconditional cleanup the fetch-failure path; this review 
raises it together with two other new test comments that describe the wrong 
path.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4056996899","thread_id":"inline:4056996899","verdict_sha256":"3d53a51cbd0aca9006e6c94d100e248a1659492e1b8c4b3c08bcd77a60d3dbee"}
 -->



##########
core/src/main/scala/org/apache/spark/shuffle/ShuffleHandle.scala:
##########
@@ -25,4 +25,19 @@ import org.apache.spark.annotation.DeveloperApi
  * @param shuffleId ID of the shuffle
  */
 @DeveloperApi
-abstract class ShuffleHandle(val shuffleId: Int) extends Serializable {}
+abstract class ShuffleHandle(val shuffleId: Int) extends Serializable {
+  /**
+   * Whether this shuffle's output is stored reliably, off the executor that 
produced it (e.g. a
+   * remote shuffle service or distributed filesystem). When true, losing the 
executor or its host
+   * does not lose the output, so its map outputs are not unregistered on 
executor/worker loss.
+   *
+   * Applies only to materialized, map-output-tracked (blocking) shuffles. A 
pipelined shuffle is
+   * located through the streaming task-location registry, not map-status 
cleanup, so it cannot
+   * honor this flag; the scheduler rejects a non-`None` value on a pipelined 
dependency.
+   *
+   * Per-shuffle override of the app-global 
`ShuffleDriverComponents.supportsReliableStorage()`:
+   * `Some(value)` is authoritative for this shuffle; `None` (the default) 
means "no per-shuffle
+   * information", so the global flag is used and managers that don't set it 
keep legacy behavior.

Review Comment:
   **Nit (P3):** "managers that don't set it keep legacy behavior" is true only 
when `supportsReliableStorage()` is `false`. With a globally reliable plugin, a 
`None` handle now registers as reliably stored. `handleWorkerRemoved` then 
keeps its map output, where the base branch called `removeOutputsOnHost(host)` 
unconditionally, and a map-output FetchFailed clears only the failed shuffle, 
where the base branch cleared every shuffle on the executor or host. Those 
changes are intended, but plugin authors reading this DeveloperApi doc would 
conclude nothing changes for them. Saying that `None` falls back to the global 
flag, and naming those two changes for globally reliable plugins, would make 
the contract accurate.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58437#issuecomment-6711788369).
   
   **Verification:**
   - **Inspection:** Compare the None semantics in the reliablyStored Scaladoc 
with worker removal, FetchFailed cleanup and executor loss after the 
executor-loss repair, and confirm every stated behavior matches.



##########
core/src/test/scala/org/apache/spark/scheduler/DAGSchedulerSuite.scala:
##########
@@ -1116,11 +1130,347 @@ class DAGSchedulerSuite extends SparkFunSuite with 
TempLocalSparkContext with Ti
     completeShuffleMapStageSuccessfully(0, 0, 1)
     runEvent(ExecutorLost("hostA-exec", event))
     verify(blockManagerMaster, times(1)).removeExecutorAsync("hostA-exec")
-    verify(mapOutputTracker, times(0)).removeOutputsOnExecutor("hostA-exec")
+    verify(mapOutputTracker, times(0)).removeOutputsOnExecutor("hostA-exec", 
true)
     assert(mapOutputTracker.getMapSizesByExecutorId(shuffleId, 
0).map(_._1).toSet ===
       HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
   }
 
+  /**
+   * Submit a job over a single reliably-stored shuffle (service off) and 
complete its map stage,
+   * returning the job id and shuffle dependency. Shared by the fence/bypass 
tests that start alike.
+   */
+  private def submitReliableShuffleJob(
+      numMaps: Int,
+      numReduces: Int,
+      hostNames: Seq[String] = Nil): (Int, ReliablyStoredShuffleDependency) = {
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+    val shuffleMapRdd = new MyRDD(sc, numMaps, Nil)
+    val shuffleDep =
+      new ReliablyStoredShuffleDependency(shuffleMapRdd, new 
HashPartitioner(numReduces))
+    val reduceRdd = new MyRDD(sc, numReduces, List(shuffleDep), tracker = 
mapOutputTracker)
+    val jobId = submit(reduceRdd, (0 until numReduces).toArray)
+    val stageId = scheduler.shuffleIdToMapStage(shuffleDep.shuffleId).id
+    completeShuffleMapStageSuccessfully(stageId, 0, numReduces, hostNames = 
hostNames)
+    (jobId, shuffleDep)
+  }
+
+  test("SPARK-59138: executor loss keeps a reliably-stored shuffle but drops a 
local-disk one") {
+    // No external shuffle service, so a plain (local-disk) shuffle's outputs 
are lost on executor
+    // loss, but a per-shuffle reliably-stored one survives.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(1))
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(1))
+    val reduceRdd = new MyRDD(sc, 1, List(reliableDep, localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    // Two independent map stages, one per shuffle; complete both on hostA / 
hostB.
+    completeShuffleMapStageSuccessfully(0, 0, 1)
+    completeShuffleMapStageSuccessfully(1, 0, 1)
+
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+    verify(mapOutputTracker, times(1)).removeOutputsOnExecutor("hostA-exec", 
true)
+
+    // Reliable shuffle keeps hostA's output; local-disk shuffle loses it.
+    assert(mapOutputTracker.getMapSizesByExecutorId(reliableDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(localDep.shuffleId, 0)
+    }
+  }
+
+  test("SPARK-59138: per-shuffle reliablyStored=false overrides a global 
supportsReliableStorage") {
+    // Global flag true, but one shuffle reports Some(false); the per-shuffle 
value must win.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+    conf.set(config.SHUFFLE_IO_PLUGIN_CLASS.key,
+      classOf[TestShuffleDataIOWithMockedComponents].getName)
+    when(sc.shuffleDriverComponents.supportsReliableStorage()).thenReturn(true)
+
+    val reliableRdd = new MyRDD(sc, 2, Nil)
+    val reliableDep = new ReliablyStoredShuffleDependency(reliableRdd, new 
HashPartitioner(1))
+    val fallbackRdd = new MyRDD(sc, 2, Nil)
+    val fallbackDep =
+      new ReliablyStoredShuffleDependency(fallbackRdd, new HashPartitioner(1), 
Some(false))
+    val reduceRdd = new MyRDD(sc, 1, List(reliableDep, fallbackDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    completeShuffleMapStageSuccessfully(0, 0, 1)
+    completeShuffleMapStageSuccessfully(1, 0, 1)
+
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+
+    // Some(true) keeps hostA's output despite the global flag; Some(false) 
loses it despite it.
+    assert(mapOutputTracker.getMapSizesByExecutorId(reliableDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA"), makeBlockManagerId("hostB")))
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(fallbackDep.shuffleId, 0)
+    }
+  }
+
+  test("SPARK-59138: a duplicate same-epoch FetchFailed for a reliable shuffle 
is fenced by the " +
+    "per-shuffle bypass") {
+    // Executor loss preserves the reliable shuffle but stamps the executor 
fence. The first
+    // same-epoch reliable FetchFailed takes the per-shuffle bypass, cleans 
the failed shuffle, and
+    // records its reliableShuffleFileLostEpoch entry. A duplicate at the same 
epoch must be fenced
+    // by that entry, or repeated failures would re-clean and sweep freshly 
recomputed output.
+    val shuffleDep = submitReliableShuffleJob(numMaps = 2, numReduces = 2)._2
+    val shuffleId = shuffleDep.shuffleId
+
+    // Executor loss preserves the reliable shuffle and stamps the executor 
fence.
+    runEvent(ExecutorLost("hostA-exec", ExecutorKilled))
+
+    // First same-epoch reliable FetchFailed: fence rejects it, per-shuffle 
bypass cleans.
+    runEvent(makeCompletionEvent(taskSets(1).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), shuffleId, 0L, 0, 0, 
"ignored"), null))
+
+    // Duplicate at the same epoch: fenced by the per-shuffle entry, no 
re-clean.
+    runEvent(makeCompletionEvent(taskSets(1).tasks(1),
+      FetchFailed(makeBlockManagerId("hostA"), shuffleId, 0L, 0, 1, 
"ignored"), null))
+
+    verify(mapOutputTracker, times(1))
+      .removeOutputsOnExecutor("hostA-exec", true, Some(shuffleId), true)
+  }
+
+  test("SPARK-59138: map-output FetchFailed clears the failed shuffle's 
co-located maps in one " +
+    "pass while an unrelated reliable shuffle on the same executor survives") {
+    // A FetchFailed against a reliably-stored map output is evidence that 
shuffle's output on the
+    // host is actually gone, so the failed shuffle is exempted from reliable 
preservation and all
+    // its maps on hostA clear together. A different reliable shuffle on hostA 
has no such evidence
+    // and stays registered.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val failedRdd = new MyRDD(sc, 2, Nil)
+    val failedDep = new ReliablyStoredShuffleDependency(failedRdd, new 
HashPartitioner(1))
+    val otherRdd = new MyRDD(sc, 1, Nil)
+    val otherDep = new ReliablyStoredShuffleDependency(otherRdd, new 
HashPartitioner(1))
+    val reduceRdd = new MyRDD(sc, 1, List(failedDep, otherDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0))
+
+    // Both shuffles' maps land on hostA; the failed shuffle's two maps must 
clear, the other's not.
+    completeShuffleMapStageSuccessfully(0, 0, 1, hostNames = Seq("hostA", 
"hostA"))
+    completeShuffleMapStageSuccessfully(1, 0, 1, hostNames = Seq("hostA", 
"hostA"))
+
+    complete(taskSets(2), Seq(
+      (FetchFailed(makeBlockManagerId("hostA"), failedDep.shuffleId, 0L, 0, 0, 
"ignored"), null)))
+
+    // The failed shuffle loses both hostA maps in one pass (it is exempted 
from preservation).
+    // getNumAvailableOutputs proves both are gone: the old per-map behavior 
would leave one.
+    assert(mapOutputTracker.getNumAvailableOutputs(failedDep.shuffleId) === 0)
+    intercept[MetadataFetchFailedException] {
+      mapOutputTracker.getMapSizesByExecutorId(failedDep.shuffleId, 0)
+    }
+    // The unrelated reliable shuffle keeps hostA's output.
+    assert(mapOutputTracker.getMapSizesByExecutorId(otherDep.shuffleId, 
0).map(_._1).toSet ===
+      HashSet(makeBlockManagerId("hostA")))
+  }
+
+  test("SPARK-59138: a delayed same-epoch FetchFailed is fenced after a local 
shuffle's retry " +
+    "re-registers output") {
+    // After a local shuffle's retry re-registers map 0, a delayed same-epoch 
FetchFailed for the
+    // still-missing map 1 must be fenced by the executor fence, or it 
bulk-deletes the recomputed
+    // map 0.
+    conf.set(config.SHUFFLE_SERVICE_ENABLED.key, "false")
+
+    val localRdd = new MyRDD(sc, 2, Nil)
+    val localDep = new ShuffleDependency(localRdd, new HashPartitioner(2))
+    val localShuffleId = localDep.shuffleId
+    val reduceRdd = new MyRDD(sc, 2, List(localDep), tracker = 
mapOutputTracker)
+    submit(reduceRdd, Array(0, 1))
+
+    val localStageId = scheduler.shuffleIdToMapStage(localShuffleId).id
+    completeShuffleMapStageSuccessfully(localStageId, 0, 2, hostNames = 
Seq("hostA", "hostA"))
+
+    // First FetchFailed for L clears both hostA maps and stamps the executor 
fence; L resubmits.
+    runEvent(makeCompletionEvent(taskSets(0).tasks(0),
+      FetchFailed(makeBlockManagerId("hostA"), localShuffleId, 0L, 0, 0, 
"ignored"), null))
+    assert(mapOutputTracker.getNumAvailableOutputs(localShuffleId) === 0)
+    scheduler.resubmitFailedStages()
+
+    // Retry re-registers L's map 0 on the still-live hostA; map 1 stays 
pending.
+    val retry = taskSets.last
+    assert(retry.stageId === localStageId)
+    runEvent(makeCompletionEvent(retry.tasks(0), Success,
+      makeMapStatus("hostA", reduceRdd.partitions.length)))
+    assert(mapOutputTracker.getNumAvailableOutputs(localShuffleId) === 1)
+
+    // Delayed same-epoch duplicate FetchFailed for L's still-missing map 1 
must be fenced: no
+    // second cleanup, and map 0 survives.
+    runEvent(makeCompletionEvent(taskSets(0).tasks(1),

Review Comment:
   **Nit (P3):** Both events come from `taskSets(0)`, the shuffle map stage's 
attempt-0 task set. Once `resubmitFailedStages()` starts attempt 1 of that 
stage, `handleTaskCompletion` ignores this delayed FetchFailed at the 
`failedStage.latestInfo.attemptNumber() != task.stageAttemptId` check, before 
`unregisterOutputsOnFetchFailedExecutor` runs. Making `passesExecutorFence` 
always true would therefore leave the `times(1)` verify and the 'map 0 
survives' assertion passing. Reporting both failures from the result stage's 
task set, `taskSets(1)`, whose attempt stays current while it waits on the 
resubmitted parent, would route the delayed event to the fence. Another test 
still pins the executor-fence dedup, so the gap is a test that reads as 
coverage it does not provide.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/58437#discussion_r4066169776).
   
   **Verification:**
   - **Regression:** With the executor-fence comparison disabled, the delayed 
same-epoch duplicate scenario must fail; with it enabled, the duplicate runs no 
cleanup and the recomputed map output survives.



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -4674,27 +4715,42 @@ private[spark] class DAGScheduler(
       clearCacheLocs()
     }
     if (fileLost) {
-      // When the fetch failure is for a merged shuffle chunk, 
ignoreShuffleFileLostEpoch is true
-      // and so all the files will be removed.
-      val remove = if (ignoreShuffleFileLostEpoch) {
-        true
-      } else if (!shuffleFileLostEpoch.contains(execId) ||
-        shuffleFileLostEpoch(execId) < currentEpoch) {
-        shuffleFileLostEpoch(execId) = currentEpoch
-        true
-      } else {
-        false
+      // ignoreShuffleFileLostEpoch (merged-chunk failure) removes everything 
past the gate. A
+      // FetchFailed for a reliably-stored shuffle is exempt once per epoch: 
the executor loss
+      // preserved it, so the executor fence would otherwise skip clearing it 
now proven gone.
+      val reliableFetchFailedBypass = failedShuffleId.exists { id =>
+        mapOutputTracker.isReliablyStored(id) &&
+          reliableShuffleFileLostEpoch.get((execId, id)).forall(_ < 
currentEpoch)
       }
-      if (remove) {
+      val shouldRemove = ignoreShuffleFileLostEpoch ||
+        reliableFetchFailedBypass ||
+        !shuffleFileLostEpoch.contains(execId) ||
+        shuffleFileLostEpoch(execId) < currentEpoch
+      if (shouldRemove) {
         hostToUnregisterOutputs match {
           case Some(host) =>
             logInfo(log"Shuffle files lost for host: ${MDC(HOST, host)} (epoch 
" +
               log"${MDC(EPOCH, currentEpoch)}")
-            mapOutputTracker.removeOutputsOnHost(host)
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnHost(host, 
respectReliablyStored, failed)
+            }
           case None =>
-              logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
-                log"(epoch ${MDC(EPOCH, currentEpoch)})")
-            mapOutputTracker.removeOutputsOnExecutor(execId)
+            logInfo(log"Shuffle files lost for executor: ${MDC(EXECUTOR_ID, 
execId)} " +
+              log"(epoch ${MDC(EPOCH, currentEpoch)})")
+            failedShuffleId match {
+              case None => mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored)
+              case failed =>
+                mapOutputTracker.removeOutputsOnExecutor(execId, 
respectReliablyStored, failed)
+            }
+        }
+        // Stamp the executor fence on every real cleanup to dedup same-epoch 
duplicates; also stamp
+        // the per-shuffle fence so a bypassed reliable shuffle's own 
duplicates are deduped. Match
+        // prior behavior: don't stamp under ignoreShuffleFileLostEpoch.
+        if (!ignoreShuffleFileLostEpoch) {
+          shuffleFileLostEpoch(execId) = currentEpoch
+          failedShuffleId.foreach(id => reliableShuffleFileLostEpoch((execId, 
id)) = currentEpoch)

Review Comment:
   Thanks, tying the entries to the map stage bounds them. This review raises 
one remaining point: the entries are still written for shuffles that are not 
reliably stored, which the bypass never reads.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4085168340","thread_id":"inline:4085168340","verdict_sha256":"3d53a51cbd0aca9006e6c94d100e248a1659492e1b8c4b3c08bcd77a60d3dbee"}
 -->



##########
core/src/main/scala/org/apache/spark/scheduler/DAGScheduler.scala:
##########
@@ -4043,7 +4057,10 @@ private[spark] class DAGScheduler(
           }
 
           // TODO: mark the executor as failed only if there were lots of 
fetch failures on it
-          unregisterOutputsOnFetchFailedExecutor(bmAddress, task)
+          // Exempt the failed shuffle from reliable-preservation only on a 
map-output failure
+          // (mapIndex != -1); a merged-chunk failure says nothing about its 
reliable map output.
+          val failedMapShuffleId = if (mapIndex != -1) Some(shuffleId) else 
None

Review Comment:
   Thanks for adding the case. This review raises that the new test still 
passes when the merged-chunk path passes Some(shuffleId), so the guard is not 
yet protected.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4085168402","thread_id":"inline:4085168402","verdict_sha256":"3d53a51cbd0aca9006e6c94d100e248a1659492e1b8c4b3c08bcd77a60d3dbee"}
 -->



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