goutamadwant commented on code in PR #12277:
URL: https://github.com/apache/seatunnel/pull/12277#discussion_r3998102230


##########
seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/TaskExecutionServiceCooperativeBudgetTest.java:
##########
@@ -0,0 +1,168 @@
+/*
+ * 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.seatunnel.engine.server;
+
+import org.apache.seatunnel.engine.common.utils.PassiveCompletableFuture;
+import org.apache.seatunnel.engine.server.execution.CooperativeWorkerBudget;
+import org.apache.seatunnel.engine.server.execution.FixedCallTestTimeTask;
+import org.apache.seatunnel.engine.server.execution.Task;
+import org.apache.seatunnel.engine.server.execution.TaskExecutionState;
+import org.apache.seatunnel.engine.server.execution.TaskGroup;
+import org.apache.seatunnel.engine.server.execution.TaskGroupDefaultImpl;
+import org.apache.seatunnel.engine.server.execution.TaskGroupLocation;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import lombok.NonNull;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static 
org.apache.seatunnel.engine.server.execution.ExecutionState.FINISHED;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Covers the promotion budget of cooperative workers, configured by {@code
+ * seatunnel_cooperative_worker_budget.yaml} with a global limit of 2 and a 
per job limit of 1.
+ *
+ * <p>Every cooperative task here needs much longer than the call timer 
allows, so without a budget
+ * each one of them would promote its own worker thread.
+ */
+public class TaskExecutionServiceCooperativeBudgetTest
+        extends 
AbstractSeaTunnelServerTest<TaskExecutionServiceCooperativeBudgetTest> {
+
+    private static final int MAX_PROMOTED_WORKERS_PER_JOB = 1;
+    private static final long SLOW_CALL_TIME_MILLIS = 300;
+    private static final int SLOW_TASK_COUNT = 8;
+
+    private static String previousConfigFile;
+
+    @BeforeAll
+    public void before() {
+        previousConfigFile = System.getProperty("seatunnel.config");
+        System.setProperty("seatunnel.config", configFilePath());
+        super.before();
+    }
+
+    @AfterAll
+    public void after() {
+        try {
+            super.after();
+        } finally {
+            if (previousConfigFile == null) {
+                System.clearProperty("seatunnel.config");
+            } else {
+                System.setProperty("seatunnel.config", previousConfigFile);
+            }
+        }
+    }
+
+    @Test
+    public void testSlowCooperativeTasksCannotPromoteMoreWorkersThanTheBudget()
+            throws InterruptedException {
+        TaskExecutionService taskExecutionService = 
server.getTaskExecutionService();
+        CooperativeWorkerBudget budget = 
taskExecutionService.getCooperativeWorkerBudget();
+        assertEquals(2, budget.getMaxPromotedWorkers());
+        assertEquals(MAX_PROMOTED_WORKERS_PER_JOB, 
budget.getMaxPromotedWorkersPerJob());
+
+        long testJobId = System.currentTimeMillis();
+        AtomicBoolean stop = new AtomicBoolean(false);
+        CopyOnWriteArrayList<Long> lagList = new CopyOnWriteArrayList<>();
+        List<Task> tasks = new ArrayList<>();
+        for (int i = 0; i < SLOW_TASK_COUNT; i++) {
+            tasks.add(
+                    new FixedCallTestTimeTask(
+                            SLOW_CALL_TIME_MILLIS, "slow-task-" + i, stop, 
lagList));
+        }
+
+        TaskGroupDefaultImpl taskGroup =
+                new TaskGroupDefaultImpl(
+                        new TaskGroupLocation(testJobId, 1, 1), 
"cooperative-budget", tasks);
+
+        PassiveCompletableFuture<TaskExecutionState> future =
+                deployLocalTask(taskExecutionService, taskGroup);
+
+        // The budget must deny promotions once the job holds its single 
promoted worker, and the
+        // tasks that were denied must keep running instead of being dropped.
+        await().atMost(30, TimeUnit.SECONDS)
+                .untilAsserted(
+                        () -> {
+                            assertTrue(budget.getDeniedPromotions() > 0);
+                            assertEquals(
+                                    MAX_PROMOTED_WORKERS_PER_JOB,
+                                    budget.getPromotedWorkers(testJobId));
+                        });
+
+        // Every task keeps making progress while the budget is exhausted, so 
the shared queue is
+        // still served: each task must be called more than once.
+        await().atMost(30, TimeUnit.SECONDS)
+                .untilAsserted(() -> assertTrue(lagList.size() >= 
SLOW_TASK_COUNT));

Review Comment:
   This does not prove that every task progresses. All eight 
FixedCallTestTimeTask instances append to the same lagList on every call after 
their first, and a promoted worker repeatedly executes its exclusive task. That 
one task can therefore make lagList.size() reach 8 while other tasks never 
start. This assertion masks the shared-queue starvation at 
TaskExecutionService.java:1477. Please use per-task invocation counters or 
latches and assert that every task starts or advances independently. The 
regression should include blocked denied calls plus a later queued readiness 
task.



##########
seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:
##########
@@ -1349,12 +1429,60 @@ public boolean runNewBusWork(boolean checkTaskQueue) {
                 BlockingQueue<Future<?>> futureBlockingQueue = new 
LinkedBlockingQueue<>();
                 CooperativeTaskWorker cooperativeTaskWorker =
                         new CooperativeTaskWorker(taskQueue, this, 
futureBlockingQueue);
-                Future<?> submit = 
executorService.submit(cooperativeTaskWorker);
+                sharedCooperativeWorkers.incrementAndGet();
+                Future<?> submit;
+                try {
+                    submit = executorService.submit(cooperativeTaskWorker);
+                } catch (RuntimeException e) {
+                    // The worker never runs, so it can never return its place 
itself.
+                    sharedCooperativeWorkers.decrementAndGet();
+                    throw e;
+                }
                 futureBlockingQueue.add(submit);
                 return true;
             }
             return false;
         }
+
+        /**
+         * Decides whether a worker running a slow task call may be promoted 
to an exclusive worker.
+         *
+         * <p>A promotion costs one worker thread: the current worker stays 
with the slow task and a
+         * replacement is started for the shared queue. The promotion is 
therefore admitted by
+         * {@link CooperativeWorkerBudget} first. When the budget is exhausted 
the worker keeps the
+         * slow task on the shared queue side and the caller retries later, 
except that a
+         * replacement is still started when this is the last worker serving 
the queue, so an
+         * exhausted budget can never stop queued tasks from reaching 
readiness.
+         *
+         * @param worker the worker that is executing the slow task call
+         * @param taskTracker the slow task
+         * @return true when the worker was promoted, false when the budget 
denied it
+         */
+        public boolean tryPromoteCooperativeWorker(
+                CooperativeTaskWorker worker, TaskTracker taskTracker) {
+            long jobId =
+                    taskTracker
+                            .taskGroupExecutionTracker
+                            .taskGroup
+                            .getTaskGroupLocation()
+                            .getJobId();
+            if (!cooperativeWorkerBudget.tryAcquire(jobId)) {
+                logger.fine(
+                        String.format(
+                                "Promotion of a cooperative worker for job %d 
was denied with reason BUDGET_EXHAUSTED, "
+                                        + "promoted workers: %d, denied 
promotions: %d",
+                                jobId,
+                                cooperativeWorkerBudget.getPromotedWorkers(),
+                                
cooperativeWorkerBudget.getDeniedPromotions()));
+                if (sharedCooperativeWorkers.get() <= 1) {

Review Comment:
   sharedCooperativeWorkers measures whether workers were promoted, not whether 
they are currently available to poll the shared queue. I reproduced the 
resulting starvation at this PR head with a per-job budget of 1 and four 
latch-blocked cooperative tasks: the first worker promoted, the second was 
denied and started a replacement, and that replacement took a third blocking 
task and was also denied. Both denied workers remained counted as shared, so 
the count was 2 even though neither could poll the queue. This condition 
refused another replacement, and the fourth task never started until a blocked 
call was released. If the blocked calls depend on later source, sink, or 
coordinator work reaching readiness, this becomes an indefinite deadlock. 
Making this check atomic would only prevent over-spawning; it would not correct 
the availability accounting. Please track workers actually available to poll 
the queue, or reserve/priority-route readiness work, and add a latch-based 
regression wh
 ere blocked calls cannot complete until a later queued task starts.



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

Reply via email to