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


##########
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:
   Nothing masks the chosen executor after this launch, so the ordinary loop 
below fills its remaining cores in the same round. What does the retry gain 
over ordinary placement, given it also gives up locality?



##########
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:
   Is this needed for the feature? The reservation mask sets CPUs to 0 and 
resources to empty, for which `calculateAvailableSlots` already returns 0. This 
looks like a fix for fractional-resource fragmentation that predates this PR, 
and it changes barrier scheduling for everyone. Please split it out.



##########
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:
   On a heap OOM the culprit reports its own `ExceptionFailure` before the 
executor exits with 52, yet every co-located task is charged here too. Those 
neighbors lose speculation and, after a second such loss, compete with the 
culprit for the single reservation in task-set/partition order, each waiting up 
to `isolationTimeout` if it loses. Would it be enough to skip executor-level 
attribution when a task on that executor already reported a typed OOM?
   
   Also, this match is duplicated in `ExecutorAllocationManager.onTaskEnd`; a 
shared method on `TaskFailedReason` would keep them in sync.



##########
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:
   This changes when SPARK-55639 recovery mode triggers: a sidecar `OOMKilled` 
in the exit message used to trigger it and no longer does, while exit code 52 
now does. @dongjoon-hyun, is that the intended behavior?



##########
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:
   On standalone, `onDisconnected` can remove the executor with 
`ExecutorProcessLost` before the Master reports the exit code, in which case 
exit 52 is not recognized. Worth either noting that or handling it.



##########
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:
   This fixes a double decrement that exists on master today and is independent 
of OOM recovery. A separate PR would make it backportable.



##########
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:
   `ExecutorExited` is `private[spark]`, so this could be a constructor 
parameter with a default rather than a `var` that `copy`, `equals` and 
`toString` ignore.



##########
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:
   Dropping the `throw` changes the legacy barrier abort path with the policy 
off. Reasonable, since the throw discarded launches already registered in this 
round, but it deserves its own JIRA.



##########
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:
   This adds an annotation to every executor pod to handle feature steps that 
rename the container, which is a limitation of the existing exit-code lookup 
and unrelated to OOM retry. Separate PR?



##########
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:
   This fixes an existing leak (the task stays in the scheduler's running set 
after the abort) regardless of the policy. Please split it out as well.



##########
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:
   This second per-task map, the `isExecutorActive` check on task start, and 
the `onExecutorRemoved` cleanup exist only to size around one reserved 
executor. Without them, at most `tasksPerExecutor - 1` tasks wait for one 
isolated attempt. Could this land as a follow-up once the policy itself is in?



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