You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by da...@apache.org on 2026/10/06 16:21:32 UTC

(kafka) branch 4.3 updated: KAFKA-21196: Release memory held by cancelled CoordinatorExecutorImpl tasks (4.3) (#23677)

This is an automated email from the ASF dual-hosted git repository.

dajac pushed a commit to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git


The following commit(s) were added to refs/heads/4.3 by this push:
     new 4c43cedf1cc KAFKA-21196: Release memory held by cancelled CoordinatorExecutorImpl tasks (4.3) (#23677)
4c43cedf1cc is described below

commit 4c43cedf1ccdcbb5c09cfeb8c94dcb038dd6818d
Author: David Jacot <da...@apache.org>
AuthorDate: Tue Oct 6 18:21:24 2026 +0200

    KAFKA-21196: Release memory held by cancelled CoordinatorExecutorImpl tasks (4.3) (#23677)
    
    When a `CoordinatorExecutorImpl` task is cancelled, it remains in the
    executor queue or in the event processor queue until it is processed and
    it retains its runnable, its operation and the result of its runnable in
    the meantime. When the group coordinator is overloaded, these queues can
    grow large and retain data structures that are no longer needed, e.g.
    the metadata image captured by the regular expression resolution.
    
    This patch boxes the runnable, the operation and the result in a `Task`
    object which releases them when the task is cancelled. The operation and
    the result are also released once the operation is executed because the
    write event is retained until its records are committed.
    
    Reviewers: Sean Quah <sq...@confluent.io>
---
 .../common/runtime/CoordinatorExecutorImpl.java    | 212 ++++++++++++++++-----
 .../runtime/CoordinatorExecutorImplTest.java       |  88 ++++++++-
 2 files changed, 249 insertions(+), 51 deletions(-)

diff --git a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImpl.java b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImpl.java
index 31aeebee30a..84338e3b3ea 100644
--- a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImpl.java
+++ b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImpl.java
@@ -31,60 +31,53 @@ import java.util.concurrent.RejectedExecutionException;
 public class CoordinatorExecutorImpl<U> implements CoordinatorExecutor<U> {
     private record TaskResult<R>(R result, Throwable exception) { }
 
-    private final Logger log;
-    private final ExecutorService executor;
-    private final CoordinatorShardScheduler<U> scheduler;
-    private final Map<String, TaskRunnable<?>> tasks = new ConcurrentHashMap<>();
-
-    public CoordinatorExecutorImpl(
-        LogContext logContext,
-        ExecutorService executor,
-        CoordinatorShardScheduler<U> scheduler
-    ) {
-        this.log = logContext.logger(CoordinatorExecutorImpl.class);
-        this.executor = executor;
-        this.scheduler = scheduler;
-    }
-
-    private <R> TaskResult<R> executeTask(TaskRunnable<R> task) {
-        try {
-            return new TaskResult<>(task.run(), null);
-        } catch (Throwable ex) {
-            return new TaskResult<>(null, ex);
+    /**
+     * A scheduled task. The task holds its runnable, its operation and the result of
+     * the runnable only while they are needed. The runnable is released when it is
+     * executed, and the operation and the result are released when the operation is
+     * executed. All of them are released when the task is cancelled because the task
+     * may remain in the executor queue or in the event processor queue long after its
+     * cancellation.
+     *
+     * @param <R> The return type of the task.
+     */
+    class Task<R> {
+        private final String key;
+        private TaskRunnable<R> runnable;
+        private TaskOperation<U, R> operation;
+        private TaskResult<R> result;
+
+        Task(
+            String key,
+            TaskRunnable<R> runnable,
+            TaskOperation<U, R> operation
+        ) {
+            this.key = key;
+            this.runnable = runnable;
+            this.operation = operation;
         }
-    }
-
-    @Override
-    public <R> boolean schedule(
-        String key,
-        TaskRunnable<R> task,
-        TaskOperation<U, R> operation
-    ) {
-        // Put the task if the key is free. Otherwise, reject it.
-        if (tasks.putIfAbsent(key, task) != null) return false;
 
-        // Submit the task.
-        executor.submit(() -> {
+        /**
+         * Executes the runnable and schedules the write operation to handle its result.
+         * This is called by the executor.
+         */
+        private void run() {
             // If the task associated with the key is not us, it means
             // that the task was either replaced or cancelled. We stop.
-            if (tasks.get(key) != task) return;
+            if (tasks.get(key) != this) return;
 
-            // Execute the task.
-            var result = executeTask(task);
+            // The runnable is null if the task was cancelled in the meantime.
+            var runnable = takeRunnable();
+            if (runnable == null) return;
+
+            // Execute the task. The result is not stored if the task
+            // was cancelled while it was running.
+            if (!maybeSetResult(executeTask(runnable))) return;
 
             // Schedule the operation.
             scheduler.scheduleWriteOperation(
                 key,
-                () -> {
-                    // If the task associated with the key is not us, it means
-                    // that the task was either replaced or cancelled. We stop.
-                    if (!tasks.remove(key, task)) {
-                        throw new RejectedExecutionException(String.format("Task %s was overridden or cancelled", key));
-                    }
-
-                    // Call the underlying write operation with the result of the task.
-                    return operation.onComplete(result.result(), result.exception());
-                }
+                this::complete
             ).exceptionally(exception -> {
                 // Exceptions may be wrapped in CompletionException when propagated
                 // through CompletableFuture chains, so we unwrap them before
@@ -92,7 +85,7 @@ public class CoordinatorExecutorImpl<U> implements CoordinatorExecutor<U> {
                 exception = Errors.maybeUnwrapException(exception);
 
                 // Remove the task after a failure.
-                tasks.remove(key, task);
+                if (tasks.remove(key, this)) cancel();
 
                 if (exception instanceof RejectedExecutionException) {
                     log.debug("The write event for the task {} was not executed because it was " +
@@ -107,7 +100,116 @@ public class CoordinatorExecutorImpl<U> implements CoordinatorExecutor<U> {
 
                 return null;
             });
-        });
+        }
+
+        /**
+         * Calls the operation with the result of the runnable. This is called by
+         * the write operation scheduled in the runtime.
+         */
+        private CoordinatorResult<Void, U> complete() {
+            // If the task associated with the key is not us, it means
+            // that the task was either replaced or cancelled. We stop.
+            if (!tasks.remove(key, this)) {
+                throw new RejectedExecutionException(String.format("Task %s was overridden or cancelled", key));
+            }
+
+            // The task cannot be cancelled anymore because it is no longer
+            // in the map. The operation and the result are released because
+            // the write operation is retained until its records are committed.
+            TaskOperation<U, R> operation;
+            TaskResult<R> result;
+            synchronized (this) {
+                operation = this.operation;
+                result = this.result;
+                this.operation = null;
+                this.result = null;
+            }
+
+            // Call the underlying write operation with the result of the task.
+            return operation.onComplete(result.result(), result.exception());
+        }
+
+        /**
+         * Takes the runnable and releases it.
+         *
+         * @return The runnable or null if the task was cancelled.
+         */
+        private synchronized TaskRunnable<R> takeRunnable() {
+            var runnable = this.runnable;
+            this.runnable = null;
+            return runnable;
+        }
+
+        /**
+         * Stores the result of the runnable unless the task was cancelled.
+         *
+         * @param result The result of the runnable.
+         * @return True if the result was stored; False if the task was cancelled.
+         */
+        private synchronized boolean maybeSetResult(TaskResult<R> result) {
+            if (operation == null) return false;
+            this.result = result;
+            return true;
+        }
+
+        /**
+         * Releases the runnable, the operation and the result. The caller must
+         * remove the task from the map beforehand.
+         */
+        private synchronized void cancel() {
+            runnable = null;
+            operation = null;
+            result = null;
+        }
+
+        /**
+         * Return true if the runnable, the operation and the result are released.
+         * Visible for testing.
+         */
+        synchronized boolean isReleased() {
+            return runnable == null && operation == null && result == null;
+        }
+    }
+
+    private final Logger log;
+    private final ExecutorService executor;
+    private final CoordinatorShardScheduler<U> scheduler;
+    private final Map<String, Task<?>> tasks = new ConcurrentHashMap<>();
+
+    public CoordinatorExecutorImpl(
+        LogContext logContext,
+        ExecutorService executor,
+        CoordinatorShardScheduler<U> scheduler
+    ) {
+        this.log = logContext.logger(CoordinatorExecutorImpl.class);
+        this.executor = executor;
+        this.scheduler = scheduler;
+    }
+
+    /**
+     * Executes the runnable and captures its result or its exception.
+     */
+    private <R> TaskResult<R> executeTask(TaskRunnable<R> runnable) {
+        try {
+            return new TaskResult<>(runnable.run(), null);
+        } catch (Throwable ex) {
+            return new TaskResult<>(null, ex);
+        }
+    }
+
+    @Override
+    public <R> boolean schedule(
+        String key,
+        TaskRunnable<R> runnable,
+        TaskOperation<U, R> operation
+    ) {
+        var task = new Task<>(key, runnable, operation);
+
+        // Put the task if the key is free. Otherwise, reject it.
+        if (tasks.putIfAbsent(key, task) != null) return false;
+
+        // Submit the task.
+        executor.submit(task::run);
 
         return true;
     }
@@ -119,10 +221,22 @@ public class CoordinatorExecutorImpl<U> implements CoordinatorExecutor<U> {
 
     @Override
     public void cancel(String key) {
-        tasks.remove(key);
+        var task = tasks.remove(key);
+        if (task != null) task.cancel();
     }
 
+    /**
+     * Cancels all the tasks.
+     */
     public void cancelAll() {
-        tasks.clear();
+        tasks.keySet().forEach(this::cancel);
+    }
+
+    /**
+     * Return the task associated with the key or null if there is none.
+     * Visible for testing.
+     */
+    Task<?> task(String key) {
+        return tasks.get(key);
     }
 }
diff --git a/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImplTest.java b/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImplTest.java
index da0f4697c51..58af1828eb8 100644
--- a/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImplTest.java
+++ b/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutorImplTest.java
@@ -27,6 +27,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -38,6 +39,8 @@ import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 // Creating mocks of classes using generics creates unsafe assignment.
@@ -69,8 +72,10 @@ public class CoordinatorExecutorImplTest {
             return CompletableFuture.completedFuture(null);
         });
 
+        AtomicReference<CoordinatorExecutorImpl<String>.Task<?>> task = new AtomicReference<>();
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
             assertTrue(executor.isScheduled(TASK_KEY));
+            task.set(executor.task(TASK_KEY));
             Runnable op = args.getArgument(0);
             op.run();
             return CompletableFuture.completedFuture(null);
@@ -98,6 +103,8 @@ public class CoordinatorExecutorImplTest {
 
         assertTrue(taskCalled.get());
         assertTrue(operationCalled.get());
+        assertFalse(executor.isScheduled(TASK_KEY));
+        assertTrue(task.get().isReleased());
     }
 
     @Test
@@ -122,7 +129,9 @@ public class CoordinatorExecutorImplTest {
             return CompletableFuture.completedFuture(null);
         });
 
+        AtomicReference<CoordinatorExecutorImpl<String>.Task<?>> task = new AtomicReference<>();
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
+            task.set(executor.task(TASK_KEY));
             Runnable op = args.getArgument(0);
             op.run();
             return CompletableFuture.completedFuture(null);
@@ -151,6 +160,8 @@ public class CoordinatorExecutorImplTest {
 
         assertTrue(taskCalled.get());
         assertTrue(operationCalled.get());
+        assertFalse(executor.isScheduled(TASK_KEY));
+        assertTrue(task.get().isReleased());
     }
 
     @Test
@@ -164,8 +175,13 @@ public class CoordinatorExecutorImplTest {
         );
 
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
-            // Cancel the task before running it.
+            CoordinatorExecutorImpl<String>.Task<?> task = executor.task(TASK_KEY);
+            assertFalse(task.isReleased());
+
+            // Cancel the task before running it. The task must
+            // release its runnable and its operation.
             executor.cancel(TASK_KEY);
+            assertTrue(task.isReleased());
 
             // Running the task.
             Runnable op = args.getArgument(0);
@@ -193,6 +209,54 @@ public class CoordinatorExecutorImplTest {
 
         assertFalse(taskCalled.get());
         assertFalse(operationCalled.get());
+        verify(scheduler, never()).scheduleWriteOperation(anyString(), any());
+    }
+
+    @Test
+    public void testTaskCancelledWhileBeingExecuted() {
+        CoordinatorShardScheduler<String> scheduler = mock(CoordinatorShardScheduler.class);
+        ExecutorService executorService = mock(ExecutorService.class);
+        CoordinatorExecutorImpl<String> executor = new CoordinatorExecutorImpl<>(
+            LOG_CONTEXT,
+            executorService,
+            scheduler
+        );
+
+        AtomicReference<CoordinatorExecutorImpl<String>.Task<?>> task = new AtomicReference<>();
+        when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
+            task.set(executor.task(TASK_KEY));
+            Runnable op = args.getArgument(0);
+            op.run();
+            return CompletableFuture.completedFuture(null);
+        });
+
+        AtomicBoolean taskCalled = new AtomicBoolean(false);
+        CoordinatorExecutor.TaskRunnable<String> taskRunnable = () -> {
+            taskCalled.set(true);
+            // Cancel the task while it is running.
+            executor.cancel(TASK_KEY);
+            return "Hello!";
+        };
+
+        AtomicBoolean operationCalled = new AtomicBoolean(false);
+        CoordinatorExecutor.TaskOperation<String, String> taskOperation = (result, exception) -> {
+            operationCalled.set(true);
+            return null;
+        };
+
+        executor.schedule(
+            TASK_KEY,
+            taskRunnable,
+            taskOperation
+        );
+
+        // The result of the task is dropped and the write
+        // operation is not scheduled.
+        assertTrue(taskCalled.get());
+        assertFalse(operationCalled.get());
+        assertFalse(executor.isScheduled(TASK_KEY));
+        assertTrue(task.get().isReleased());
+        verify(scheduler, never()).scheduleWriteOperation(anyString(), any());
     }
 
     @Test
@@ -205,12 +269,17 @@ public class CoordinatorExecutorImplTest {
             scheduler
         );
 
+        AtomicReference<CoordinatorExecutorImpl<String>.Task<?>> task = new AtomicReference<>();
         when(scheduler.scheduleWriteOperation(
             eq(TASK_KEY),
             any()
         )).thenAnswer(args -> {
-            // Cancel the task before running the write operation.
+            assertFalse(task.get().isReleased());
+
+            // Cancel the task before running the write operation. The task
+            // must release its operation and the result of its runnable.
             executor.cancel(TASK_KEY);
+            assertTrue(task.get().isReleased());
 
             CoordinatorShardScheduler.WriteOperation<String> op = args.getArgument(1);
             Throwable ex = assertThrows(RejectedExecutionException.class, op::generate);
@@ -218,6 +287,7 @@ public class CoordinatorExecutorImplTest {
         });
 
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
+            task.set(executor.task(TASK_KEY));
             Runnable op = args.getArgument(0);
             op.run();
             return CompletableFuture.completedFuture(null);
@@ -260,7 +330,9 @@ public class CoordinatorExecutorImplTest {
             any()
         )).thenReturn(CompletableFuture.failedFuture(new Throwable("Oh no!")));
 
+        AtomicReference<CoordinatorExecutorImpl<String>.Task<?>> task = new AtomicReference<>();
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
+            task.set(executor.task(TASK_KEY));
             Runnable op = args.getArgument(0);
             op.run();
             return CompletableFuture.completedFuture(null);
@@ -287,6 +359,7 @@ public class CoordinatorExecutorImplTest {
         assertTrue(taskCalled.get());
         assertFalse(operationCalled.get());
         assertFalse(executor.isScheduled(TASK_KEY));
+        assertTrue(task.get().isReleased());
     }
 
     @Test
@@ -311,7 +384,9 @@ public class CoordinatorExecutorImplTest {
             return writeFuture;
         });
 
+        List<CoordinatorExecutorImpl<String>.Task<?>> tasks = new ArrayList<>();
         when(executorService.submit(any(Runnable.class))).thenAnswer(args -> {
+            tasks.add(executor.task(TASK_KEY + tasks.size()));
             Runnable op = args.getArgument(0);
             op.run();
             return CompletableFuture.completedFuture(null);
@@ -337,8 +412,17 @@ public class CoordinatorExecutorImplTest {
             );
         }
 
+        assertEquals(2, tasks.size());
+        tasks.forEach(task -> assertFalse(task.isReleased()));
+
         executor.cancelAll();
 
+        // All the tasks are cancelled and released.
+        for (int i = 0; i < 2; i++) {
+            assertFalse(executor.isScheduled(TASK_KEY + i));
+        }
+        tasks.forEach(task -> assertTrue(task.isReleased()));
+
         for (int i = 0; i < writeOperations.size(); i++) {
             CoordinatorShardScheduler.WriteOperation<String> writeOperation = writeOperations.get(i);
             CompletableFuture<Void> writeFuture = writeFutures.get(i);