gerashegalov commented on code in PR #8752:
URL: https://github.com/apache/hadoop/pull/8752#discussion_r4656532385


##########
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacitySchedulerAsyncScheduling.java:
##########
@@ -146,6 +149,113 @@ public void testAsyncContainerAllocationWithMultiNode() 
throws Exception {
     testAsyncContainerAllocation(2);
   }
 
+  @Test
+  @Timeout(value = 60)
+  public void testConflictingMultiNodeReservationProposals() throws Exception {
+    CapacitySchedulerConfiguration csConf =
+        new CapacitySchedulerConfiguration(conf);
+    csConf.setBoolean(
+        CapacitySchedulerConfiguration.MULTI_NODE_PLACEMENT_ENABLED, true);
+    csConf.set(CapacitySchedulerConfiguration.MULTI_NODE_SORTING_POLICIES,
+        "resource-based");
+    csConf.set(CapacitySchedulerConfiguration.MULTI_NODE_SORTING_POLICY_NAME,
+        "resource-based");
+    String policy = 
CapacitySchedulerConfiguration.MULTI_NODE_SORTING_POLICY_NAME
+        + ".resource-based";
+    csConf.set(policy + ".class", POLICY_CLASS_NAME);
+    csConf.setInt(policy + ".sorting-interval.ms", 0);
+    csConf.setInt(
+        CapacitySchedulerConfiguration.SCHEDULE_ASYNCHRONOUSLY_MAXIMUM_THREAD, 
1);
+    csConf.setMaximumApplicationMasterResourcePerQueuePercent(
+        new QueuePath("root.default"), 1.0f);
+
+    List<CSAssignment> reservations = new ArrayList<>();
+    List<Boolean> commitResults = new ArrayList<>();
+    CountDownLatch committed = new CountDownLatch(2);
+    CapacityScheduler cs = new CapacityScheduler() {
+      @Override
+      public void submitResourceCommitRequest(Resource cluster,
+          CSAssignment assignment) {
+        if (assignment.getAssignmentInformation().getNumReservations() == 0) {
+          super.submitResourceCommitRequest(cluster, assignment);
+          return;
+        }
+        if (reservations.size() == 2) {
+          return;
+        }
+        // Generate both proposals while the target node is still unreserved.
+        reservations.add(assignment);
+        if (reservations.size() == 2) {
+          
getAsyncSchedulerThreads().forEach(AsyncScheduleThread::suspendSchedule);
+          for (CSAssignment reservation : reservations) {
+            super.submitResourceCommitRequest(cluster, reservation);
+          }
+        }
+      }
+
+      @Override
+      public boolean tryCommit(Resource cluster, ResourceCommitRequest request,
+          boolean updatePending) {
+        boolean accepted = super.tryCommit(cluster, request, updatePending);
+        if (!request.getContainersToReserve().isEmpty()) {
+          commitResults.add(accepted);
+          committed.countDown();
+        }
+        return accepted;
+      }
+    };
+    cs.setConf(csConf);
+    try (MockRM rm = new MockRM(csConf) {
+      @Override
+      protected ResourceScheduler createScheduler() {
+        return cs;
+      }
+    }) {
+      rm.start();
+      assertTrue(cs.getConfiguration().getScheduleAynschronously());
+      MockNM nm1 = rm.registerNode("h1:1234", 5 * GB);

Review Comment:
   Nothing heartbeats the NMs after they register. With multi-node placement, 
async scheduling only considers nodes that heartbeated within `heartbeat 
interval × skip-node multiplier` (2 s by default here). If registering h1 and 
launching the two AMs takes longer than that on a slow CI host, h1 is no longer 
a candidate. Then no reservation is proposed, and the test fails at the 30 s 
latch even though the code is correct.
   
   Locally, adding a 2.5 s sleep before `am1.allocate` makes the test fail, and 
setting `YarnConfiguration.SCHEDULER_SKIP_NODE_MULTIPLIER` to a large value 
makes it pass again. Other tests in this class guard against this with 
`keepNMHeartbeat` or a raised multiplier. Could you do the same here?



##########
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/allocator/TestRegularContainerAllocator.java:
##########
@@ -0,0 +1,227 @@
+/**
+ * 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.hadoop.yarn.server.resourcemanager.scheduler.capacity.allocator;
+
+import java.util.Arrays;
+import java.util.Iterator;
+
+import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.api.records.ResourceRequest;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.AppSchedulingInfo;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.AbstractLeafQueue;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.SchedulingMode;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.PendingAsk;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.placement.AppPlacementAllocator;
+import 
org.apache.hadoop.yarn.server.resourcemanager.scheduler.placement.CandidateNodeSet;
+import org.apache.hadoop.yarn.server.scheduler.SchedulerRequestKey;
+import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class TestRegularContainerAllocator {
+
+  private FiCaSchedulerApp application;
+  private RMContext rmContext;
+  private SchedulerRequestKey schedulerKey;
+  private CandidateNodeSet<FiCaSchedulerNode> candidates;
+  private ResourceLimits resourceLimits;
+  private AppSchedulingInfo appSchedulingInfo;
+
+  @BeforeEach
+  public void setUp() {
+    application = mock(FiCaSchedulerApp.class);
+    rmContext = mock(RMContext.class);
+    when(rmContext.getYarnConfiguration()).thenReturn(new YarnConfiguration());
+
+    schedulerKey = mock(SchedulerRequestKey.class);
+    candidates = mock(CandidateNodeSet.class);
+    resourceLimits = mock(ResourceLimits.class);
+    appSchedulingInfo = mock(AppSchedulingInfo.class);
+
+    when(application.getAppSchedulingInfo()).thenReturn(appSchedulingInfo);
+    when(application.getPendingAsk(schedulerKey, ResourceRequest.ANY))
+        .thenReturn(new PendingAsk(Resource.newInstance(1024, 1), 1));
+    when(application.getOutstandingAsksCount(schedulerKey)).thenReturn(1);
+
+    AbstractLeafQueue leafQueue = mock(AbstractLeafQueue.class);
+    when(leafQueue.isReservationsContinueLooking()).thenReturn(true);
+    when(application.getCSLeafQueue()).thenReturn(leafQueue);
+    when(application.getAppAttemptResourceUsage()).thenReturn(new 
ResourceUsage());
+    when(resourceLimits.getHeadroom())
+        .thenReturn(Resource.newInstance(100 * 1024, 100));
+    when(candidates.getPartition()).thenReturn("");
+  }
+
+  @Test
+  public void testReservationFallbackUsesReservationNode() throws Exception {
+    FiCaSchedulerNode reservationNode = mock(FiCaSchedulerNode.class);
+    FiCaSchedulerNode skippedNode = mock(FiCaSchedulerNode.class);
+    when(reservationNode.getNodeID())
+        .thenReturn(NodeId.newInstance("reservation", 1234));
+    when(skippedNode.getNodeID())
+        .thenReturn(NodeId.newInstance("skipped", 1234));
+
+    mockPlacement(reservationNode, skippedNode);
+    allowNodePrecheck(reservationNode);
+
+    ContainerAllocation reservation = new ContainerAllocation(null,
+        Resource.newInstance(1024, 1), AllocationState.RESERVED);
+    TestAllocator allocator =
+        new TestAllocator(application, rmContext, reservation);
+
+    ContainerAllocation result = allocate(allocator);
+
+    assertEquals(AllocationState.RESERVED, result.getAllocationState());
+    assertSame(reservationNode, allocator.getLastDoAllocationNode());
+  }
+
+  @Test
+  public void testLaterReservationReplacesEarlierReservation()
+      throws Exception {
+    FiCaSchedulerNode firstReservationNode = mock(FiCaSchedulerNode.class);
+    FiCaSchedulerNode secondReservationNode = mock(FiCaSchedulerNode.class);
+    FiCaSchedulerNode skippedNode = mock(FiCaSchedulerNode.class);
+    when(firstReservationNode.getNodeID())
+        .thenReturn(NodeId.newInstance("reservation1", 1234));
+    when(secondReservationNode.getNodeID())
+        .thenReturn(NodeId.newInstance("reservation2", 1234));
+    when(skippedNode.getNodeID())
+        .thenReturn(NodeId.newInstance("skipped", 1234));
+
+    mockPlacement(firstReservationNode, secondReservationNode, skippedNode);
+    allowNodePrecheck(firstReservationNode);
+    allowNodePrecheck(secondReservationNode);
+
+    ContainerAllocation firstReservation = new ContainerAllocation(null,
+        Resource.newInstance(1024, 1), AllocationState.RESERVED);
+    ContainerAllocation secondReservation = new ContainerAllocation(null,
+        Resource.newInstance(2048, 1), AllocationState.RESERVED);
+    TestAllocator allocator = new TestAllocator(application, rmContext,
+        firstReservation, secondReservation);
+
+    ContainerAllocation result = allocate(allocator);
+
+    assertSame(secondReservation, result);
+    assertSame(secondReservationNode, allocator.getLastDoAllocationNode());
+  }
+
+  @Test
+  public void testFailedAllocationPreventsReservationFallback()

Review Comment:
   This test also passes on the code before the fix, so it documents the 
intended behavior rather than catching the bug. That's fine, but a short 
comment saying so would help.
   
   Nothing covers the success path: a `RESERVED` result followed by an 
`ALLOCATED` result on a later node that commits. That is the case `return 
doAllocation(...)` is meant to handle. Could you add a test for it?



##########
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/allocator/RegularContainerAllocator.java:
##########
@@ -840,14 +840,15 @@ ContainerAllocation doAllocation(ContainerAllocation 
allocationResult,
     return allocationResult;
   }
 
-  private ContainerAllocation allocate(Resource clusterResource,
+  ContainerAllocation allocate(Resource clusterResource,

Review Comment:
   Nit: since this was widened only for tests, consider `@VisibleForTesting`.



##########
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/allocator/RegularContainerAllocator.java:
##########
@@ -921,15 +921,15 @@ private ContainerAllocation allocate(Resource 
clusterResource,
       // iterator could not fit and returns RESERVED allocation.
       if (AllocationState.RESERVED == result.getAllocationState()) {

Review Comment:
   The fallback can now pick a node that already holds another container's 
reservation. `skip-allocate-on-nodes-with-reserved-containers` is `false` by 
default, so `tryAllocateOnNode` still returns `RESERVED` for such a node.
   
   That proposal can never commit, because `FiCaSchedulerApp#accept` rejects a 
new reservation on an already-reserved node. Its resource is non-zero, though, 
so `AbstractLeafQueue` returns it and stops trying the remaining apps. The same 
proposal is built again on every cycle.
   
   Before this change, the method returned the last node's skip in this 
situation, and the queue moved on to the next app. Base already had this 
behavior when the reserved node happened to be the last candidate; this change 
extends it to a reserved node in any position.
   
   Repro, with sync multi-node and the resource-based policy:
   - h1 5 GB holds app1's 2 GB AM, h2 3 GB is full, h3 and h4 are 3 GB and 
empty.
   - app1 asks for two 4 GB containers; app2 asks for 1 GB.
   - Update 1 correctly reserves h1. Updates 2 and 3 each propose a second 
reservation on h1 for app1's other ask, and commit rejects it ("Try to reserve 
a container, but the node is already reserved by another container").
   - app2's 1 GB request is never tried, although it fits on h3.
   
   Suggested guard (`nodeReservedContainer` is already in scope):
   
   ```suggestion
         if (AllocationState.RESERVED == result.getAllocationState()
             && (nodeReservedContainer == null
                 || nodeReservedContainer == reservedContainer)) {
   ```
   
   With the guard, app2 is allocated on update 2, no proposals are rejected, 
and app1 keeps exactly one reservation on h1. All tests in this PR still pass, 
as do `TestCapacitySchedulerMultiNodesWithPreemption`, 
`TestContainerAllocation` and `TestReservations`.
   
   <details><summary>Regression test for TestCapacitySchedulerMultiNodes (fails 
at this head, passes with the guard)</summary>
   
   Additional imports: `java.util.concurrent.atomic.AtomicInteger`, 
`org.apache.hadoop.yarn.api.records.Resource`, 
`org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.ResourceCommitRequest`.
   
   ```java
     /**
      * The reservation fallback must not pick a node that already holds a
      * different reservation: that proposal is always rejected at commit, and
      * because its resource is non-zero it stops the leaf queue from trying the
      * next application.
      */
     @Test
     @Timeout(value = 60)
     public void testFallbackReservationOnReservedNodeDoesNotBlockQueue()
         throws Exception {
       CapacitySchedulerConfiguration newConf =
           new CapacitySchedulerConfiguration(conf);
       
newConf.setInt(CapacitySchedulerConfiguration.MULTI_NODE_SORTING_POLICY_NAME
           + ".resource-based.sorting-interval.ms", 0);
       newConf.setMaximumApplicationMasterResourcePerQueuePercent(DEFAULT, 
1.0f);
       // Keep nodes that only heartbeat at registration in the candidate set.
       newConf.setInt(YarnConfiguration.SCHEDULER_SKIP_NODE_MULTIPLIER, 100000);
   
       AtomicInteger rejectedReservations = new AtomicInteger();
       CapacityScheduler countingCs = new CapacityScheduler() {
         @Override
         public boolean tryCommit(Resource cluster, ResourceCommitRequest 
request,
             boolean updatePending) {
           boolean accepted = super.tryCommit(cluster, request, updatePending);
           if (!accepted && !request.getContainersToReserve().isEmpty()) {
             rejectedReservations.incrementAndGet();
           }
           return accepted;
         }
       };
       countingCs.setConf(newConf);
       try (MockRM rm = new MockRM(newConf) {
         @Override
         protected ResourceScheduler createScheduler() {
           return countingCs;
         }
       }) {
         rm.start();
         // h1 5 GB; h2, h3, h4 3 GB (can never hold 4 GB).
         MockNM nm1 = rm.registerNode("h1:1234", 5 * GB);
         MockNM nm2 = rm.registerNode("h2:1234", 3 * GB);
         MockNM nm3 = rm.registerNode("h3:1234", 3 * GB);
         MockNM nm4 = rm.registerNode("h4:1234", 3 * GB);
   
         RMApp app1 = MockRMAppSubmitter.submit(rm,
             MockRMAppSubmissionData.Builder.createWithMemory(2 * GB, rm)
                 .withAppName("app1").withUser("user1").withQueue("default")
                 .build());
         MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, nm1);
         RMApp app2 = MockRMAppSubmitter.submit(rm,
             MockRMAppSubmissionData.Builder.createWithMemory(3 * GB, rm)
                 .withAppName("app2").withUser("user2").withQueue("default")
                 .build());
         MockAM am2 = MockRM.launchAndRegisterAM(app2, rm, nm2);
   
         CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
         FiCaSchedulerApp schedulerApp1 =
             cs.getApplicationAttempt(am1.getApplicationAttemptId());
         FiCaSchedulerApp schedulerApp2 =
             cs.getApplicationAttempt(am2.getApplicationAttemptId());
         int liveBefore = schedulerApp2.getLiveContainers().size();
   
         // Visit order: h3, h4 (0 GB used), h1 (2 GB), h2 (3 GB).
         // app1 wants two 4 GB containers: only h1 can reserve.
         // app2 wants 1 GB, which fits on h3/h4.
         am1.allocate("*", 4 * GB, 2, new ArrayList<>());
         am2.allocate("*", 1 * GB, 1, new ArrayList<>());
   
         RMNode rmNode1 = rm.getRMContext().getRMNodes().get(nm1.getNodeId());
         for (int i = 0; i < 3
             && schedulerApp2.getLiveContainers().size() == liveBefore; i++) {
           cs.handle(new NodeUpdateSchedulerEvent(rmNode1));
         }
   
         assertEquals(liveBefore + 1, schedulerApp2.getLiveContainers().size(),
             "rejected reservation proposals=" + rejectedReservations.get());
         assertEquals(0, rejectedReservations.get());
         RMContainer reserved = 
cs.getNode(nm1.getNodeId()).getReservedContainer();
         assertNotNull(reserved);
         assertEquals(1, schedulerApp1.getReservedContainers().size());
         assertSame(reserved, schedulerApp1.getReservedContainers().get(0));
         assertNull(cs.getNode(nm3.getNodeId()).getReservedContainer());
         assertNull(cs.getNode(nm4.getNodeId()).getReservedContainer());
       }
     }
   ```
   
   </details>



##########
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacitySchedulerMultiNodes.java:
##########
@@ -522,6 +523,63 @@ public void testMultiNodeSorterAfterHeartbeatInterval() 
throws Exception {
     rm.stop();
   }
 
+  @Test
+  @Timeout(value = 30)
+  public void testReservationPreservedAfterLaterNodeSkipped()
+      throws Exception {
+    CapacitySchedulerConfiguration newConf =
+        new CapacitySchedulerConfiguration(conf);
+    
newConf.setInt(CapacitySchedulerConfiguration.MULTI_NODE_SORTING_POLICY_NAME
+        + ".resource-based.sorting-interval.ms", 0);
+    newConf.setMaximumApplicationMasterResourcePerQueuePercent(DEFAULT, 1.0f);
+    MockRM rm = new MockRM(newConf);
+
+    try {
+      rm.start();
+      MockNM nm1 = rm.registerNode("h1:1234", 5 * GB);

Review Comment:
   The same 2 s heartbeat window applies here. If h2 ages out of the candidate 
set, h1 becomes the last candidate, and the test also passes against the 
unfixed allocator. I confirmed that with a 2.5 s sleep. Raising 
`SCHEDULER_SKIP_NODE_MULTIPLIER` would keep this test meaningful.



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