You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2026/10/22 23:26:33 UTC

(pulsar) branch master updated: [fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)

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

merlimat pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pulsar.git


The following commit(s) were added to refs/heads/master by this push:
     new aeaf47e5458a [fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)
aeaf47e5458a is described below

commit aeaf47e5458af76c900e3dccbbe9ac1a575f2750
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 23 02:26:26 2026 +0300

    [fix][ml] Run the add-entry timeout check on the managed ledger executor (#27056)
---
 .../bookkeeper/mledger/impl/ManagedLedgerImpl.java | 14 ++++-
 .../bookkeeper/mledger/impl/ManagedLedgerTest.java | 72 ++++++++++++++++++++++
 2 files changed, 85 insertions(+), 1 deletion(-)

diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
index 643afc6a4ebd..b26fed3e4d45 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerImpl.java
@@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
 import static java.lang.Math.min;
 import static org.apache.bookkeeper.mledger.util.Errors.isNoSuchLedgerExistsException;
+import static org.apache.pulsar.common.util.Runnables.catchingAndLoggingThrowables;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.BoundType;
 import com.google.common.collect.Lists;
@@ -5460,10 +5461,21 @@ public class ManagedLedgerImpl implements ManagedLedger, CreateCallback {
         if (config.getAddEntryTimeoutSeconds() > 0) {
             long timeoutSec = config.getAddEntryTimeoutSeconds();
             this.timeoutTask = this.scheduledExecutor.scheduleAtFixedRate(
-                    this::checkAddTimeout, timeoutSec, timeoutSec, TimeUnit.SECONDS);
+                    catchingAndLoggingThrowables(this::scheduleAddTimeoutCheck), timeoutSec, timeoutSec,
+                    TimeUnit.SECONDS);
         }
     }
 
+    /**
+     * Runs the add timeout check on the managed ledger executor. The pending adds complete and get recycled on that
+     * executor, so checking the head of the queue from the scheduler thread could read a recycled, possibly reused,
+     * OpAddEntry. An exception must not escape to the scheduler, or the periodic check would stop for good.
+     */
+    @VisibleForTesting
+    void scheduleAddTimeoutCheck() {
+        executor.execute(catchingAndLoggingThrowables(this::checkAddTimeout));
+    }
+
     private void checkAddTimeout() {
         final State state = STATE_UPDATER.get(this);
         if (state == State.Closed
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
index c1017299783c..da6129044abc 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
@@ -4103,6 +4103,78 @@ public class ManagedLedgerTest extends MockedBookKeeperTestCase {
         factory.delete(ledger.name);
     }
 
+    /**
+     * The add timeout check runs on the managed ledger executor, after the add completions already queued there. The
+     * check must not act on an add that has completed: once its completion runs, the add is recycled and may be
+     * reused by another add, possibly of another managed ledger.
+     */
+    @Test(timeOut = 30000)
+    public void testAddTimeoutCheckRunsAfterQueuedAddCompletion() throws Exception {
+        // A timeout this long keeps the periodic check from running by itself: the test triggers it.
+        ManagedLedgerConfig config = initManagedLedgerConfig(defaultConfig()).setAddEntryTimeoutSeconds(3600);
+        ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("add_timeout_check_after_completion", config);
+
+        // Hold the bookie's add response, to deliver it at a chosen moment.
+        record BookieAdd(AddCallback callback, Object ctx) {
+        }
+        CompletableFuture<BookieAdd> bookieAdd = new CompletableFuture<>();
+        LedgerHandle spyLedger = spy(ledger.currentLedger);
+        doAnswer(invocation -> {
+            ((ByteBuf) invocation.getArgument(0)).release();
+            bookieAdd.complete(new BookieAdd(invocation.getArgument(1), invocation.getArgument(2)));
+            return null;
+        }).when(spyLedger).asyncAddEntry(any(ByteBuf.class), any(AddCallback.class), any());
+        ledger.currentLedger = spyLedger;
+
+        CompletableFuture<Position> addResult = new CompletableFuture<>();
+        ledger.asyncAddEntry("entry".getBytes(UTF_8), new AddEntryCallback() {
+            @Override
+            public void addComplete(Position position, ByteBuf entryData, Object ctx) {
+                addResult.complete(position);
+            }
+
+            @Override
+            public void addFailed(ManagedLedgerException exception, Object ctx) {
+                addResult.completeExceptionally(exception);
+            }
+        }, null);
+        BookieAdd pendingBookieAdd = bookieAdd.get(10, TimeUnit.SECONDS);
+        OpAddEntry op = ledger.pendingAddEntries.peek();
+        assertThat(op).isNotNull();
+        // Make the add older than the timeout.
+        op.lastInitTime = System.nanoTime() - TimeUnit.HOURS.toNanos(2);
+
+        CountDownLatch executorBlocked = new CountDownLatch(1);
+        CountDownLatch releaseExecutor = new CountDownLatch(1);
+        ledger.getExecutor().execute(() -> {
+            executorBlocked.countDown();
+            try {
+                releaseExecutor.await();
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            }
+        });
+        assertThat(executorBlocked.await(10, TimeUnit.SECONDS)).isTrue();
+        try {
+            // The bookie confirms the add, whose completion queues on the managed ledger executor...
+            pendingBookieAdd.callback().addComplete(BKException.Code.OK, spyLedger, 0, pendingBookieAdd.ctx());
+            // ...and the periodic timeout check fires before that completion has run.
+            ledger.scheduleAddTimeoutCheck();
+            assertThat(ledger.currentLedgerTimeoutTriggered)
+                    .as("timeout applied to an add whose completion is queued")
+                    .isFalse();
+        } finally {
+            releaseExecutor.countDown();
+        }
+
+        assertThat(addResult.get(10, TimeUnit.SECONDS)).isEqualTo(PositionFactory.create(spyLedger.getId(), 0));
+        // Wait for the timeout check queued after the completion.
+        CompletableFuture.runAsync(() -> { }, ledger.getExecutor()).get(10, TimeUnit.SECONDS);
+        assertThat(ledger.currentLedgerTimeoutTriggered).isFalse();
+        assertThat(ledger.pendingAddEntries).isEmpty();
+        assertThat(ledger.currentLedger).isSameAs(spyLedger);
+    }
+
     private static class CollectCtxAddEntryCallback implements AddEntryCallback {
 
         public List<Object> addCompleteCtxList = new CopyOnWriteArrayList<>();