spark-test commented on code in PR #56957: URL: https://github.com/apache/spark/pull/56957#discussion_r4508912856
########## core/src/main/scala/org/apache/spark/scheduler/TaskAssignmentStrategy.scala: ########## @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.scheduler + +import scala.collection.mutable +import scala.util.Random + +/** + * Decides the order in which the executor [[WorkerOffer]]s of a single resource-offer round are + * considered when [[TaskSchedulerImpl]] launches tasks, and whether an offer should be revisited + * after a task has (or has not) been launched on it. Different strategies produce different task + * placement, e.g. concentrating tasks onto few executors versus spreading them evenly. + * + * Lifecycle: a single instance is created per [[TaskSchedulerImpl.resourceOffers]] round and shared + * across all task sets and locality levels of that round. [[prepare]] is called once at the start + * of the round with the offers and the live `availableCpus` array; [[reset]] is called at the start + * of every `resourceOfferSingleTaskSet` invocation (i.e. per task set x locality level x scheduling + * pass) to restart the iteration cursor. The scheduler drives the assignment strategy like this: + * {{{ + * assignmentStrategy.prepare(offers, availableCpus) // once per resource-offer round + * for (taskSet <- sortedTaskSets; locality <- localityLevels) { + * assignmentStrategy.reset() // once per resourceOfferSingleTaskSet pass + * while (assignmentStrategy.hasNext) { + * val i = assignmentStrategy.next() // index into the prepare() offers + * val launched = tryToLaunchOn(i) // attempt to schedule a task on offers(i) + * assignmentStrategy.taskLaunched(launched) + * } + * } + * }}} + * `availableCpus` is drained in place by the scheduler as tasks launch (and reverted on the barrier + * partial-launch path), so strategies that order by free cores read the live values on each + * [[reset]] rather than a stale snapshot. The strategy is selected via + * [[internal.config.TASK_ASSIGNMENT_STRATEGY]]. + */ +private[spark] trait TaskAssignmentStrategy { + + /** + * Called once at the start of a resource-offer round. All subsequent indices produced by + * `next()` refer to `offers`. `availableCpus` is the live per-offer free-cpu array (index `i` + * corresponds to `offers(i)`) that the scheduler mutates as the round proceeds; strategies that + * order by free cores may hold a reference to it and read the current values in [[reset]]. + */ + def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit + + /** + * Called at the start of every `resourceOfferSingleTaskSet` invocation to restart the iteration. + * Strategies that order by free cores recompute their order here from the live `availableCpus`. + */ + def reset(): Unit + + /** Returns true while there is another offer index to visit in the current pass. */ + def hasNext: Boolean + + /** Returns the index of the offer to try next. */ + def next(): Int + + /** + * Reports whether a task was launched on the offer returned by the most recent `next()`. Let + * the strategy decide whether to advance past the current offer or revisit it. + */ + def taskLaunched(launched: Boolean): Unit = {} +} + +/** + * Visits every offer once, in the order they were prepared. + */ +private[spark] class SimpleAssignmentStrategy extends TaskAssignmentStrategy { + private var preparedOffer: IndexedSeq[WorkerOffer] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + preparedOffer = offers + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < preparedOffer.length + + override def next(): Int = { + val originalIndex = index + index = index + 1 + originalIndex + } +} + +/** + * Visits every offer once, but shuffles the offers once in `prepare` so that tasks are not always + * placed on the same executors. The shuffled order is fixed for the whole round and reused across + * all task sets and locality levels. + */ +private[spark] class RoundRobinAssignmentStrategy extends TaskAssignmentStrategy { + private var shuffledIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + shuffledIndices = Random.shuffle(offers.indices.toIndexedSeq) + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < shuffledIndices.length + + override def next(): Int = { + val originalIndex = shuffledIndices(index) + index = index + 1 + originalIndex + } +} + +/** + * Concentrates a task set onto as few executors as possible, which can help dynamic allocation + * reclaim idle executors and speed up executor decommissioning. Offers are visited best-fit first: + * the executor with the fewest free cores (the "fullest" one) is tried first, with executor id as a + * deterministic tie-breaker when two offers have the same number of free cores. The strategy keeps + * launching tasks on the current offer until it can no longer accept one, only then advancing to + * the next. Ordering by the live `availableCpus` (recomputed on every [[reset]]) means executors + * that already carry work sort ahead of idle ones, so packing keeps filling the busiest executors + * and lets the rest idle out; the executor-id tie-break keeps the target deterministic and + * convergent across resource-offer rounds when free-core counts are equal. + */ +private[spark] class BinPackAssignmentStrategy extends TaskAssignmentStrategy { + private var offers: IndexedSeq[WorkerOffer] = _ + private var availableCpus: Array[BigDecimal] = _ + private var orderedIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + this.offers = offers + this.availableCpus = availableCpus + } + + override def reset(): Unit = { + // Recompute the visit order from the live free-core counts (they change as tasks launch and + // are reverted on the barrier partial-launch path). Fewest free cores first packs the fullest + // executors, and executor id breaks ties so the order is stable across rounds. + orderedIndices = + offers.indices.sortBy(i => (availableCpus(i), offers(i).executorId)).toIndexedSeq Review Comment: **Non-blocking (P2):** Sorting by free cores alone treats the executor with the fewest free cores as the busiest, which holds only when executors are the same size. In standalone mode without `spark.executor.cores`, each worker runs one executor sized by the cores assigned to it, so sizes can differ. Take an 8-core executor with 4 tasks running (4 free) and an idle 3-core executor (3 free): the idle one sorts first and a 3-task task set lands entirely on it, leaving both executors busy although the 8-core one alone had room. Even with every executor idle, the new 5/4/6-core test in `TaskSchedulerImplSuite` spreads 6 tasks over two executors when the 6-core one could hold all of them. The scaladoc, the config doc and `docs/configuration.md` promise fewest-executor, busiest-first placement without that caveat, so on mixed-size executors binpack can keep executors busy that dynamic allocation would otherwise reclaim. Equally sized executors, the usual case within one resource profile on YARN and Kubernetes, behave as documented. This extends existing discussions [1](https://github.com/apache/spark/pull/56957#issuecomment-5087877708), [2](https://github.com/apache/spark/pull/56957#pullrequestreview-4777263336). **Recommended change:** Rank binpack offers busy-first: executors already running tasks come ahead of idle ones, then fewer free cores, then executor id, using running-task counts that resourceOffers provides to the strategy. Rewrite the binpack descriptions in the config doc, the configuration docs and the class scaladoc to describe that order instead of promising the fewest possible executors. Add binpack scheduler tests with differently sized busy and idle executors. **Why this works:** resourceOffers already tracks the running tasks of each executor and updates that count as tasks launch. If prepare receives this live count, reset can sort executors by whether they carry work before it compares free cores. Packing then keeps filling executors that are already busy, whatever their size, and leaves idle executors idle so dynamic allocation can reclaim them. The documentation then states exactly that order. **Scope:** Give binpack a busy-first ranking based on the scheduler's running-task state, and make its documentation match. **Compatibility:** Placement under roundrobin, none and balance is unchanged, and binpack still fills one executor before moving on to the next. **Risks:** Placement under binpack changes on clusters where executor sizes differ or some executors are already busy. The strategy remains opt-in, and switching strategy rolls the change back. Barrier tasks count as running only once their whole task set launches, so within a single barrier task set the busy signal lags behind the free-core counts. **Constraints:** The new order must stay compatible with the per-pass ordering-cost fix, which orders only offers that can fit a task and re-sorts incrementally in the same reset step, and with binpack's locality-preserving fill rule, which only decides when binpack moves on to the next executor. **Exclusions:** - A different policy among idle executors, such as largest first, is left to the author; idle executors keep the fewest-free-cores-first order. **Success:** With an 8-core executor running tasks (4 free cores) and an idle 3-core executor, a 3-task task set under binpack lands on the busy executor and the idle executor receives no task. The binpack documentation describes busy-first, then fewest-free-cores ordering and no longer promises the fewest possible executors. **Verification:** - **Regression:** A binpack scheduling test with differently sized executors, one partially busy and one idle, shows new tasks going to the busy executor while the idle executor stays unused. - **Behavior:** On equally sized idle executors, binpack placement is unchanged: it fills one executor before the next, in executor-id order. - **Inspection:** The config doc, the user docs and the class scaladoc describe the implemented order and make no fewest-executor guarantee. ########## core/src/test/scala/org/apache/spark/scheduler/TaskSchedulerImplSuite.scala: ########## @@ -208,6 +208,181 @@ class TaskSchedulerImplSuite extends SparkFunSuite with LocalSparkContext assert(!failedTaskSet) } + test("SPARK-57878: Binpack assignment concentrates tasks onto a part of executors") { + val taskScheduler = setupScheduler(config.TASK_ASSIGNMENT_STRATEGY.key -> "binpack") + val workerOffers = IndexedSeq( + WorkerOffer("executor0", "host0", 5), + WorkerOffer("executor1", "host0", 4), + WorkerOffer("executor2", "host1", 6)) + val taskSet = FakeTask.createTaskSet(6) + taskScheduler.submitTasks(taskSet) + val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten + assert(taskDescriptions.length === 6) + val perExecutor = taskDescriptions.groupBy(_.executorId).view.mapValues(_.size).toMap + // All executors are idle at the start, so they are visited fewest-free-cores first: executor1 + // (4 cores) is packed to its capacity, and the remaining 2 tasks land on executor0 (5 cores). + assert(perExecutor.size === 2) + assert(perExecutor.get("executor1").contains(4)) + assert(perExecutor.get("executor0").contains(2)) + assert(!perExecutor.contains("executor2")) + } + + test("SPARK-57878: Balance assignment spreads tasks across executors") { + val taskScheduler = setupScheduler(config.TASK_ASSIGNMENT_STRATEGY.key -> "balance") + val workerOffers = IndexedSeq( + WorkerOffer("executor0", "host0", 2), + WorkerOffer("executor1", "host0", 4), + WorkerOffer("executor2", "host1", 4)) + val taskSet = FakeTask.createTaskSet(4) + taskScheduler.submitTasks(taskSet) + val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten + assert(taskDescriptions.length === 4) + val perExecutor = taskDescriptions.groupBy(_.executorId).view.mapValues(_.size).toMap + assert(perExecutor.size === 2) + assert(!perExecutor.contains("executor0")) + assert(perExecutor.get("executor1").contains(2)) + assert(perExecutor.get("executor2").contains(2)) + } + + test("SPARK-57878: Binpack assignment still honors PROCESS_LOCAL preference over packing") { + // The strategy is prepared once per resource-offer round and reset for each locality level in + // resourceOfferSingleTaskSet, and TaskSetManager.resourceOffer gates each launch by locality. + // So bin-packing only reorders which offers are tried within a locality tier; it must not + // steal a task away from the executor it prefers. + val taskScheduler = setupScheduler(config.TASK_ASSIGNMENT_STRATEGY.key -> "binpack") + // executor2 has the fewest free cores, so binpack would try it first if locality did not + // constrain placement. The single task prefers executor0 (which has more cores). + val workerOffers = IndexedSeq( + WorkerOffer("executor0", "host0", 4), + WorkerOffer("executor1", "host1", 3), + WorkerOffer("executor2", "host2", 1)) + val taskSet = FakeTask.createTaskSet(1, + Seq(ExecutorCacheTaskLocation("host0", "executor0"))) + taskScheduler.submitTasks(taskSet) + val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten + assert(taskDescriptions.length === 1) + // The task lands on its preferred executor, not on the most-packed one. + assert(taskDescriptions.head.executorId === "executor0") + // ...and it is scheduled at PROCESS_LOCAL, i.e. binpack did not force a worse locality. + val tsm = taskScheduler.taskSetManagerForAttempt(taskSet.stageId, 0).get + assert(tsm.taskInfos(taskDescriptions.head.taskId).taskLocality === TaskLocality.PROCESS_LOCAL) + } + + test("SPARK-57878: Balance assignment still honors PROCESS_LOCAL preference over spreading") { + val taskScheduler = setupScheduler(config.TASK_ASSIGNMENT_STRATEGY.key -> "balance") + // executor0 has the most free cores, so balance would try it first if locality did not + // constrain placement. The single task prefers executor2 (which has the fewest cores). + val workerOffers = IndexedSeq( + WorkerOffer("executor0", "host0", 4), + WorkerOffer("executor1", "host1", 3), + WorkerOffer("executor2", "host2", 1)) + val taskSet = FakeTask.createTaskSet(1, + Seq(ExecutorCacheTaskLocation("host2", "executor2"))) + taskScheduler.submitTasks(taskSet) + val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten + assert(taskDescriptions.length === 1) + // The task lands on its preferred executor, not on the one with the most free cores. + assert(taskDescriptions.head.executorId === "executor2") + // ...and it is scheduled at PROCESS_LOCAL, i.e. balance did not force a worse locality. + val tsm = taskScheduler.taskSetManagerForAttempt(taskSet.stageId, 0).get + assert(tsm.taskInfos(taskDescriptions.head.taskId).taskLocality === TaskLocality.PROCESS_LOCAL) + } + + test("SPARK-57878: Rejects an unknown assignment strategy") { + val conf = new SparkConf() + // checkValues on the config entry rejects unknown values at get() time. + val error = intercept[IllegalArgumentException] { + conf.set(config.TASK_ASSIGNMENT_STRATEGY.key, "does-not-exist") + conf.get(config.TASK_ASSIGNMENT_STRATEGY) + } + assert(error.getMessage.contains( + "'does-not-exist' in the config \"spark.scheduler.taskAssignmentStrategy\" is invalid")) + } + + test("SPARK-57878: Binpack assignment packs multiple tasksets onto the same executor") { + // Two tasksets are offered in a single resource-offer round. Both executors start with the same + // free cores, so the executor-id tie-break visits executor0 first; the first taskset uses one + // slot there, and because binpack packs greedily by fewest-free-cores, the now-fuller executor0 + // stays ahead of executor1, so the second taskset keeps filling it before spilling over. + val taskScheduler = setupScheduler(config.TASK_ASSIGNMENT_STRATEGY.key -> "binpack") + val workerOffers = IndexedSeq( + WorkerOffer("executor0", "host0", 2), + WorkerOffer("executor1", "host1", 2)) + val taskSet0 = FakeTask.createTaskSet(1, stageId = 0, stageAttemptId = 0, priority = 0, + rpId = ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID) + val taskSet1 = FakeTask.createTaskSet(1, stageId = 1, stageAttemptId = 0, priority = 1, + rpId = ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID) + taskScheduler.submitTasks(taskSet0) + taskScheduler.submitTasks(taskSet1) + val taskDescriptions = taskScheduler.resourceOffers(workerOffers).flatten + assert(taskDescriptions.length === 2) + // Both tasks land on executor0, leaving executor1 idle so it can be reclaimed. + assert(taskDescriptions.forall(_.executorId === "executor0")) Review Comment: **Nit (P3):** This assertion also holds if binpack never re-sorts: both offers start with 2 free cores, so the executor-id tie-break already puts executor0 first for the second task set. More broadly, computing binpack's order once per round instead of on each reset would leave every new binpack test green, since each of the others offers a single task set whose first order is already the live one. Likewise, no test reaches the barrier partial-launch revert under `binpack` or `balance` (the binpack barrier test's first round is skipped by the slot check, and the other barrier rounds launch every task), `balance` has no multi-task-set or custom-resource case, and nothing asserts the order `none` keeps, which the migrated locality tests now rely on. The live-state ordering that the earlier review asked about could therefore regress without any test failing. This extends existing discussions [1](https://github.com/apache/spark/pull/56957#issuecomment-5087877708), [2](https://github.com/apache/spark/pull/56957#pullrequestreview-4777263336). **Verification:** - **Regression:** A binpack variant that orders offers only once per round fails the two-task-set placement check. - **Regression:** A strategy that ignores free cores restored after a barrier partial launch fails the barrier checks for both binpack and balance. - **Behavior:** balance places tasks from two task sets, and tasks with GPU requirements, on the executors with the most free cores. - **Behavior:** 'none' visits offers in the order they were given. ########## core/src/main/scala/org/apache/spark/scheduler/TaskAssignmentStrategy.scala: ########## @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.scheduler + +import scala.collection.mutable +import scala.util.Random + +/** + * Decides the order in which the executor [[WorkerOffer]]s of a single resource-offer round are + * considered when [[TaskSchedulerImpl]] launches tasks, and whether an offer should be revisited + * after a task has (or has not) been launched on it. Different strategies produce different task + * placement, e.g. concentrating tasks onto few executors versus spreading them evenly. + * + * Lifecycle: a single instance is created per [[TaskSchedulerImpl.resourceOffers]] round and shared + * across all task sets and locality levels of that round. [[prepare]] is called once at the start + * of the round with the offers and the live `availableCpus` array; [[reset]] is called at the start + * of every `resourceOfferSingleTaskSet` invocation (i.e. per task set x locality level x scheduling + * pass) to restart the iteration cursor. The scheduler drives the assignment strategy like this: + * {{{ + * assignmentStrategy.prepare(offers, availableCpus) // once per resource-offer round + * for (taskSet <- sortedTaskSets; locality <- localityLevels) { + * assignmentStrategy.reset() // once per resourceOfferSingleTaskSet pass + * while (assignmentStrategy.hasNext) { + * val i = assignmentStrategy.next() // index into the prepare() offers + * val launched = tryToLaunchOn(i) // attempt to schedule a task on offers(i) + * assignmentStrategy.taskLaunched(launched) + * } + * } + * }}} + * `availableCpus` is drained in place by the scheduler as tasks launch (and reverted on the barrier + * partial-launch path), so strategies that order by free cores read the live values on each + * [[reset]] rather than a stale snapshot. The strategy is selected via + * [[internal.config.TASK_ASSIGNMENT_STRATEGY]]. + */ +private[spark] trait TaskAssignmentStrategy { + + /** + * Called once at the start of a resource-offer round. All subsequent indices produced by + * `next()` refer to `offers`. `availableCpus` is the live per-offer free-cpu array (index `i` + * corresponds to `offers(i)`) that the scheduler mutates as the round proceeds; strategies that + * order by free cores may hold a reference to it and read the current values in [[reset]]. + */ + def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit + + /** + * Called at the start of every `resourceOfferSingleTaskSet` invocation to restart the iteration. + * Strategies that order by free cores recompute their order here from the live `availableCpus`. + */ + def reset(): Unit + + /** Returns true while there is another offer index to visit in the current pass. */ + def hasNext: Boolean + + /** Returns the index of the offer to try next. */ + def next(): Int + + /** + * Reports whether a task was launched on the offer returned by the most recent `next()`. Let + * the strategy decide whether to advance past the current offer or revisit it. + */ + def taskLaunched(launched: Boolean): Unit = {} +} + +/** + * Visits every offer once, in the order they were prepared. + */ +private[spark] class SimpleAssignmentStrategy extends TaskAssignmentStrategy { + private var preparedOffer: IndexedSeq[WorkerOffer] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + preparedOffer = offers + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < preparedOffer.length + + override def next(): Int = { + val originalIndex = index + index = index + 1 + originalIndex + } +} + +/** + * Visits every offer once, but shuffles the offers once in `prepare` so that tasks are not always + * placed on the same executors. The shuffled order is fixed for the whole round and reused across + * all task sets and locality levels. + */ +private[spark] class RoundRobinAssignmentStrategy extends TaskAssignmentStrategy { + private var shuffledIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + shuffledIndices = Random.shuffle(offers.indices.toIndexedSeq) + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < shuffledIndices.length + + override def next(): Int = { + val originalIndex = shuffledIndices(index) + index = index + 1 + originalIndex + } +} + +/** + * Concentrates a task set onto as few executors as possible, which can help dynamic allocation + * reclaim idle executors and speed up executor decommissioning. Offers are visited best-fit first: + * the executor with the fewest free cores (the "fullest" one) is tried first, with executor id as a + * deterministic tie-breaker when two offers have the same number of free cores. The strategy keeps + * launching tasks on the current offer until it can no longer accept one, only then advancing to + * the next. Ordering by the live `availableCpus` (recomputed on every [[reset]]) means executors + * that already carry work sort ahead of idle ones, so packing keeps filling the busiest executors + * and lets the rest idle out; the executor-id tie-break keeps the target deterministic and + * convergent across resource-offer rounds when free-core counts are equal. + */ +private[spark] class BinPackAssignmentStrategy extends TaskAssignmentStrategy { + private var offers: IndexedSeq[WorkerOffer] = _ + private var availableCpus: Array[BigDecimal] = _ + private var orderedIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + this.offers = offers + this.availableCpus = availableCpus + } + + override def reset(): Unit = { + // Recompute the visit order from the live free-core counts (they change as tasks launch and + // are reverted on the barrier partial-launch path). Fewest free cores first packs the fullest + // executors, and executor id breaks ties so the order is stable across rounds. + orderedIndices = + offers.indices.sortBy(i => (availableCpus(i), offers(i).executorId)).toIndexedSeq Review Comment: **Nit (P3):** This sorts all offers by a freshly built `(availableCpus, executorId)` tuple on every `resourceOfferSingleTaskSet` pass, that is, once per task set, locality level and repeated pass in each round, while holding the scheduler lock that also serializes status updates. In a busy round where most executors have no free cores, each of those sorts (about N log2 N key-building comparisons, roughly 10^4 at 1,000 executors) is followed by probes that all fail the cpu check, so the ordering cannot change any placement, and a pass that follows one that launched nothing re-sorts identical keys. The previous code did no ordering work per pass. Only applications that choose `binpack` pay this; its size was not measured. See **Shared repair plan 1** in the review body. ########## core/src/main/scala/org/apache/spark/scheduler/TaskAssignmentStrategy.scala: ########## @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.scheduler + +import scala.collection.mutable +import scala.util.Random + +/** + * Decides the order in which the executor [[WorkerOffer]]s of a single resource-offer round are + * considered when [[TaskSchedulerImpl]] launches tasks, and whether an offer should be revisited + * after a task has (or has not) been launched on it. Different strategies produce different task + * placement, e.g. concentrating tasks onto few executors versus spreading them evenly. + * + * Lifecycle: a single instance is created per [[TaskSchedulerImpl.resourceOffers]] round and shared + * across all task sets and locality levels of that round. [[prepare]] is called once at the start + * of the round with the offers and the live `availableCpus` array; [[reset]] is called at the start + * of every `resourceOfferSingleTaskSet` invocation (i.e. per task set x locality level x scheduling + * pass) to restart the iteration cursor. The scheduler drives the assignment strategy like this: + * {{{ + * assignmentStrategy.prepare(offers, availableCpus) // once per resource-offer round + * for (taskSet <- sortedTaskSets; locality <- localityLevels) { + * assignmentStrategy.reset() // once per resourceOfferSingleTaskSet pass + * while (assignmentStrategy.hasNext) { + * val i = assignmentStrategy.next() // index into the prepare() offers + * val launched = tryToLaunchOn(i) // attempt to schedule a task on offers(i) + * assignmentStrategy.taskLaunched(launched) + * } + * } + * }}} + * `availableCpus` is drained in place by the scheduler as tasks launch (and reverted on the barrier + * partial-launch path), so strategies that order by free cores read the live values on each + * [[reset]] rather than a stale snapshot. The strategy is selected via + * [[internal.config.TASK_ASSIGNMENT_STRATEGY]]. + */ +private[spark] trait TaskAssignmentStrategy { + + /** + * Called once at the start of a resource-offer round. All subsequent indices produced by + * `next()` refer to `offers`. `availableCpus` is the live per-offer free-cpu array (index `i` + * corresponds to `offers(i)`) that the scheduler mutates as the round proceeds; strategies that + * order by free cores may hold a reference to it and read the current values in [[reset]]. + */ + def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit + + /** + * Called at the start of every `resourceOfferSingleTaskSet` invocation to restart the iteration. + * Strategies that order by free cores recompute their order here from the live `availableCpus`. + */ + def reset(): Unit + + /** Returns true while there is another offer index to visit in the current pass. */ + def hasNext: Boolean + + /** Returns the index of the offer to try next. */ + def next(): Int + + /** + * Reports whether a task was launched on the offer returned by the most recent `next()`. Let + * the strategy decide whether to advance past the current offer or revisit it. + */ + def taskLaunched(launched: Boolean): Unit = {} +} + +/** + * Visits every offer once, in the order they were prepared. + */ +private[spark] class SimpleAssignmentStrategy extends TaskAssignmentStrategy { + private var preparedOffer: IndexedSeq[WorkerOffer] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + preparedOffer = offers + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < preparedOffer.length + + override def next(): Int = { + val originalIndex = index + index = index + 1 + originalIndex + } +} + +/** + * Visits every offer once, but shuffles the offers once in `prepare` so that tasks are not always + * placed on the same executors. The shuffled order is fixed for the whole round and reused across + * all task sets and locality levels. + */ +private[spark] class RoundRobinAssignmentStrategy extends TaskAssignmentStrategy { + private var shuffledIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + shuffledIndices = Random.shuffle(offers.indices.toIndexedSeq) + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < shuffledIndices.length + + override def next(): Int = { + val originalIndex = shuffledIndices(index) + index = index + 1 + originalIndex + } +} + +/** + * Concentrates a task set onto as few executors as possible, which can help dynamic allocation + * reclaim idle executors and speed up executor decommissioning. Offers are visited best-fit first: + * the executor with the fewest free cores (the "fullest" one) is tried first, with executor id as a + * deterministic tie-breaker when two offers have the same number of free cores. The strategy keeps + * launching tasks on the current offer until it can no longer accept one, only then advancing to + * the next. Ordering by the live `availableCpus` (recomputed on every [[reset]]) means executors + * that already carry work sort ahead of idle ones, so packing keeps filling the busiest executors + * and lets the rest idle out; the executor-id tie-break keeps the target deterministic and + * convergent across resource-offer rounds when free-core counts are equal. + */ +private[spark] class BinPackAssignmentStrategy extends TaskAssignmentStrategy { + private var offers: IndexedSeq[WorkerOffer] = _ + private var availableCpus: Array[BigDecimal] = _ + private var orderedIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + this.offers = offers + this.availableCpus = availableCpus + } + + override def reset(): Unit = { + // Recompute the visit order from the live free-core counts (they change as tasks launch and + // are reverted on the barrier partial-launch path). Fewest free cores first packs the fullest + // executors, and executor id breaks ties so the order is stable across rounds. + orderedIndices = + offers.indices.sortBy(i => (availableCpus(i), offers(i).executorId)).toIndexedSeq + index = 0 + } + + override def hasNext: Boolean = index < orderedIndices.size + + override def next(): Int = orderedIndices(index) + + override def taskLaunched(launched: Boolean): Unit = { + // Move to the next work offer only when the current one can no longer accept a task. + if (!launched) { + index = index + 1 + } + } +} + +/** + * Spreads a task set as evenly as possible across the available executors to favor parallelism. + * Offers are kept in a priority queue keyed by the live free cores (with executor id as a + * deterministic tie-breaker), and the offer with the most free cores is always tried next, + * re-enqueued after a successful launch. + */ +private[spark] class BalanceAssignmentStrategy extends TaskAssignmentStrategy { + private var offers: IndexedSeq[WorkerOffer] = _ + private var availableCpus: Array[BigDecimal] = _ + private var preparedOffers: mutable.PriorityQueue[Int] = _ + private var currentIndex: Int = _ + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + this.offers = offers + this.availableCpus = availableCpus + } + + override def reset(): Unit = { + // Order by the live free cores (descending) with executor id as a deterministic tie-breaker. + // The comparator reads the live availableCpus array; only the just-dequeued offer's value is + // mutated by the scheduler before it is re-enqueued, so the heap stays valid. + implicit val ord: Ordering[Int] = new Ordering[Int] { + override def compare(x: Int, y: Int): Int = { + val byCpus = availableCpus(x).compare(availableCpus(y)) + if (byCpus != 0) { + byCpus + } else { + // PriorityQueue dequeues the max, so reverse the id order to make the smaller executor + // id win the tie. + offers(y).executorId.compareTo(offers(x).executorId) + } + } + } + preparedOffers = new mutable.PriorityQueue[Int]() Review Comment: **Nit (P3):** This allocates a new comparator and queue and enqueues every offer on each `resourceOfferSingleTaskSet` pass, that is, once per task set, locality level and repeated pass in every round, all under the scheduler lock. Offers whose free cores are below the task's cpus are enqueued and dequeued only to fail the cpu check, so in a saturated round the heap work (roughly 2 N log2 N comparisons and two allocations per pass) cannot change any placement, where the previous code just walked the shuffled offers. Reusing the queue, as an earlier comment on this method suggests, removes the allocations but still pays to enqueue offers that cannot take a task. Only applications that choose `balance` pay this; its size was not measured. This extends an [existing discussion](https://github.com/apache/spark/pull/56957#discussion_r3701174723). See **Shared repair plan 1** in the review body. ########## core/src/main/scala/org/apache/spark/scheduler/TaskAssignmentStrategy.scala: ########## @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.scheduler + +import scala.collection.mutable +import scala.util.Random + +/** + * Decides the order in which the executor [[WorkerOffer]]s of a single resource-offer round are + * considered when [[TaskSchedulerImpl]] launches tasks, and whether an offer should be revisited + * after a task has (or has not) been launched on it. Different strategies produce different task + * placement, e.g. concentrating tasks onto few executors versus spreading them evenly. + * + * Lifecycle: a single instance is created per [[TaskSchedulerImpl.resourceOffers]] round and shared + * across all task sets and locality levels of that round. [[prepare]] is called once at the start + * of the round with the offers and the live `availableCpus` array; [[reset]] is called at the start + * of every `resourceOfferSingleTaskSet` invocation (i.e. per task set x locality level x scheduling + * pass) to restart the iteration cursor. The scheduler drives the assignment strategy like this: + * {{{ + * assignmentStrategy.prepare(offers, availableCpus) // once per resource-offer round + * for (taskSet <- sortedTaskSets; locality <- localityLevels) { + * assignmentStrategy.reset() // once per resourceOfferSingleTaskSet pass + * while (assignmentStrategy.hasNext) { + * val i = assignmentStrategy.next() // index into the prepare() offers + * val launched = tryToLaunchOn(i) // attempt to schedule a task on offers(i) + * assignmentStrategy.taskLaunched(launched) + * } + * } + * }}} + * `availableCpus` is drained in place by the scheduler as tasks launch (and reverted on the barrier + * partial-launch path), so strategies that order by free cores read the live values on each + * [[reset]] rather than a stale snapshot. The strategy is selected via + * [[internal.config.TASK_ASSIGNMENT_STRATEGY]]. + */ +private[spark] trait TaskAssignmentStrategy { + + /** + * Called once at the start of a resource-offer round. All subsequent indices produced by + * `next()` refer to `offers`. `availableCpus` is the live per-offer free-cpu array (index `i` + * corresponds to `offers(i)`) that the scheduler mutates as the round proceeds; strategies that + * order by free cores may hold a reference to it and read the current values in [[reset]]. + */ + def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit + + /** + * Called at the start of every `resourceOfferSingleTaskSet` invocation to restart the iteration. + * Strategies that order by free cores recompute their order here from the live `availableCpus`. + */ + def reset(): Unit + + /** Returns true while there is another offer index to visit in the current pass. */ + def hasNext: Boolean + + /** Returns the index of the offer to try next. */ + def next(): Int + + /** + * Reports whether a task was launched on the offer returned by the most recent `next()`. Let + * the strategy decide whether to advance past the current offer or revisit it. + */ + def taskLaunched(launched: Boolean): Unit = {} +} + +/** + * Visits every offer once, in the order they were prepared. + */ +private[spark] class SimpleAssignmentStrategy extends TaskAssignmentStrategy { + private var preparedOffer: IndexedSeq[WorkerOffer] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + preparedOffer = offers + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < preparedOffer.length + + override def next(): Int = { + val originalIndex = index + index = index + 1 + originalIndex + } +} + +/** + * Visits every offer once, but shuffles the offers once in `prepare` so that tasks are not always + * placed on the same executors. The shuffled order is fixed for the whole round and reused across + * all task sets and locality levels. + */ +private[spark] class RoundRobinAssignmentStrategy extends TaskAssignmentStrategy { + private var shuffledIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + shuffledIndices = Random.shuffle(offers.indices.toIndexedSeq) + } + + override def reset(): Unit = { + index = 0 + } + + override def hasNext: Boolean = index < shuffledIndices.length + + override def next(): Int = { + val originalIndex = shuffledIndices(index) + index = index + 1 + originalIndex + } +} + +/** + * Concentrates a task set onto as few executors as possible, which can help dynamic allocation + * reclaim idle executors and speed up executor decommissioning. Offers are visited best-fit first: + * the executor with the fewest free cores (the "fullest" one) is tried first, with executor id as a + * deterministic tie-breaker when two offers have the same number of free cores. The strategy keeps + * launching tasks on the current offer until it can no longer accept one, only then advancing to + * the next. Ordering by the live `availableCpus` (recomputed on every [[reset]]) means executors + * that already carry work sort ahead of idle ones, so packing keeps filling the busiest executors + * and lets the rest idle out; the executor-id tie-break keeps the target deterministic and + * convergent across resource-offer rounds when free-core counts are equal. + */ +private[spark] class BinPackAssignmentStrategy extends TaskAssignmentStrategy { + private var offers: IndexedSeq[WorkerOffer] = _ + private var availableCpus: Array[BigDecimal] = _ + private var orderedIndices: IndexedSeq[Int] = _ + private var index = 0 + + override def prepare(offers: IndexedSeq[WorkerOffer], availableCpus: Array[BigDecimal]): Unit = { + this.offers = offers + this.availableCpus = availableCpus + } + + override def reset(): Unit = { + // Recompute the visit order from the live free-core counts (they change as tasks launch and + // are reverted on the barrier partial-launch path). Fewest free cores first packs the fullest + // executors, and executor id breaks ties so the order is stable across rounds. + orderedIndices = + offers.indices.sortBy(i => (availableCpus(i), offers(i).executorId)).toIndexedSeq + index = 0 + } + + override def hasNext: Boolean = index < orderedIndices.size + + override def next(): Int = orderedIndices(index) + + override def taskLaunched(launched: Boolean): Unit = { + // Move to the next work offer only when the current one can no longer accept a task. + if (!launched) { Review Comment: **Non-blocking (P2):** Staying on the same offer until an attempt fails lets the first executor take every task `TaskSetManager` hands it at this level, including tasks that are also local to executors visited later in the pass. For example, with delay scheduling on: executors eA@hA and eB@hB each have 2 free cores, t0 and t1 prefer {hA, hB}, and t2 and t3 prefer only hA. eA wins the tie, takes t0 and t1, and is full. eB's host list holds only t0 and t1, so it finds nothing node-local, and at ANY delay scheduling rejects it, so t2 and t3 wait for `spark.locality.wait` (3s by default) or later run remotely. The previous sweep, which gives each offer at most one launch per pass, launches t0, t1 and t2 node-local in either shuffle order. So with overlapping preferred hosts (HDFS replicas, or several executors per host) binpack gets fewer node-local launches per round, which contradicts the statement in the PR description and the docs that task locality is unaffected. The new locality tests give each task a single preferred executor, so they cannot catch this. **Recommended change:** Report to the strategy whether each launch used the task's locality preference, meaning the task has preferred locations and launched PROCESS_LOCAL, NODE_LOCAL or RACK_LOCAL; the scheduler already has the launch's locality and the dequeued task index. binpack moves to the next executor after such a launch, as the default sweep does, and keeps filling the same executor only after launching a task without preferences or at ANY locality. Add binpack scheduler tests with overlapping preferred hosts, and correct the locality note in the configuration docs to match. **Why this works:** TaskSetManager hands an executor its executor-local and host-local tasks before any others, at every locality level, including the NO_PREF pass that delay scheduling does not hold back. Moving on after every launch that used a task's locality preference lets each executor take its local tasks one at a time, as the default sweep does, so a task that several hosts could run locally is no longer taken by the first executor at the expense of the others. A launch of a task without preferences, or at ANY locality, means the executor had no executor-local or host-local task left to take, so binpack keeps packing those onto it. **Scope:** Make binpack stop filling one executor with tasks that launch through their locality preferences. **Compatibility:** Locality gating in TaskSetManager and the roundrobin, none and balance strategies are unchanged, and binpack still packs tasks without locality preferences onto the fullest executor first. **Risks:** Under binpack, stages whose tasks launch on their preferred executors or hosts are packed less tightly, because after each such launch binpack moves to the next executor, as the default sweep does. binpack remains opt-in, and switching strategy rolls the change back. **Constraints:** The rule only decides when binpack moves on to the next executor, so it must keep the visit order that the busy-first ordering fix and the per-pass ordering-cost fix compute when each pass is reset. **Success:** In the overlapping-preference case (two 2-core executors, two tasks preferring both hosts and two preferring one host), binpack launches the same three node-local tasks in the round as the default strategy. The same holds when the task set also contains a task without preferences and an executor-local task still waiting for its busy executor, so that the overlapping tasks are placed in the NO_PREF pass. Tasks without locality preferences, and tasks launched at ANY locality, are still packed onto the fullest executor first. **Verification:** - **Regression:** A binpack test with tasks whose preferred hosts overlap shows the same node-local launches per round as the default strategy and no extra delay-scheduling wait, both on its own and with a task without preferences and an executor-local task waiting for a busy executor in the same task set. - **Behavior:** binpack still concentrates tasks without locality preferences in its fullest-first order, so the existing binpack placement expectations still hold. ########## core/src/main/scala/org/apache/spark/scheduler/TaskSchedulerImpl.scala: ########## @@ -551,19 +561,22 @@ private[spark] class TaskSchedulerImpl( } }.getOrElse(offers) - val shuffledOffers = shuffleOffers(filteredOffers) // Build a list of tasks to assign to each worker. // Note the size estimate here might be off with different ResourceProfiles but should be // close estimate. It is only a capacity hint, so cap it: with a tiny fractional // spark.task.cpus the exact slot count can be huge and would preallocate a giant buffer. - val tasks = shuffledOffers.map { o => + val tasks = filteredOffers.map { o => val sizeHint = math.min(ResourceProfile.numTasksBasedOnCores(o.cores, CPUS_PER_TASK), 1024) new ArrayBuffer[TaskDescription](sizeHint) } - val availableResources = shuffledOffers.map(_.resources).toArray - val availableCpus = shuffledOffers.map(o => o.cores).toArray - val resourceProfileIds = shuffledOffers.map(o => o.resourceProfileId).toArray + val availableResources = filteredOffers.map(_.resources).toArray + val availableCpus = filteredOffers.map(o => o.cores).toArray + val resourceProfileIds = filteredOffers.map(o => o.resourceProfileId).toArray + // Create the assignment strategy once per round and prepare it with the live availableCpus + // array so strategies that order by free cores observe resources being drained as tasks launch. + val assignmentStrategy = TaskAssignmentStrategy.create(taskAssignmentStrategy) Review Comment: **Nit (P3):** Now that this line selects the configured strategy, the method's scaladoc above ('We fill each node with tasks in a round-robin manner so that tasks are balanced across the cluster') is accurate only for `roundrobin` and `none`: `binpack` deliberately fills one executor before moving to the next, and `balance` keeps returning to whichever executor has the most free cores. The scheduler's main entry point now misdescribes placement for supported settings. See **Shared repair plan 2** in the review body. -- 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]
