From f676e23caea437e7f30d59cd62956cd0b9de4f98 Mon Sep 17 00:00:00 2001 From: Viren Baraiya Date: Fri, 27 Nov 2026 00:18:03 -0800 Subject: [PATCH 1/2] fix(client): TaskRunner keeps tasks leased to it at shutdown, and sends a refused update once - Shutdown waits for a poll in flight to return and hands its tasks to the executor, which still takes them. Before, the executor was shut down under the poll, its tasks were refused, and each waited out its response timeout on the server. A poll that is terminating the JVM (fatal auth) is not waited for: System.exit waits for the shutdown hooks. - With taskUpdateV2, a task finishing after shutdown began is sent with update, which hands nothing back; a task an update handed back as shutdown began, which the ended poll loop no longer takes, runs before shutdown returns. Before, both waited out their response timeout. - A 4xx update other than 408 or 429 is not retried: the same request is refused again, and each retry held a worker thread for 2 s. --- .../client/automator/TaskRunner.java | 149 +++++++--- .../automator/TaskRunnerShutdownTest.java | 254 ++++++++++++++++++ 2 files changed, 372 insertions(+), 31 deletions(-) create mode 100644 conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerShutdownTest.java diff --git a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java index e8b70f28b..059c685c9 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java +++ b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java @@ -58,6 +58,7 @@ import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; +import io.orkes.conductor.client.http.ApiException; import io.orkes.conductor.client.http.FatalAuthenticationException; import com.google.common.annotations.VisibleForTesting; @@ -79,6 +80,12 @@ class TaskRunner { private int pollingErrorCount; private String domain; private volatile boolean pollingAndExecuting = true; + /** Guards {@link #pollsInFlight}, and the end of {@link #pollingAndExecuting}. */ + private final Object pollLock = new Object(); + /** Polls whose tasks are not yet handed to the executor. */ + private int pollsInFlight; + /** Set when a poll is terminating the JVM: it never returns, and shutdown does not wait for it. */ + private volatile boolean exiting; private final List pollFilters; private final EventDispatcher eventDispatcher; private final LinkedBlockingQueue tasksTobeExecuted; @@ -175,7 +182,10 @@ public void pollAndExecute() { } try { - List tasks = pollTasksForWorker(); + List tasks = pollAndSubmit(); + if (tasks == null) { + break; // shutting down + } if (tasks.isEmpty()) { if (stopwatch == null) { stopwatch = Stopwatch.createStarted(); @@ -188,43 +198,107 @@ public void pollAndExecute() { LOGGER.trace("Poller for task {} waited for {} ms before getting {} tasks to execute", taskType, stopwatch.elapsed(TimeUnit.MILLISECONDS), tasks.size()); stopwatch = null; } - tasks.forEach(task -> { - Future taskFuture; - try { - taskFuture = this.executorService.submit(() -> this.processTask(task)); - } catch (java.util.concurrent.RejectedExecutionException e) { - LOGGER.error("Task rejected by executor (likely shutting down); dropping task {} of type {}", - task.getTaskId(), taskType, e); - permits.release(); - return; - } - - if (task.getResponseTimeoutSeconds() > 0 && worker.leaseExtendEnabled()) { - ScheduledFuture existingFuture = leaseExtendMap.remove(task.getTaskId()); - if (existingFuture != null) { - existingFuture.cancel(false); - } - - long delay = Math.round(task.getResponseTimeoutSeconds() * LEASE_EXTEND_DURATION_FACTOR); - ScheduledFuture leaseExtendFuture = leaseExtendExecutorService.scheduleWithFixedDelay( - extendLease(task, taskFuture), - delay, - delay, - TimeUnit.SECONDS - ); - leaseExtendMap.put(task.getTaskId(), leaseExtendFuture); - } - }); } catch (Throwable t) { LOGGER.error(t.getMessage(), t); } } } + /** + * Polls, and hands the tasks that come back to the executor: one step, which shutdown waits for + * ({@link #awaitPolls}). Null when the runner is shutting down. + */ + private List pollAndSubmit() { + synchronized (pollLock) { + if (!pollingAndExecuting) { + return null; + } + pollsInFlight++; + } + try { + List tasks = pollTasksForWorker(); + tasks.forEach(task -> { + if (!submit(task)) { + permits.release(); + } + }); + return tasks; + } finally { + synchronized (pollLock) { + pollsInFlight--; + pollLock.notifyAll(); + } + } + } + + /** Runs a task on the executor, under a permit the caller holds. False when the executor refused it: the permit is then the caller's to release. */ + private boolean submit(Task task) { + Future taskFuture; + try { + taskFuture = this.executorService.submit(() -> this.processTask(task)); + } catch (java.util.concurrent.RejectedExecutionException e) { + LOGGER.error("Task rejected by executor (likely shutting down); dropping task {} of type {}", + task.getTaskId(), taskType, e); + return false; + } + + if (task.getResponseTimeoutSeconds() > 0 && worker.leaseExtendEnabled()) { + ScheduledFuture existingFuture = leaseExtendMap.remove(task.getTaskId()); + if (existingFuture != null) { + existingFuture.cancel(false); + } + + long delay = Math.round(task.getResponseTimeoutSeconds() * LEASE_EXTEND_DURATION_FACTOR); + ScheduledFuture leaseExtendFuture = leaseExtendExecutorService.scheduleWithFixedDelay( + extendLease(task, taskFuture), + delay, + delay, + TimeUnit.SECONDS + ); + leaseExtendMap.put(task.getTaskId(), leaseExtendFuture); + } + return true; + } + + /** + * Waits, at most {@code timeout} seconds, for a poll in flight to return and its tasks to be + * handed to the executor, which must still take them: the server has leased them to this + * worker, and refused, they would wait out their response timeout. + */ + private void awaitPolls(int timeout) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout); + synchronized (pollLock) { + while (pollsInFlight > 0 && !exiting) { + long millis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + if (millis <= 0) { + LOGGER.warn("A poll for {} did not return within {} seconds", taskType, timeout); + return; + } + pollLock.wait(millis); + } + } + } + + /** + * Runs the tasks update-v2 handed back that the poll loop, now ended, did not take: the server + * has leased them to this worker, so left alone they would wait out their response timeout. + * Their results go with the update that hands nothing back. + */ + private void runHandedBackTasks() { + for (Task task; (task = tasksTobeExecuted.poll()) != null; ) { + LOGGER.info("Shutting down: running task {} of type {}, handed back by an update", task.getTaskId(), taskType); + task.getExecutionMetadata().setClientReceiveTime(System.currentTimeMillis()); + processTask(task); // the permit it releases no longer matters: nothing polls + } + } + public void shutdown(int timeout) { try { - pollingAndExecuting = false; - + synchronized (pollLock) { + pollingAndExecuting = false; // no poll starts after this + } + awaitPolls(timeout); + leaseExtendMap.values().forEach(future -> future.cancel(false)); leaseExtendMap.clear(); @@ -237,6 +311,7 @@ public void shutdown(int timeout) { executorService.shutdown(); if (executorService.awaitTermination(timeout, TimeUnit.SECONDS)) { LOGGER.debug("tasks completed, shutting down"); + runHandedBackTasks(); } else { LOGGER.warn(String.format("forcing shutdown after waiting for %s second", timeout)); executorService.shutdownNow(); @@ -297,6 +372,7 @@ private List pollTasksForWorker() { if (hasFatalAuthCause(e)) { LOGGER.error("Fatal authentication failure — terminating JVM"); + exiting = true; // a shutdown hook must not wait for this thread, which waits for the hooks exitAction.run(); } @@ -475,7 +551,8 @@ private void updateTaskResult(int count, Task task, TaskResult result, Worker wo result.getExecutionMetadata().setClientSendTime(clientSendTime); LOGGER.debug("Task {} outbound send time: {}", task.getTaskId(), clientSendTime); - if(enableUpdateV2) { + // update-v2 hands back the next task, which only a running poll loop takes + if(enableUpdateV2 && pollingAndExecuting) { Task nextTask = retryOperation( (TaskResult taskResult) -> taskClient.updateTaskV2(taskResult, taskType), count, @@ -540,6 +617,9 @@ private R retryOperation(Function operation, int count, T input, St return operation.apply(input); } catch (Exception e) { LOGGER.error("Error executing {}", opName, e); + if (refused(e)) { + throw e; // the same request is refused again: retrying cannot help + } index++; Uninterruptibles.sleepUninterruptibly(500L * (count + 1), TimeUnit.MILLISECONDS); } @@ -547,6 +627,13 @@ private R retryOperation(Function operation, int count, T input, St throw new RuntimeException("Exhausted retries performing " + opName); } + /** A client error other than a timeout (408) or throttling (429). */ + private static boolean refused(Exception e) { + return e instanceof ApiException api + && api.getStatusCode() >= 400 && api.getStatusCode() < 500 + && api.getStatusCode() != 408 && api.getStatusCode() != 429; + } + private void handleException(Throwable t, TaskResult result, Worker worker, Task task) { LOGGER.error(String.format("Error while executing task %s", task.toString()), t); result.setStatus(TaskResult.Status.FAILED); diff --git a/conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerShutdownTest.java b/conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerShutdownTest.java new file mode 100644 index 000000000..108d756d3 --- /dev/null +++ b/conductor-client/src/test/java/com/netflix/conductor/client/automator/TaskRunnerShutdownTest.java @@ -0,0 +1,254 @@ +/* + * Copyright 2026 Conductor Authors. + *

+ * Licensed 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 com.netflix.conductor.client.automator; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import com.netflix.conductor.client.events.dispatcher.EventDispatcher; +import com.netflix.conductor.client.events.taskrunner.TaskRunnerEvent; +import com.netflix.conductor.client.exception.ConductorClientException; +import com.netflix.conductor.client.http.TaskClient; +import com.netflix.conductor.client.worker.Worker; +import com.netflix.conductor.common.metadata.tasks.Task; +import com.netflix.conductor.common.metadata.tasks.TaskResult; + +import io.orkes.conductor.client.http.FatalAuthenticationException; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.after; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * What a runner does with work the server has leased to it when the runner shuts down, and with an + * update the server refuses. + */ +class TaskRunnerShutdownTest { + + private TaskRunner runner; + + @AfterEach + void tearDown() { + System.clearProperty("taskUpdateV2"); + if (runner != null) { + runner.shutdown(1); + } + } + + private static Task task(String id) { + Task task = new Task(); + task.setTaskId(id); + task.setTaskDefName("test_task"); + task.setWorkflowInstanceId("wf"); + task.setStatus(Task.Status.IN_PROGRESS); + return task; + } + + private static Worker worker() { + Worker worker = mock(Worker.class); + when(worker.getTaskDefName()).thenReturn("test_task"); + when(worker.getPollingInterval()).thenReturn(10); + when(worker.getIdentity()).thenReturn("w"); + when(worker.execute(any())).thenAnswer(i -> { + TaskResult result = new TaskResult(i.getArgument(0)); + result.setStatus(TaskResult.Status.COMPLETED); + return result; + }); + return worker; + } + + private static TaskClient client() { + TaskClient client = mock(TaskClient.class); + when(client.evaluateAndUploadLargePayload(any(), any())).thenReturn(Optional.empty()); + return client; + } + + private void run(Worker worker, TaskClient client) { + run(worker, client, () -> {}); + } + + @SuppressWarnings("unchecked") + private void run(Worker worker, TaskClient client, Runnable exitAction) { + runner = new TaskRunner(worker, client, 3, Map.of(), "test-%d", 2, 100, List.of(), + (EventDispatcher) mock(EventDispatcher.class), false); + runner.setExitAction(exitAction); // never System.exit in a test + Thread poller = new Thread(runner::pollAndExecute); + poller.setDaemon(true); + poller.start(); + } + + private void shutDownWhile(CountDownLatch inFlight, CountDownLatch answer) throws InterruptedException { + inFlight.await(); + Thread stopping = new Thread(() -> runner.shutdown(5)); + stopping.start(); + Thread.sleep(500); + answer.countDown(); + stopping.join(); + } + + @Test + void aRefusedUpdateIsSentOnce() { + TaskClient client = client(); + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(task("t1")), List.of()); + updateFailsOnce(client, new ConductorClientException(404, "no such task")); + + run(worker(), client); + + // the same request is refused again: a retry, 2 s later, cannot help + verify(client, after(2500).times(1)).updateTask(any(), any()); + } + + @Test + void aThrottledUpdateIsRetried() { + TaskClient client = client(); + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(task("t1")), List.of()); + updateFailsOnce(client, new ConductorClientException(429, "slow down")); + + run(worker(), client); + + verify(client, timeout(3000).times(2)).updateTask(any(), any()); + } + + private static void updateFailsOnce(TaskClient client, RuntimeException failure) { + doThrow(failure).doNothing().when(client).updateTask(any(), any()); + } + + @Test + void theTasksOfAPollInFlightWhenShutdownBeginsStillRun() throws Exception { + Task first = task("t1"); + CountDownLatch polling = new CountDownLatch(1); + CountDownLatch answer = new CountDownLatch(1); + TaskClient client = client(); + // the poll is on its way when shutdown begins; the server answers it with a task, leased + // to this worker + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenAnswer(i -> { + polling.countDown(); + answer.await(); + return List.of(first); + }) + .thenReturn(List.of()); + Worker worker = worker(); + + run(worker, client); + shutDownWhile(polling, answer); + + verify(worker).execute(first); + verify(client).updateTask(any(), any()); + } + + @Test + void shutdownDoesNotWaitForAPollLoopThatIsTerminatingTheJvm() throws Exception { + CountDownLatch exiting = new CountDownLatch(1); + CountDownLatch exited = new CountDownLatch(1); + TaskClient client = client(); + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenThrow(new FatalAuthenticationException("revoked")); + + // System.exit runs the shutdown hooks, one of which shuts this runner down, and returns + // only when they are done + run(worker(), client, () -> { + exiting.countDown(); + try { + exited.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + exiting.await(); + long start = System.nanoTime(); + runner.shutdown(5); + long millis = (System.nanoTime() - start) / 1_000_000; + exited.countDown(); + + assertTrue(millis < 2000, "shutdown waited " + millis + " ms for a poll loop in System.exit"); + } + + @Test + void withUpdateV2ATaskFinishingDuringShutdownTakesNoNextTask() throws Exception { + System.setProperty("taskUpdateV2", "true"); + Task first = task("t1"); + Task next = task("t2"); + CountDownLatch running = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + TaskClient client = client(); + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first), List.of()); + // the server leases the next task to whoever completes with update-v2 + when(client.updateTaskV2(any(), any())).thenReturn(next, (Task) null); + Worker worker = worker(); + when(worker.execute(first)).thenAnswer(i -> { + running.countDown(); + finish.await(); + TaskResult result = new TaskResult(first); + result.setStatus(TaskResult.Status.COMPLETED); + return result; + }); + + run(worker, client); + shutDownWhile(running, finish); + + // the poll loop has ended and takes no task handed back now: the result goes with the + // update that hands nothing back + verify(client, never()).updateTaskV2(any(), any()); + verify(client).updateTask(any(), any()); + verify(worker, never()).execute(next); + } + + @Test + void withUpdateV2ATaskHandedBackAsShutdownBeginsStillRuns() throws Exception { + System.setProperty("taskUpdateV2", "true"); + Task first = task("t1"); + Task next = task("t2"); + CountDownLatch updating = new CountDownLatch(1); + CountDownLatch answer = new CountDownLatch(1); + TaskClient client = client(); + when(client.batchPollTasksInDomain(eq("test_task"), isNull(), anyString(), anyInt(), anyInt())) + .thenReturn(List.of(first), List.of()); + // the first task's update is on its way when shutdown begins; the server answers it with + // the next task, leased to this worker + when(client.updateTaskV2(any(), any())).thenAnswer(i -> { + updating.countDown(); + answer.await(); + return next; + }); + Worker worker = worker(); + + run(worker, client); + shutDownWhile(updating, answer); + + // it runs before shutdown returns; its own result goes with the update that hands nothing + // back + verify(worker).execute(next); + verify(client, times(1)).updateTaskV2(any(), any()); + verify(client).updateTask(any(), any()); + } +} From 34da181e7a5300916bcf5a546b4b4fe863cadec7 Mon Sep 17 00:00:00 2001 From: Viren Baraiya Date: Fri, 27 Nov 2026 00:30:19 -0800 Subject: [PATCH 2/2] refactor(client): count polls in flight with an AtomicInteger, no lock --- .../client/automator/TaskRunner.java | 36 +++++++------------ 1 file changed, 13 insertions(+), 23 deletions(-) diff --git a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java index 059c685c9..d93e52586 100644 --- a/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java +++ b/conductor-client/src/main/java/com/netflix/conductor/client/automator/TaskRunner.java @@ -80,10 +80,8 @@ class TaskRunner { private int pollingErrorCount; private String domain; private volatile boolean pollingAndExecuting = true; - /** Guards {@link #pollsInFlight}, and the end of {@link #pollingAndExecuting}. */ - private final Object pollLock = new Object(); - /** Polls whose tasks are not yet handed to the executor. */ - private int pollsInFlight; + /** Polls whose tasks are not yet handed to the executor; shutdown waits for them. */ + private final AtomicInteger pollsInFlight = new AtomicInteger(); /** Set when a poll is terminating the JVM: it never returns, and shutdown does not wait for it. */ private volatile boolean exiting; private final List pollFilters; @@ -209,13 +207,13 @@ public void pollAndExecute() { * ({@link #awaitPolls}). Null when the runner is shutting down. */ private List pollAndSubmit() { - synchronized (pollLock) { + pollsInFlight.incrementAndGet(); + try { + // checked once this poll is counted: shutdown stops polling, then waits for the polls + // it counts, so a poll either sees the stop or is waited for if (!pollingAndExecuting) { return null; } - pollsInFlight++; - } - try { List tasks = pollTasksForWorker(); tasks.forEach(task -> { if (!submit(task)) { @@ -224,10 +222,7 @@ private List pollAndSubmit() { }); return tasks; } finally { - synchronized (pollLock) { - pollsInFlight--; - pollLock.notifyAll(); - } + pollsInFlight.decrementAndGet(); } } @@ -267,15 +262,12 @@ private boolean submit(Task task) { */ private void awaitPolls(int timeout) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeout); - synchronized (pollLock) { - while (pollsInFlight > 0 && !exiting) { - long millis = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); - if (millis <= 0) { - LOGGER.warn("A poll for {} did not return within {} seconds", taskType, timeout); - return; - } - pollLock.wait(millis); + while (pollsInFlight.get() > 0 && !exiting) { + if (System.nanoTime() - deadline > 0) { + LOGGER.warn("A poll for {} did not return within {} seconds", taskType, timeout); + return; } + Thread.sleep(10); } } @@ -294,9 +286,7 @@ private void runHandedBackTasks() { public void shutdown(int timeout) { try { - synchronized (pollLock) { - pollingAndExecuting = false; // no poll starts after this - } + pollingAndExecuting = false; awaitPolls(timeout); leaseExtendMap.values().forEach(future -> future.cancel(false));