spark-test commented on code in PR #58714:
URL: https://github.com/apache/spark/pull/58714#discussion_r4507964254


##########
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:
   **Nit (P3):** `stop()` cancels `oomRetryWakeup` inside its synchronized 
block and then calls `ThreadUtils.shutdown(starvationTimer)`. Nothing prevents 
a later offer round from reaching this line and scheduling a new wakeup. In 
local mode, `LocalSchedulerBackend.stop` only sends an asynchronous 
`ask(StopExecutor)`, and the local endpoint keeps calling `resourceOffers` for 
later `StatusUpdate` and `ReviveOffers` messages. `DAGScheduler` doesn't cancel 
stages when it stops, so a retry that is waiting for isolation stays pending.
   
   If such a round runs before the timer is shut down, it queues a delayed 
wakeup, and `ThreadUtils.shutdown` then blocks `SparkContext.stop` for up to 
its 30s grace period: once the executor is shut down, `shutdownNow` is never 
reached, and queued delayed tasks still run. If the round runs after shutdown, 
`schedule` throws `RejectedExecutionException` out of `resourceOffers`, after 
the round may already have registered launches with `addRunningTask`. This only 
affects shutdown with the policy enabled; running applications are unaffected. 
A stopped flag set inside that synchronized block and checked here, or 
tolerating `RejectedExecutionException`, would close it.
   
   **Verification:**
   - **Regression:** With a retry waiting for isolation, stop the scheduler and 
then run an offer round. No wakeup is scheduled, no exception escapes the offer 
round, and the timer shutdown does not wait for a delayed wakeup.
   - **Behavior:** Before stop, the wakeup is still scheduled for the earliest 
pending isolation deadline.



##########
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:
   **Non-blocking (P2):** This candidate list only covers the offers in the 
current `resourceOffers` call, and `scheduleOomRetries` can't tell whether that 
call is a complete round. `CoarseGrainedSchedulerBackend` answers every 
finished-task `StatusUpdate` with `makeOffers(executorId)`, a single-executor 
round (`isAllFreeResources = false`). The `ReviveOffers` that 
`handleFailedTask` sends after the second OOM queues behind any status updates 
already in the driver endpoint's inbox.
   
   Take executors A (three running tasks) and B (idle), and suppose a status 
update from A is processed first. That round sees only A, which is eligible and 
busy, so A is reserved. The following full round skips selection because a 
reservation already exists, masks A's free slots, and hands B to ordinary work. 
The retry then waits for A to drain. If A's tasks outlast 
`spark.scheduler.oomRetry.isolationTimeout`, the retry falls back to ordinary 
placement and never runs isolated. This only happens when the policy is 
enabled, and results are unaffected. The least-busy test only uses complete 
offers, so it doesn't catch this.
   
   **Recommended change:** Choose a new isolation reservation only in a 
complete offer round. Pass resourceOffers' isAllFreeResources flag into the 
recovery pass and skip creating a reservation in a single-executor partial 
round. Partial rounds still refresh and mask an existing reservation, and the 
reserved executor's own partial offer still launches the retry once that 
executor has drained.
   
   **Why this works:** A complete round offers every active executor (the local 
backend always offers its only executor), so ranking candidates there makes the 
idle-or-fewest-running-tasks preference independent of which status update is 
processed first. The reservation keeps its current lifecycle: partial rounds 
refresh and mask it, the retry launches as soon as its executor is idle, and a 
launched isolated attempt never moves.
   
   **Scope:** Change when the OOM recovery pass creates the executor 
reservation, based on whether the current offer round includes every executor.
   
   **Compatibility:** Once the retry launches in isolation, its executor stays 
reserved and masked until the attempt exits, as it does today.
   
   **Risks:** Deferring new reservations to complete rounds can postpone 
isolation by up to one revive interval after the second OOM, while the 
isolation deadline still counts from that OOM. The delay applies only when 
spark.scheduler.oomRetry.enabled is true, so disabling the policy removes it.
   
   **Constraints:** A launched isolated attempt keeps its executor until the 
attempt exits. Partial rounds must still refresh, launch, and mask an existing 
reservation.
   
   **Exclusions:**
   - The first-OOM idle-executor preference stays best-effort per round, as the 
PR description declares.
   - Moving a pending reservation to another executor that becomes idle while 
the reserved one is still draining. The PR description does not promise this, 
and it would be a separate policy change.
   
   **Success:** When a busy executor is offered alone in a partial round and an 
idle compatible executor is registered, a retry that needs isolation is not 
reserved on the busy executor, and the next complete round reserves the idle 
executor and launches the retry there. An existing reservation stays masked in 
partial offers while its executor drains, and its retry launches from that 
executor's own partial offer once the executor is idle.
   
   **Verification:**
   - **Regression:** Record a second OOM, then deliver a single-executor 
partial offer from a busy executor followed by a complete round that includes 
an idle compatible executor. Check that the retry is reserved and launched on 
the idle executor and that the busy executor's free slots are not withheld.
   - **Behavior:** In complete rounds, reservation selection still prefers an 
idle executor and otherwise the compatible executor with the fewest running 
tasks. An existing reservation stays masked in partial offers of its executor 
while that executor drains, and its retry launches from that executor's partial 
offer once it is idle.
   - **Compatibility:** With the policy disabled, offer handling and task 
placement are unchanged.



##########
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:
   **Non-blocking (P2):** This default only marks an app-caused exit with code 
52. On YARN, `YarnAllocator.processCompletedContainers` reports a container 
killed for exceeding its memory limit as `ExecutorExited(-104, exitCausedByApp 
= true)` for physical memory, or `-103` for virtual memory. This PR doesn't 
touch that producer, so the flag stays false, and `TaskSetManager.executorLost` 
copies false into every running task's `ExecutorLostFailure`.
   
   With `spark.scheduler.oomRetry.enabled=true` on YARN, a task whose off-heap 
or native memory pushes its container over the limit therefore gets neither the 
idle-executor preference nor isolation. It can be retried into the same 
contention until `spark.task.maxFailures`, just as before this PR, while the 
equivalent Kubernetes executor-container `OOMKilled` termination does engage 
recovery. The event log also omits the OOM flag for these failures.
   
   **Recommended change:** Classify YARN executor-container physical-memory 
kills as OOM where YARN reports them: when the YARN allocator builds the 
executor-exit reason for a container killed for exceeding physical memory, set 
its OOM flag, mirroring the Kubernetes OOMKilled classification. Leave 
virtual-memory kills unclassified unless you decide that they indicate memory 
contention. Add YARN allocator tests, and list YARN physical-memory kills among 
the recognized signals in the configuration docs.
   
   **Why this works:** The task set manager already copies the executor-exit 
OOM flag into every running task's failure when the exit is app-caused. Setting 
the flag at the YARN producer therefore gives these failures the same recovery, 
speculation revocation, allocation demand, and event-log flag that Kubernetes 
OOMKilled terminations get.
   
   **Scope:** Extend executor-termination OOM classification to YARN 
physical-memory container kills and document it.
   
   **Compatibility:** Exit-code-52 and Kubernetes OOMKilled classification are 
unchanged.
   
   **Risks:** Treating virtual-memory kills as OOM could trigger isolation for 
kills caused by virtual address-space accounting rather than memory contention, 
which isolation cannot fix.
   
   **Constraints:** Only app-caused memory-limit kills may be classified. 
Preempted and explicitly released containers must stay unclassified.
   
   **Exclusions:**
   - Classifying YARN virtual-memory kills, which awaits an explicit decision.
   
   **Success:** With the policy enabled on YARN, a task lost when its executor 
container is killed for exceeding physical memory is recorded as an OOM failure 
and gets the same recovery as a Kubernetes OOMKilled termination. Preempted, 
released, and other non-memory container exits remain non-OOM.
   
   **Verification:**
   - **Behavior:** A completed YARN container reported as killed for exceeding 
physical memory yields an app-caused executor-exit reason with its OOM flag 
set, and the flag is still set after the reason reaches the driver.
   - **Regression:** Preempted, released, and other non-memory container exit 
statuses still yield a non-OOM reason, and virtual-memory kills follow the 
documented decision.
   - **Inspection:** The configuration documentation lists YARN physical-memory 
kills among the recognized OOM signals.



##########
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:
   **Nit (P3):** For every pending retry that doesn't need isolation, this 
rescans all offers, calling the synchronized `isExecutorBusy` and the 
reservation check, to find an idle executor. Within one pass executors only get 
busier, because launches add running tasks and nothing removes them. So once no 
offer is idle, every later retry's scan is wasted. `pendingOomRetries` also 
filters and sorts all OOM-affected partitions, and this pass calls it three 
times per task set per round: for reservation selection, here, and for the 
deadline.
   
   After an OOM burst on a saturated cluster, each full round does pending 
retries x offers work under the scheduler lock and launches nothing. For 
example, several executors might exit with an OOM signal and have all their 
running tasks charged. `handleFailedTask` triggers another full round for every 
failed task, so status updates and launches for every job wait on this. It only 
applies with the policy enabled. You get the same decisions by collecting the 
idle, unreserved offer indices once per pass, removing an index when a retry 
launches there, stopping when none remain, and computing each task set's 
pending retries once per round.
   
   **Verification:**
   - **Compatibility:** Idle-executor preference, busy fallback, reservation 
selection, masking, and deadline wakeups produce the same outcomes as before 
the optimization.
   - **Inspection:** The pass computes the idle unreserved offer set once, 
iterates only that set for first-OOM retries, and evaluates each task set's 
pending OOM retries at most once per round.



##########
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:
   **Nit (P3):** No test reaches this argument. The new 
`ExecutorAllocationManager` parameter defaults to `() => None`, and every 
reservation-aware sizing test in `ExecutorAllocationManagerSuite` injects its 
own supplier through `createManager`. The one `TaskSchedulerImplSuite` test 
that sets `spark.dynamicAllocation.enabled` runs on `local[8]` without 
`spark.dynamicAllocation.testing`, so `Utils.isDynamicAllocationEnabled` is 
false there, and that test drives its own `TaskSchedulerImpl` rather than 
`sc`'s.
   
   If this line were dropped or bound to the wrong scheduler, everything would 
still compile and pass. Meanwhile dynamic allocation would size demand as if no 
executor were reserved, so the reserved executor's idle slots would hide 
demand, which is what this PR says it prevents. A SparkContext-backed test 
would pin it, for example on `local-cluster` like the existing "initialize 
dynamic allocation in SparkContext" test, observing a reservation through 
`sc.executorAllocationManager`.
   
   **Verification:**
   - **Regression:** With an allocation manager built by SparkContext and an 
active reservation in the context's task scheduler, executor demand counts the 
reserved executor separately, and the check fails if the supplier is dropped or 
mis-bound.



##########
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:
   **Nit (P3):** This exclusion check, and the `canRunOomRetry` call next to 
it, have no failing test. "OOM retries preserve exclusions, resource profiles 
and custom resource requirements" stubs the excludelist mocks before the first 
isolation offer creates the reservation, so it only checks selection-time 
filtering. The other recovery tests cover decommissioning, executor loss, 
cancellation, partition completion, timeout, and the drained-but-cannot-fit 
case, but never an exclusion that arrives after a reservation exists.
   
   If either check were dropped, every suite would still pass. A pending 
reservation on an executor newly excluded for the retry's task set would then 
stay masked until `isolationTimeout`. An application-excluded executor, which 
is filtered out of offers, would hold the only reservation until then. 
`setupSchedulerWithMockTaskSetExcludelist` already exposes both mocks for a 
test that excludes the reserved executor after it is chosen.
   
   **Verification:**
   - **Regression:** After a pending reservation exists, excluding its executor 
application-wide, or for the retry's task set, releases the reservation in the 
next complete offer round, frees that executor's capacity, and lets another 
eligible executor be reserved.



##########
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:
   **Nit (P3):** This loop runs for every compatible offer of every barrier 
task set in every `resourceOffers` round when the profile requests custom 
resources (typically GPU stages), whether or not 
`spark.scheduler.oomRetry.enabled` is set. Each call copies the resource maps. 
Each simulated slot then re-filters the profile's resources, sorts every 
address list, builds new maps, and acquires them, all under the scheduler lock. 
`calculateAvailableSlots` used to do a few lookups per offer.
   
   The simulation isn't needed for the corrected count, because 
`assignAddressesCustomResources` handles each resource independently and 
greedily:
   - A whole-number request `a` only takes addresses that still hold a whole 
resource, so it fits `floor(wholeAddresses / a)` times.
   - A fractional request takes one share from the first address that still has 
one, so it fits `sum(floor(amount / share))` times over the addresses.
   
   The minimum across the requested resources (0 if one is missing), capped at 
`maxTasks`, gives the same count without copying or sorting, and keeps the 
fragmentation and multi-resource handling this PR adds.
   
   **Verification:**
   - **Compatibility:** The closed form equals the assignment-based count 
across whole and fractional requests, fragmented addresses, several requested 
resources, a missing resource, and the maxTasks cap.
   - **Behavior:** Barrier scheduling with custom resources consumed earlier in 
the round, or with a reserved executor, launches or skips the barrier stage 
exactly as before.



##########
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:
   **Nit (P3):** This only describes the first element of the `(Int, Boolean)` 
result. The Boolean is true when some pending speculative task of the 
reservation's resource profile has its original attempt somewhere other than 
the reserved executor. `maxNumExecutorsNeededPerResourceProfile` uses it as 
`speculationNeedsSeparation` to decide whether the remaining work needs one 
more executor for speculation locality. Please document both values and when 
the flag is true, so that anyone who changes the speculation rule doesn't have 
to reverse-engineer it from the call site.
   
   **Verification:**
   - **Inspection:** The doc comment states both returned values and the 
condition under which the flag is true.



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