sunchao commented on code in PR #58714:
URL: https://github.com/apache/spark/pull/58714#discussion_r4543155958


##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +464,185 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)
+              } && reservation.taskSet.canRunOomRetry(
+                reservation.index, reservation.executorId, host)
+            } && reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+      }
+    })
+    hadReservation && oomRetryReservation.isEmpty
+  }
+
+  /**
+   * Give OOM retries idle capacity before ordinary placement. Repeated OOMs 
reserve at most one
+   * executor across offer rounds, allowing existing tasks to drain without 
backfilling it. Only
+   * this recovery pass ignores locality preferences; resource requirements 
and exclusions remain
+   * mandatory. A bounded wait in TaskSetManager makes an unavailable 
reservation fall back to
+   * ordinary scheduling instead of turning an OOM into an indefinitely 
pending retry.
+   */
+  private def scheduleOomRetries(
+      taskSets: ArrayBuffer[TaskSetManager],
+      offers: IndexedSeq[WorkerOffer],
+      availableCpus: Array[BigDecimal],
+      availableResources: Array[ExecutorResourcesAmounts],
+      tasks: IndexedSeq[ArrayBuffer[TaskDescription]]): Set[TaskSetManager] = {
+    refreshOomRetryReservation()
+    val launchedTaskSets = new HashSet[TaskSetManager]
+    def taskCpusFor(taskSet: TaskSetManager): BigDecimal = {
+      val profile = sc.resourceProfileManager
+        .resourceProfileFromId(taskSet.taskSet.resourceProfileId)
+      ResourceProfile.getTaskCpusOrDefaultForProfile(profile, conf)
+    }
+
+    // A compatible profile does not guarantee that every executor has enough 
total resources.
+    // Once a reserved executor is idle, its offer tells us whether the retry 
can actually fit.
+    setOomRetryReservation(oomRetryReservation.filterNot { reservation =>
+      reservation.taskId.isEmpty && offers.indices.exists { i =>
+        offers(i).executorId == reservation.executorId &&
+          !isExecutorBusy(reservation.executorId) &&
+          resourcesMeetTaskRequirements(
+            reservation.taskSet, taskCpusFor(reservation.taskSet),
+            availableCpus(i), availableResources(i)).isEmpty
+      }
+    })
+
+    def eligible(taskSet: TaskSetManager, index: Int, i: Int): Boolean = {
+      val offer = offers(i)
+      isExecutorAlive(offer.executorId) &&
+        sc.resourceProfileManager.canBeScheduled(
+          taskSet.taskSet.resourceProfileId, offer.resourceProfileId) &&
+        taskSet.canRunOomRetry(index, offer.executorId, offer.host)
+    }
+
+    def launch(taskSet: TaskSetManager, index: Int, i: Int): Option[Long] = {
+      val offer = offers(i)
+      if (!eligible(taskSet, index, i) || isExecutorBusy(offer.executorId)) {
+        return None
+      }
+      resourcesMeetTaskRequirements(
+        taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i)).flatMap {
+        assignments =>
+          val taskCpus = taskCpusFor(taskSet)
+          try {
+            taskSet.resourceOfferOomRetry(
+              index, offer.executorId, offer.host, taskCpus, assignments)
+              .map { task =>
+                tasks(i) += task
+                addRunningTask(task.taskId, offer.executorId, taskSet)
+                launchedTaskSets += taskSet
+                availableCpus(i) -= task.cpus
+                availableResources(i).acquire(task.resources)
+                task.taskId
+              }
+          } catch {
+            case e: TaskNotSerializableException =>
+              // prepareLaunchingTask already aborts the task set on 
serialization failure.
+              logError("Failed to serialize an OOM retry", e)
+              None
+          }
+      }
+    }
+
+    if (oomRetryReservation.isEmpty) {
+      for {
+        taskSet <- taskSets
+        index <- taskSet.pendingOomRetries
+        if oomRetryReservation.isEmpty && taskSet.oomRetryNeedsIsolation(index)
+      } {
+        val candidates = offers.indices.filter { i =>

Review Comment:
   Only a full offer round can now create a reservation. A partial offer can 
still launch the pending retry once its reserved executor is idle. The 
regression test offers a busy executor alone, then includes an idle peer in the 
full round.



##########
core/src/main/scala/org/apache/spark/scheduler/ExecutorResourcesAmounts.scala:
##########
@@ -74,6 +74,23 @@ private[spark] class ExecutorResourcesAmounts(
     }
   }
 
+  /** Count tasks that fit the current resource amounts, without consuming the 
live offer. */
+  def availableTaskSlots(taskSetProf: ResourceProfile, maxTasks: Int): Int = {
+    if (taskSetProf.getCustomTaskResources().isEmpty) return maxTasks
+    val remaining = new ExecutorResourcesAmounts(
+      internalResources.map { case (name, amounts) => name -> amounts.toMap })
+    var slots = 0
+    while (slots < maxTasks) {
+      remaining.assignAddressesCustomResources(taskSetProf) match {

Review Comment:
   Barrier slot counting now computes capacity directly from whole addresses 
and remaining fractional shares, capped by CPU capacity. It no longer copies 
the maps or simulates an assignment per slot.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +464,185 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)
+              } && reservation.taskSet.canRunOomRetry(
+                reservation.index, reservation.executorId, host)
+            } && reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+      }
+    })
+    hadReservation && oomRetryReservation.isEmpty
+  }
+
+  /**
+   * Give OOM retries idle capacity before ordinary placement. Repeated OOMs 
reserve at most one
+   * executor across offer rounds, allowing existing tasks to drain without 
backfilling it. Only
+   * this recovery pass ignores locality preferences; resource requirements 
and exclusions remain
+   * mandatory. A bounded wait in TaskSetManager makes an unavailable 
reservation fall back to
+   * ordinary scheduling instead of turning an OOM into an indefinitely 
pending retry.
+   */
+  private def scheduleOomRetries(
+      taskSets: ArrayBuffer[TaskSetManager],
+      offers: IndexedSeq[WorkerOffer],
+      availableCpus: Array[BigDecimal],
+      availableResources: Array[ExecutorResourcesAmounts],
+      tasks: IndexedSeq[ArrayBuffer[TaskDescription]]): Set[TaskSetManager] = {
+    refreshOomRetryReservation()
+    val launchedTaskSets = new HashSet[TaskSetManager]
+    def taskCpusFor(taskSet: TaskSetManager): BigDecimal = {
+      val profile = sc.resourceProfileManager
+        .resourceProfileFromId(taskSet.taskSet.resourceProfileId)
+      ResourceProfile.getTaskCpusOrDefaultForProfile(profile, conf)
+    }
+
+    // A compatible profile does not guarantee that every executor has enough 
total resources.
+    // Once a reserved executor is idle, its offer tells us whether the retry 
can actually fit.
+    setOomRetryReservation(oomRetryReservation.filterNot { reservation =>
+      reservation.taskId.isEmpty && offers.indices.exists { i =>
+        offers(i).executorId == reservation.executorId &&
+          !isExecutorBusy(reservation.executorId) &&
+          resourcesMeetTaskRequirements(
+            reservation.taskSet, taskCpusFor(reservation.taskSet),
+            availableCpus(i), availableResources(i)).isEmpty
+      }
+    })
+
+    def eligible(taskSet: TaskSetManager, index: Int, i: Int): Boolean = {
+      val offer = offers(i)
+      isExecutorAlive(offer.executorId) &&
+        sc.resourceProfileManager.canBeScheduled(
+          taskSet.taskSet.resourceProfileId, offer.resourceProfileId) &&
+        taskSet.canRunOomRetry(index, offer.executorId, offer.host)
+    }
+
+    def launch(taskSet: TaskSetManager, index: Int, i: Int): Option[Long] = {
+      val offer = offers(i)
+      if (!eligible(taskSet, index, i) || isExecutorBusy(offer.executorId)) {
+        return None
+      }
+      resourcesMeetTaskRequirements(
+        taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i)).flatMap {
+        assignments =>
+          val taskCpus = taskCpusFor(taskSet)
+          try {
+            taskSet.resourceOfferOomRetry(
+              index, offer.executorId, offer.host, taskCpus, assignments)
+              .map { task =>
+                tasks(i) += task
+                addRunningTask(task.taskId, offer.executorId, taskSet)
+                launchedTaskSets += taskSet
+                availableCpus(i) -= task.cpus
+                availableResources(i).acquire(task.resources)
+                task.taskId
+              }
+          } catch {
+            case e: TaskNotSerializableException =>
+              // prepareLaunchingTask already aborts the task set on 
serialization failure.
+              logError("Failed to serialize an OOM retry", e)
+              None
+          }
+      }
+    }
+
+    if (oomRetryReservation.isEmpty) {
+      for {
+        taskSet <- taskSets
+        index <- taskSet.pendingOomRetries
+        if oomRetryReservation.isEmpty && taskSet.oomRetryNeedsIsolation(index)
+      } {
+        val candidates = offers.indices.filter { i =>
+          eligible(taskSet, index, i) &&
+            (isExecutorBusy(offers(i).executorId) ||
+              resourcesMeetTaskRequirements(
+                taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i))
+                .isDefined)
+        }
+        // A busy executor may currently offer no CPUs or custom resources. 
Check its profile
+        // now and its actual free resources again after it drains, before 
launching anything.
+        candidates.sortBy(i => 
executorIdToRunningTaskIds(offers(i).executorId).size)
+          .headOption.foreach { i =>
+            setOomRetryReservation(Some(
+              OomRetryReservation(taskSet, index, offers(i).executorId)))
+            logInfo(log"Reserving executor ${MDC(LogKeys.EXECUTOR_ID, 
offers(i).executorId)} for " +
+              log"OOM retry of task ${MDC(TASK_INDEX, index)} in stage " + 
taskSet.taskSet.logId)
+          }
+      }
+    }
+
+    oomRetryReservation.filter(_.taskId.isEmpty).foreach { reservation =>
+      offers.indices.find(i => offers(i).executorId == 
reservation.executorId).foreach { i =>
+        launch(reservation.taskSet, reservation.index, i).foreach { tid =>
+          setOomRetryReservation(Some(reservation.copy(taskId = Some(tid))))
+        }
+      }
+    }
+
+    for {
+      taskSet <- taskSets
+      index <- taskSet.pendingOomRetries
+      if !taskSet.oomRetryNeedsIsolation(index)
+    } {
+      offers.indices.iterator.filter { i =>

Review Comment:
   The first-OOM pass now builds the idle offer set once, removes an executor 
after a launch, and stops when that set is empty. The pass also shares one 
pending-retry list.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +464,185 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)

Review Comment:
   Added tests that choose a reservation first, then apply a task-set or 
application-wide exclusion and verify that the retry moves to another executor.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -635,8 +853,16 @@ private[spark] class TaskSchedulerImpl(
       // value is -1
       val numBarrierSlotsAvailable = if (taskSet.isBarrier) {
         val rpId = taskSet.taskSet.resourceProfileId
-        val resAmounts = availableResources.map(_.resourceAddressAmount)
-        calculateAvailableSlots(this, conf, rpId, resourceProfileIds, 
availableCpus, resAmounts)
+        val profile = sc.resourceProfileManager.resourceProfileFromId(rpId)
+        val taskCpus = ResourceProfile.getTaskCpusOrDefaultForProfile(profile, 
conf)
+        shuffledOffers.indices.iterator
+          .filter(i => sc.resourceProfileManager.canBeScheduled(rpId, 
resourceProfileIds(i)))
+          .map { i =>
+            // Recovery may already have consumed whole or fractional custom 
resources.
+            val maxTasks = math.min(
+              ResourceProfile.numTasksBasedOnCores(availableCpus(i), 
taskCpus), taskSet.numTasks)
+            availableResources(i).availableTaskSlots(profile, maxTasks)

Review Comment:
   Agreed that zero CPUs already masks the reserved executor. The barrier pass 
also sees offers after recovery launches have consumed CPU and custom 
resources. The remaining GPU fractions can fit fewer tasks than the old address 
count suggests. I kept the address-aware count here so barrier admission uses 
the resources actually left in the round. It also fixes the pre-existing 
fragmentation case with the policy off.



##########
core/src/main/scala/org/apache/spark/scheduler/cluster/CoarseGrainedSchedulerBackend.scala:
##########
@@ -464,7 +464,15 @@ class CoarseGrainedSchedulerBackend(protected val 
scheduler: TaskSchedulerImpl,
                 s"${RPC_MESSAGE_MAX_SIZE.key} (%d bytes). Consider increasing 
" +
                 s"${RPC_MESSAGE_MAX_SIZE.key} or using broadcast variables for 
large values."
               msg = msg.format(task.taskId, task.index, 
serializedTask.limit(), maxRpcMessageSize)
-              taskSetMgr.abort(msg)
+              try {

Review Comment:
   Agreed that the running-task leak also exists with the policy disabled. For 
an isolated retry, an oversized launch is rejected before it reaches the 
executor, so no terminal update will arrive to release the reservation. The 
scheduler-side `KILLED` update clears both the running record and that 
reservation. I've kept the cleanup here for that path.



##########
core/src/main/scala/org/apache/spark/scheduler/ExecutorLossReason.scala:
##########
@@ -29,7 +30,10 @@ class ExecutorLossReason(val message: String) extends 
Serializable {
 
 private[spark]
 case class ExecutorExited(exitCode: Int, exitCausedByApp: Boolean, reason: 
String)
-  extends ExecutorLossReason(reason)
+  extends ExecutorLossReason(reason) {
+  private[spark] var isOutOfMemoryError: Boolean =

Review Comment:
   The YARN allocator now marks application-caused `KILLED_EXCEEDED_PMEM` exits 
as OOM. Tests cover physical-memory kills, virtual-memory kills, and containers 
the driver already released.



##########
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/scheduler/cluster/k8s/KubernetesExecutorBuilder.scala:
##########
@@ -88,13 +90,21 @@ private[spark] class KubernetesExecutorBuilder {
 
     // If using a template this will always get the resources from that and 
combine
     // them with any Spark conf or ResourceProfile resources.
-    features.foldLeft(spec) { case (spec, feature) =>
+    val resolved = features.foldLeft(spec) { case (spec, feature) =>
       val configuredPod = feature.configurePod(spec.pod)
       val addedResources = feature.getAdditionalKubernetesResources()
       KubernetesExecutorSpec(
         configuredPod,
         spec.executorKubernetesResources ++ addedResources)
     }
+    // Templates and custom feature steps can both choose the executor 
container's name.
+    val executorPod = resolved.pod
+    val annotatedPod = new PodBuilder(executorPod.pod)
+      .editOrNewMetadata()
+        .addToAnnotations(EXECUTOR_CONTAINER_NAME_ANNOTATION, 
executorPod.container.getName)

Review Comment:
   The annotation records the final executor container name after custom 
feature steps run. The typed retry classifier uses that identity to read the 
renamed executor's termination status and distinguish it from sidecar statuses. 
I've kept the annotation with that classifier.



##########
resource-managers/yarn/src/main/scala/org/apache/spark/deploy/yarn/YarnAllocator.scala:
##########
@@ -933,7 +933,11 @@ private[yarn] class YarnAllocator(
         } else {
           logInfo(containerExitReason)
         }
-        ExecutorExited(exitStatus, exitCausedByApp, 
containerExitReason.message)
+        val reason = ExecutorExited(exitStatus, exitCausedByApp, 
containerExitReason.message)
+        if (exitCausedByApp && exitStatus == 
ContainerExitStatus.KILLED_EXCEEDED_PMEM) {

Review Comment:
   I reproduced exit 143 with that hook in a local OpenJDK 21 probe. The catch 
block still ran in the probe, so it doesn't establish whether the task report 
reaches a YARN driver. The config docs now say that exit 143 alone is 
unclassified and recovery in this case depends on receiving a typed task 
failure.



##########
docs/configuration.md:
##########
@@ -3049,6 +3049,46 @@ Apart from these, the following properties are also 
available, and may be useful
   </td>
   <td>0.8.0</td>
 </tr>
+<tr>
+  <td><code>spark.scheduler.oomRetry.enabled</code></td>
+  <td>false</td>
+  <td>
+    Prefer eligible idle executors when retrying a task after an out-of-memory 
failure.
+    After the second and each subsequent OOM failure of the same task, Spark 
tries to reserve
+    one executor for its next attempt. It lets existing tasks finish, then 
runs the retry alone.
+    Spark releases the executor when the isolated attempt ends, including when 
it fails with OOM.
+    At most one executor per application is reserved. Other repeated OOM 
retries wait up to
+    <code>spark.scheduler.oomRetry.isolationTimeout</code> before falling back 
to ordinary placement.
+    Normal tasks retain their ordinary placement policy. OOM retries may 
ignore preferred
+    locations, but still respect exclusions, resource profiles, and custom 
resource requirements.
+    Task CPU requests, executor memory limits, and 
<code>spark.task.maxFailures</code> are unchanged.
+    Dynamic allocation counts the reserved executor separately from the 
remaining work, within
+    the configured executor limits, so its unused slots do not suppress 
requests for other tasks.
+    Barrier and pipelined stages are excluded, and OOM-affected tasks are not 
speculated.
+    Recognized failures include JVM/Spark OOM exceptions (including wrapped 
exceptions),
+    application-caused Spark executor exits with code 52, Kubernetes 
executor-container

Review Comment:
   Documented this in `8032eee1`. If Standalone processes the generic executor 
loss before the Master's exit status arrives, the later exit 52 cannot 
reclassify the tasks already failed by the first removal. A typed task failure 
can still reach the driver independently.



##########
core/src/main/scala/org/apache/spark/SparkContext.scala:
##########
@@ -726,10 +726,12 @@ class SparkContext(config: SparkConf) extends Logging {
       if (dynamicAllocationEnabled) {
         schedulerBackend match {
           case b: ExecutorAllocationClient =>
+            val taskScheduler = _taskScheduler
             Some(new ExecutorAllocationManager(
               schedulerBackend.asInstanceOf[ExecutorAllocationClient], 
listenerBus, _conf,
               cleaner = cleaner, resourceProfileManager = 
resourceProfileManager,
-              reliableShuffleStorage = 
_shuffleDriverComponents.supportsReliableStorage()))
+              reliableShuffleStorage = 
_shuffleDriverComponents.supportsReliableStorage(),
+              oomRetryReservationInfo = () => 
taskScheduler.oomRetryReservationInfo))

Review Comment:
   Added a test that creates the allocation manager through a real 
`SparkContext` and verifies that a live scheduler reservation raises the 
executor target from one to two.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +464,185 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)
+              } && reservation.taskSet.canRunOomRetry(
+                reservation.index, reservation.executorId, host)
+            } && reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+      }
+    })
+    hadReservation && oomRetryReservation.isEmpty
+  }
+
+  /**
+   * Give OOM retries idle capacity before ordinary placement. Repeated OOMs 
reserve at most one
+   * executor across offer rounds, allowing existing tasks to drain without 
backfilling it. Only
+   * this recovery pass ignores locality preferences; resource requirements 
and exclusions remain
+   * mandatory. A bounded wait in TaskSetManager makes an unavailable 
reservation fall back to
+   * ordinary scheduling instead of turning an OOM into an indefinitely 
pending retry.
+   */
+  private def scheduleOomRetries(
+      taskSets: ArrayBuffer[TaskSetManager],
+      offers: IndexedSeq[WorkerOffer],
+      availableCpus: Array[BigDecimal],
+      availableResources: Array[ExecutorResourcesAmounts],
+      tasks: IndexedSeq[ArrayBuffer[TaskDescription]]): Set[TaskSetManager] = {
+    refreshOomRetryReservation()
+    val launchedTaskSets = new HashSet[TaskSetManager]
+    def taskCpusFor(taskSet: TaskSetManager): BigDecimal = {
+      val profile = sc.resourceProfileManager
+        .resourceProfileFromId(taskSet.taskSet.resourceProfileId)
+      ResourceProfile.getTaskCpusOrDefaultForProfile(profile, conf)
+    }
+
+    // A compatible profile does not guarantee that every executor has enough 
total resources.
+    // Once a reserved executor is idle, its offer tells us whether the retry 
can actually fit.
+    setOomRetryReservation(oomRetryReservation.filterNot { reservation =>
+      reservation.taskId.isEmpty && offers.indices.exists { i =>
+        offers(i).executorId == reservation.executorId &&
+          !isExecutorBusy(reservation.executorId) &&
+          resourcesMeetTaskRequirements(
+            reservation.taskSet, taskCpusFor(reservation.taskSet),
+            availableCpus(i), availableResources(i)).isEmpty
+      }
+    })
+
+    def eligible(taskSet: TaskSetManager, index: Int, i: Int): Boolean = {
+      val offer = offers(i)
+      isExecutorAlive(offer.executorId) &&
+        sc.resourceProfileManager.canBeScheduled(
+          taskSet.taskSet.resourceProfileId, offer.resourceProfileId) &&
+        taskSet.canRunOomRetry(index, offer.executorId, offer.host)
+    }
+
+    def launch(taskSet: TaskSetManager, index: Int, i: Int): Option[Long] = {
+      val offer = offers(i)
+      if (!eligible(taskSet, index, i) || isExecutorBusy(offer.executorId)) {
+        return None
+      }
+      resourcesMeetTaskRequirements(
+        taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i)).flatMap {
+        assignments =>
+          val taskCpus = taskCpusFor(taskSet)
+          try {
+            taskSet.resourceOfferOomRetry(
+              index, offer.executorId, offer.host, taskCpus, assignments)
+              .map { task =>
+                tasks(i) += task
+                addRunningTask(task.taskId, offer.executorId, taskSet)
+                launchedTaskSets += taskSet
+                availableCpus(i) -= task.cpus
+                availableResources(i).acquire(task.resources)
+                task.taskId
+              }
+          } catch {
+            case e: TaskNotSerializableException =>
+              // prepareLaunchingTask already aborts the task set on 
serialization failure.
+              logError("Failed to serialize an OOM retry", e)
+              None
+          }
+      }
+    }
+
+    if (oomRetryReservation.isEmpty) {
+      for {
+        taskSet <- taskSets
+        index <- taskSet.pendingOomRetries
+        if oomRetryReservation.isEmpty && taskSet.oomRetryNeedsIsolation(index)
+      } {
+        val candidates = offers.indices.filter { i =>
+          eligible(taskSet, index, i) &&
+            (isExecutorBusy(offers(i).executorId) ||
+              resourcesMeetTaskRequirements(
+                taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i))
+                .isDefined)
+        }
+        // A busy executor may currently offer no CPUs or custom resources. 
Check its profile
+        // now and its actual free resources again after it drains, before 
launching anything.
+        candidates.sortBy(i => 
executorIdToRunningTaskIds(offers(i).executorId).size)
+          .headOption.foreach { i =>
+            setOomRetryReservation(Some(
+              OomRetryReservation(taskSet, index, offers(i).executorId)))
+            logInfo(log"Reserving executor ${MDC(LogKeys.EXECUTOR_ID, 
offers(i).executorId)} for " +
+              log"OOM retry of task ${MDC(TASK_INDEX, index)} in stage " + 
taskSet.taskSet.logId)
+          }
+      }
+    }
+
+    oomRetryReservation.filter(_.taskId.isEmpty).foreach { reservation =>
+      offers.indices.find(i => offers(i).executorId == 
reservation.executorId).foreach { i =>
+        launch(reservation.taskSet, reservation.index, i).foreach { tid =>
+          setOomRetryReservation(Some(reservation.copy(taskId = Some(tid))))
+        }
+      }
+    }
+
+    for {
+      taskSet <- taskSets
+      index <- taskSet.pendingOomRetries
+      if !taskSet.oomRetryNeedsIsolation(index)
+    } {
+      offers.indices.iterator.filter { i =>
+        !isExecutorBusy(offers(i).executorId) &&
+          !oomRetryReservation.exists(_.executorId == offers(i).executorId)
+      }.exists(i => launch(taskSet, index, i).isDefined)
+    }
+
+    // Capture deadlines before refreshing and masking: if one expires during 
this pass, either
+    // its reservation is released below or the captured delay still 
guarantees another offer.
+    val nextDelay = taskSets.iterator.flatMap { taskSet =>
+      
taskSet.pendingOomRetries.iterator.map(taskSet.oomRetryIsolationTimeRemaining)
+    }.filter(_ > 0).reduceOption(_ min _)
+
+    // A failed launch may have aborted its task set. Missing partial offers 
must not release an
+    // otherwise valid reservation. Mask it for every task set, including 
barrier slot counting.
+    refreshOomRetryReservation()
+    oomRetryReservation.foreach { reservation =>
+      offers.indices.filter(i => offers(i).executorId == 
reservation.executorId)
+        .foreach { i =>
+          availableCpus(i) = 0
+          availableResources(i) = ExecutorResourcesAmounts.empty
+        }
+    }
+
+    // Local backends do not periodically revive offers. Keep one wakeup for 
the earliest
+    // pending deadline, including retries waiting behind another task's 
reservation.
+    oomRetryWakeup.foreach(_.cancel(false))
+    oomRetryWakeup = nextDelay.map { delay =>
+      starvationTimer.schedule(new Runnable {

Review Comment:
   `stop()` now sets the stopped flag under the scheduler lock and cancels the 
wakeup. Late offers skip the OOM retry pass. The regression test delivers an 
offer after stop.



##########
core/src/main/scala/org/apache/spark/ExecutorAllocationManager.scala:
##########
@@ -1080,6 +1122,32 @@ private[spark] class ExecutorAllocationManager(
       }.sum
     }
 
+    /** Count only reserved tasks that also contribute to this listener's 
demand. */

Review Comment:
   The helper now documents both return values, including when pending 
speculation needs a separate executor.



##########
core/src/main/scala/org/apache/spark/ExecutorAllocationManager.scala:
##########
@@ -791,6 +806,9 @@ private[spark] class ExecutorAllocationManager(
     // Number of running tasks per stageAttempt including speculative tasks.
     // Should be 0 when no stages are active.
     private val stageAttemptToNumRunningTask = new 
mutable.HashMap[StageAttempt, Int]
+    // Used only for OOM recovery. Keep coverage in the same event domain as 
allocation demand.
+    private val executorToRunningTasks =

Review Comment:
   `tasksPerExecutor - 1` bounds the slots withheld on the reserved executor. 
At a lower executor allocation ratio, a target that includes the reserved 
executor can leave more queued tasks waiting. Speculative copies can also 
require a distinct executor. The bookkeeping lets the allocator size the 
remaining work independently of the reserved executor, so I've kept it in this 
revision.



##########
core/src/main/scala/org/apache/spark/scheduler/ExecutorLossReason.scala:
##########
@@ -29,7 +30,10 @@ class ExecutorLossReason(val message: String) extends 
Serializable {
 
 private[spark]
 case class ExecutorExited(exitCode: Int, exitCausedByApp: Boolean, reason: 
String)
-  extends ExecutorLossReason(reason)
+  extends ExecutorLossReason(reason) {
+  private[spark] var isOutOfMemoryError: Boolean =

Review Comment:
   Agreed that a constructor field would make `copy` and equality preserve the 
override. I didn't find a production copy path that drops it today. The 
inherited `toString` renders the loss message, so printing the flag would also 
need an explicit change.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSetManager.scala:
##########
@@ -1005,6 +1094,17 @@ private[spark] class TaskSetManager(
     info.markFinished(state, clock.getTimeMillis())
     val index = info.index
     copiesRunning(index) -= 1
+    val isOom = reason match {

Review Comment:
   Yes, a neighboring task can lose speculation and compete for the reservation 
after another OOM-classified executor loss. The task failure report and the 
executor loss can reach the driver in either order, and a container kill may 
provide no task-level report. Skipping attribution when a report is present 
would make the decision depend on delivery order unless we correlate the two 
reliably. The config docs describe the current rule. A shared predicate for the 
scheduler and allocation manager would make sense as a cleanup.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +465,192 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)
+              } && reservation.taskSet.canRunOomRetry(
+                reservation.index, reservation.executorId, host)
+            } && reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+      }
+    })
+    hadReservation && oomRetryReservation.isEmpty
+  }
+
+  /**
+   * Give OOM retries idle capacity before ordinary placement. Repeated OOMs 
reserve at most one
+   * executor across offer rounds, allowing existing tasks to drain without 
backfilling it. Only
+   * this recovery pass ignores locality preferences; resource requirements 
and exclusions remain
+   * mandatory. A bounded wait in TaskSetManager makes an unavailable 
reservation fall back to
+   * ordinary scheduling instead of turning an OOM into an indefinitely 
pending retry.
+   */
+  private def scheduleOomRetries(
+      taskSets: ArrayBuffer[TaskSetManager],
+      offers: IndexedSeq[WorkerOffer],
+      isAllFreeResources: Boolean,
+      availableCpus: Array[BigDecimal],
+      availableResources: Array[ExecutorResourcesAmounts],
+      tasks: IndexedSeq[ArrayBuffer[TaskDescription]]): Set[TaskSetManager] = {
+    refreshOomRetryReservation()
+    val launchedTaskSets = new HashSet[TaskSetManager]
+    def taskCpusFor(taskSet: TaskSetManager): BigDecimal = {
+      val profile = sc.resourceProfileManager
+        .resourceProfileFromId(taskSet.taskSet.resourceProfileId)
+      ResourceProfile.getTaskCpusOrDefaultForProfile(profile, conf)
+    }
+
+    // A compatible profile does not guarantee that every executor has enough 
total resources.
+    // Once a reserved executor is idle, its offer tells us whether the retry 
can actually fit.
+    setOomRetryReservation(oomRetryReservation.filterNot { reservation =>
+      reservation.taskId.isEmpty && offers.indices.exists { i =>
+        offers(i).executorId == reservation.executorId &&
+          !isExecutorBusy(reservation.executorId) &&
+          resourcesMeetTaskRequirements(
+            reservation.taskSet, taskCpusFor(reservation.taskSet),
+            availableCpus(i), availableResources(i)).isEmpty
+      }
+    })
+
+    def eligible(taskSet: TaskSetManager, index: Int, i: Int): Boolean = {
+      val offer = offers(i)
+      isExecutorAlive(offer.executorId) &&
+        sc.resourceProfileManager.canBeScheduled(
+          taskSet.taskSet.resourceProfileId, offer.resourceProfileId) &&
+        taskSet.canRunOomRetry(index, offer.executorId, offer.host)
+    }
+
+    def launch(taskSet: TaskSetManager, index: Int, i: Int): Option[Long] = {
+      val offer = offers(i)
+      if (!eligible(taskSet, index, i) || isExecutorBusy(offer.executorId)) {
+        return None
+      }
+      resourcesMeetTaskRequirements(
+        taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i)).flatMap {
+        assignments =>
+          val taskCpus = taskCpusFor(taskSet)
+          try {
+            taskSet.resourceOfferOomRetry(
+              index, offer.executorId, offer.host, taskCpus, assignments)
+              .map { task =>
+                tasks(i) += task
+                addRunningTask(task.taskId, offer.executorId, taskSet)
+                launchedTaskSets += taskSet
+                availableCpus(i) -= task.cpus
+                availableResources(i).acquire(task.resources)
+                task.taskId
+              }
+          } catch {
+            case e: TaskNotSerializableException =>
+              // prepareLaunchingTask already aborts the task set on 
serialization failure.
+              logError("Failed to serialize an OOM retry", e)
+              None
+          }
+      }
+    }
+
+    val pendingRetries = taskSets.flatMap { taskSet =>
+      taskSet.pendingOomRetries.map(index => (taskSet, index))
+    }
+    // A partial round may omit a better executor. Wait for a full round to 
choose a new
+    // reservation, but continue draining and launching an existing one on 
partial offers.
+    if (isAllFreeResources && oomRetryReservation.isEmpty) {
+      for {
+        (taskSet, index) <- pendingRetries.iterator.takeWhile(_ => 
oomRetryReservation.isEmpty)
+        if taskSet.oomRetryNeedsIsolation(index)
+      } {
+        val candidates = offers.indices.filter { i =>
+          eligible(taskSet, index, i) &&
+            (isExecutorBusy(offers(i).executorId) ||
+              resourcesMeetTaskRequirements(
+                taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i))
+                .isDefined)
+        }
+        // A busy executor may currently offer no CPUs or custom resources. 
Check its profile
+        // now and its actual free resources again after it drains, before 
launching anything.
+        candidates.sortBy(i => 
executorIdToRunningTaskIds(offers(i).executorId).size)
+          .headOption.foreach { i =>
+            setOomRetryReservation(Some(
+              OomRetryReservation(taskSet, index, offers(i).executorId)))
+            logInfo(log"Reserving executor ${MDC(LogKeys.EXECUTOR_ID, 
offers(i).executorId)} for " +
+              log"OOM retry of task ${MDC(TASK_INDEX, index)} in stage " + 
taskSet.taskSet.logId)
+          }
+      }
+    }
+
+    oomRetryReservation.filter { reservation =>
+      reservation.taskId.isEmpty && 
reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+    }.foreach { reservation =>
+      offers.indices.find(i => offers(i).executorId == 
reservation.executorId).foreach { i =>
+        launch(reservation.taskSet, reservation.index, i).foreach { tid =>
+          setOomRetryReservation(Some(reservation.copy(taskId = Some(tid))))
+        }
+      }
+    }
+
+    if (pendingRetries.nonEmpty) {
+      val idleOffers = 
mutable.LinkedHashSet.from(offers.indices.iterator.filter { i =>

Review Comment:
   Yes, the ordinary pass can fill the remaining slots in the same round. The 
first retry gets a chance to start on an executor that has no work running yet, 
and that placement bypasses the locality wait. Only a repeated-OOM retry 
reserves the executor. The tests cover placement, and I don't have workload 
data quantifying the benefit of the first step.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -761,7 +994,6 @@ private[spark] class TaskSchedulerImpl(
                 log"to get rid of this error."
               logWarning(logMsg)
               taskSet.abort(logMsg.message)

Review Comment:
   Agreed that this changes the legacy abort path with the policy off. The 
barrier stage still aborts. Returning the rest of the offer round preserves 
launches already registered for other task sets, including OOM retries. I 
removed the unused error helper and error condition in `8032eee1`. The abort 
fix is still part of this revision.



##########
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/scheduler/cluster/k8s/KubernetesClusterSchedulerBackend.scala:
##########
@@ -76,8 +76,9 @@ private[spark] class KubernetesClusterSchedulerBackend(
 
   private[k8s] def doRemoveExecutor(executorId: String, reason: 
ExecutorLossReason): Unit = {
     removeExecutor(executorId, reason)
-    podAllocator match {
-      case allocator: ExecutorPodsAllocator if reason.message.contains("OOM") 
=>
+    (podAllocator, reason) match {
+      case (allocator: ExecutorPodsAllocator, exited: ExecutorExited)
+          if exited.exitCausedByApp && exited.isOutOfMemoryError =>

Review Comment:
   Peter is right that code 52 already matched the old message check. 
`8032eee1` restores that check for the allocator, including the prior behavior 
for 137 and sidecar text. The opt-in task retry still uses typed executor OOM 
attribution. The Kubernetes suite checks the restored behavior with the retry 
policy off.



##########
core/src/main/scala/org/apache/spark/ExecutorAllocationManager.scala:
##########
@@ -925,7 +953,15 @@ private[spark] class ExecutorAllocationManager(
       val stageAttempt = StageAttempt(stageId, stageAttemptId)
       val taskIndex = taskEnd.taskInfo.index
       allocationManager.synchronized {
-        if (stageAttemptToNumRunningTask.contains(stageAttempt)) {
+        executorToRunningTasks.get(taskEnd.taskInfo.executorId).foreach { 
runningTasks =>
+          runningTasks.remove(taskEnd.taskInfo.taskId)
+          if (runningTasks.isEmpty) {
+            executorToRunningTasks.remove(taskEnd.taskInfo.executorId)
+          }
+        }
+        // Resubmitted reports lost output from a task that already finished, 
not another exit.
+        if (taskEnd.reason != Resubmitted &&

Review Comment:
   Agreed that this predates OOM retry and can be backported separately. The 
original completion already decrements the running count, and `Resubmitted` 
only reports lost output. This revision keeps the correction alongside the 
reservation-aware demand changes, which also use that running count.



##########
core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala:
##########
@@ -439,6 +465,192 @@ private[spark] class TaskSchedulerImpl(
     logInfo(log"Removed TaskSet " + manager.taskSet.logId +
       log" whose tasks have all completed, from pool ${MDC(LogKeys.POOL_NAME, 
manager.parent.name)}"
     )
+    if (releasedOomReservation) {
+      // A cancelled pending retry has no task exit to wake work held behind 
its reservation.
+      backend.reviveOffers()
+    }
+  }
+
+  private def setOomRetryReservation(reservation: 
Option[OomRetryReservation]): Unit = {
+    oomRetryReservation = reservation
+    // Publish an immutable snapshot without calling into the allocation 
manager: it can already
+    // hold its lock while acquiring the scheduler lock through the backend.
+    oomRetryReservationSnapshot = reservation.map { r =>
+      val taskSet = r.taskSet.taskSet
+      OomRetryReservationInfo(taskSet.resourceProfileId, r.executorId,
+        taskSet.stageId, taskSet.stageAttemptId, r.index)
+    }
+  }
+
+  private def refreshOomRetryReservation(): Boolean = {
+    val hadReservation = oomRetryReservation.nonEmpty
+    setOomRetryReservation(oomRetryReservation.filter { reservation =>
+      reservation.taskId match {
+        // Cancellation or another attempt's success can precede the task's 
exit. Keep its
+        // executor isolated until the terminal status update releases the 
running task.
+        case Some(tid) => 
taskIdToExecutorId.get(tid).contains(reservation.executorId)
+        case None =>
+          isExecutorAlive(reservation.executorId) &&
+            executorIdToHost.get(reservation.executorId).exists { host =>
+              !healthTrackerOpt.exists { tracker =>
+                tracker.isExecutorExcluded(reservation.executorId) || 
tracker.isNodeExcluded(host)
+              } && reservation.taskSet.canRunOomRetry(
+                reservation.index, reservation.executorId, host)
+            } && reservation.taskSet.oomRetryNeedsIsolation(reservation.index)
+      }
+    })
+    hadReservation && oomRetryReservation.isEmpty
+  }
+
+  /**
+   * Give OOM retries idle capacity before ordinary placement. Repeated OOMs 
reserve at most one
+   * executor across offer rounds, allowing existing tasks to drain without 
backfilling it. Only
+   * this recovery pass ignores locality preferences; resource requirements 
and exclusions remain
+   * mandatory. A bounded wait in TaskSetManager makes an unavailable 
reservation fall back to
+   * ordinary scheduling instead of turning an OOM into an indefinitely 
pending retry.
+   */
+  private def scheduleOomRetries(
+      taskSets: ArrayBuffer[TaskSetManager],
+      offers: IndexedSeq[WorkerOffer],
+      isAllFreeResources: Boolean,
+      availableCpus: Array[BigDecimal],
+      availableResources: Array[ExecutorResourcesAmounts],
+      tasks: IndexedSeq[ArrayBuffer[TaskDescription]]): Set[TaskSetManager] = {
+    refreshOomRetryReservation()
+    val launchedTaskSets = new HashSet[TaskSetManager]
+    def taskCpusFor(taskSet: TaskSetManager): BigDecimal = {
+      val profile = sc.resourceProfileManager
+        .resourceProfileFromId(taskSet.taskSet.resourceProfileId)
+      ResourceProfile.getTaskCpusOrDefaultForProfile(profile, conf)
+    }
+
+    // A compatible profile does not guarantee that every executor has enough 
total resources.
+    // Once a reserved executor is idle, its offer tells us whether the retry 
can actually fit.
+    setOomRetryReservation(oomRetryReservation.filterNot { reservation =>
+      reservation.taskId.isEmpty && offers.indices.exists { i =>
+        offers(i).executorId == reservation.executorId &&
+          !isExecutorBusy(reservation.executorId) &&
+          resourcesMeetTaskRequirements(
+            reservation.taskSet, taskCpusFor(reservation.taskSet),
+            availableCpus(i), availableResources(i)).isEmpty
+      }
+    })
+
+    def eligible(taskSet: TaskSetManager, index: Int, i: Int): Boolean = {
+      val offer = offers(i)
+      isExecutorAlive(offer.executorId) &&
+        sc.resourceProfileManager.canBeScheduled(
+          taskSet.taskSet.resourceProfileId, offer.resourceProfileId) &&
+        taskSet.canRunOomRetry(index, offer.executorId, offer.host)
+    }
+
+    def launch(taskSet: TaskSetManager, index: Int, i: Int): Option[Long] = {
+      val offer = offers(i)
+      if (!eligible(taskSet, index, i) || isExecutorBusy(offer.executorId)) {
+        return None
+      }
+      resourcesMeetTaskRequirements(
+        taskSet, taskCpusFor(taskSet), availableCpus(i), 
availableResources(i)).flatMap {
+        assignments =>
+          val taskCpus = taskCpusFor(taskSet)
+          try {
+            taskSet.resourceOfferOomRetry(
+              index, offer.executorId, offer.host, taskCpus, assignments)
+              .map { task =>
+                tasks(i) += task
+                addRunningTask(task.taskId, offer.executorId, taskSet)
+                launchedTaskSets += taskSet
+                availableCpus(i) -= task.cpus
+                availableResources(i).acquire(task.resources)
+                task.taskId
+              }
+          } catch {
+            case e: TaskNotSerializableException =>
+              // prepareLaunchingTask already aborts the task set on 
serialization failure.
+              logError("Failed to serialize an OOM retry", e)
+              None
+          }
+      }
+    }
+
+    val pendingRetries = taskSets.flatMap { taskSet =>
+      taskSet.pendingOomRetries.map(index => (taskSet, index))
+    }
+    // A partial round may omit a better executor. Wait for a full round to 
choose a new
+    // reservation, but continue draining and launching an existing one on 
partial offers.
+    if (isAllFreeResources && oomRetryReservation.isEmpty) {

Review Comment:
   Thanks for the probe. In `8032eee1`, a full offer round can launch the 
pending retry on an eligible idle peer that fits while the reserved executor is 
still draining. It keeps the original deadline. A partial offer still only 
launches on the reserved executor. I added a regression that covers the handoff 
and verifies that the original executor can take ordinary work in the same 
round.



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