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

(pulsar) 07/27: [fix][ml] Fix backlog estimation during ledger rollover with pending writes (#26647)

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

lhotari pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 8d785b7acbf7d9b7bf913f1103e10be7375d5417
Author: sinan liu <li...@gmail.com>
AuthorDate: Sun Sep 20 10:20:44 2026 +0800

    [fix][ml] Fix backlog estimation during ledger rollover with pending writes (#26647)
    
    Co-authored-by: Lari Hotari <lh...@users.noreply.github.com>
    (cherry picked from commit 776248a7fe0f93b213b9f06658ca7f7e64c87c42)
---
 .../bookkeeper/mledger/impl/ManagedCursorImpl.java |  14 ++-
 .../mledger/impl/ManagedLedgerBkTest.java          | 109 +++++++++++++++++++++
 2 files changed, 118 insertions(+), 5 deletions(-)

diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
index 501487366d29..85357e5067d0 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
@@ -1312,7 +1312,7 @@ public class ManagedCursorImpl implements ManagedCursor {
         }
         if (markDeletePosition.compareTo(lastPosition) > 0) {
             if (!ledger.ledgerExists(lastPosition.getLedgerId())
-                    || isMarkDeletePositionOnEmptyCurrentLedger(markDeletePosition)) {
+                    || isMarkDeletePositionAtStartOfCurrentLedger(markDeletePosition)) {
                 return 0;
             }
             throw new IllegalArgumentException(String.format(
@@ -1385,10 +1385,14 @@ public class ManagedCursorImpl implements ManagedCursor {
         return adjustedSize;
     }
 
-    private boolean isMarkDeletePositionOnEmptyCurrentLedger(Position markDeletePosition) {
-        return ledger.currentLedger != null
-                && markDeletePosition.getLedgerId() == ledger.currentLedger.getId()
-                && ledger.currentLedgerEntries == 0;
+    private boolean isMarkDeletePositionAtStartOfCurrentLedger(Position markDeletePosition) {
+        // The caller has already checked that mark-delete is ahead of the last confirmed position.
+        // Rollover can move the cursor to this sentinel while the first add is still pending;
+        // currentLedgerEntries includes pending adds, so it cannot identify this state.
+        LedgerHandle currentLedger = ledger.currentLedger;
+        return currentLedger != null
+                && markDeletePosition.getLedgerId() == currentLedger.getId()
+                && markDeletePosition.getEntryId() == -1;
     }
 
     private long getNumberOfEntriesInBacklog() {
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java
index 9740db647d90..0d086b6be66c 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerBkTest.java
@@ -20,6 +20,7 @@ package org.apache.bookkeeper.mledger.impl;
 
 import static org.apache.pulsar.common.util.PortManager.releaseLockedPort;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNotEquals;
 import static org.testng.Assert.assertNotNull;
@@ -79,6 +80,114 @@ public class ManagedLedgerBkTest extends BookKeeperClusterTestCase {
         super(2);
     }
 
+    private static ManagedLedgerConfig defaultConfig() {
+        ManagedLedgerConfig config = new ManagedLedgerConfig();
+        config.setPulsarMessageEntries(false);
+        return config;
+    }
+
+    @Test
+    public void testEstimatedUnackedSizeDuringRolloverWithPendingAdd() throws Exception {
+        @Cleanup("shutdown")
+        ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(metadataStore, bkc);
+        ManagedLedgerConfig config = defaultConfig()
+                .setEnsembleSize(2).setWriteQuorumSize(2).setAckQuorumSize(2)
+                .setRetentionSizeInMB(-1).setRetentionTime(-1, TimeUnit.MILLISECONDS);
+        config.setMinimumRolloverTime(0, TimeUnit.MILLISECONDS);
+        ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("pending-add-" + testName, config);
+        ManagedCursor cursor = ledger.openCursor("c1");
+        byte[] data = "entry".getBytes(StandardCharsets.UTF_8);
+        ledger.addEntry(data);
+        Position lastPosition = ledger.addEntry(data);
+        cursor.markDelete(lastPosition);
+        config.setMaxEntriesPerLedger(2);
+
+        CompletableFuture<Position> pendingAdd = new CompletableFuture<>();
+        CountDownLatch resumeBookie = new CountDownLatch(1);
+        CountDownLatch bookieSuspended = new CountDownLatch(1);
+        try {
+            // Both bookies must acknowledge the write. Hold one so the first add to the new ledger stays pending.
+            sleepBookie(getBookie(0), resumeBookie, bookieSuspended);
+            assertThat(bookieSuspended.await(10, TimeUnit.SECONDS)).isTrue();
+            ledger.rollCurrentLedgerIfFull();
+            ledger.asyncAddEntry(data, new AddEntryCallback() {
+                @Override
+                public void addComplete(Position position, ByteBuf entryData, Object ctx) {
+                    pendingAdd.complete(position);
+                }
+
+                @Override
+                public void addFailed(ManagedLedgerException exception, Object ctx) {
+                    pendingAdd.completeExceptionally(exception);
+                }
+            }, null);
+
+            // Rollover itself moves the caught-up cursor to the new ledger's -1 sentinel.
+            Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+                assertThat(cursor.getMarkDeletedPosition().getLedgerId()).isGreaterThan(lastPosition.getLedgerId());
+                assertThat(cursor.getMarkDeletedPosition().getEntryId()).isEqualTo(-1);
+                assertThat(ledger.getCurrentLedgerEntries()).isEqualTo(1);
+            });
+            assertThat(cursor.getMarkDeletedPosition().getLedgerId()).isEqualTo(ledger.currentLedger.getId());
+            assertThat(ledger.getLastPosition()).isEqualTo(lastPosition);
+            // Keep the old ledger so the removed-ledger shortcut cannot mask the regression.
+            assertThat(ledger.ledgerExists(lastPosition.getLedgerId())).isTrue();
+            assertThat(pendingAdd).isNotDone();
+            assertThat(cursor.getEstimatedSizeSinceMarkDeletePosition()).isZero();
+        } finally {
+            resumeBookie.countDown();
+        }
+
+        Position newPosition = pendingAdd.get(10, TimeUnit.SECONDS);
+        assertThat(newPosition.getLedgerId()).isGreaterThan(lastPosition.getLedgerId());
+        assertThat(newPosition.getEntryId()).isZero();
+        assertThat(cursor.getEstimatedSizeSinceMarkDeletePosition()).isEqualTo(data.length);
+        List<Entry> entries = cursor.readEntries(1);
+        try {
+            assertThat(entries).hasSize(1);
+            assertThat(entries.get(0).getPosition()).isEqualTo(newPosition);
+            assertThat(entries.get(0).getData()).isEqualTo(data);
+        } finally {
+            entries.forEach(Entry::release);
+        }
+        cursor.markDelete(newPosition);
+        assertThat(cursor.getEstimatedSizeSinceMarkDeletePosition()).isZero();
+    }
+
+    @Test
+    public void testEstimatedUnackedSizeRejectsUnconfirmedEntryInEmptyLedger() throws Exception {
+        @Cleanup("shutdown")
+        ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(metadataStore, bkc);
+        ManagedLedgerConfig config = defaultConfig()
+                .setEnsembleSize(2).setWriteQuorumSize(2).setAckQuorumSize(2)
+                .setRetentionSizeInMB(-1).setRetentionTime(-1, TimeUnit.MILLISECONDS);
+        config.setMinimumRolloverTime(0, TimeUnit.MILLISECONDS);
+        ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("invalid-position-" + testName, config);
+        ManagedCursor cursor = ledger.openCursor("c1");
+        Position lastPosition = ledger.addEntry("entry".getBytes(StandardCharsets.UTF_8));
+        cursor.markDelete(lastPosition);
+        config.setMaxEntriesPerLedger(1);
+        ledger.rollCurrentLedgerIfFull();
+
+        Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+            assertThat(cursor.getMarkDeletedPosition().getLedgerId()).isGreaterThan(lastPosition.getLedgerId());
+            assertThat(cursor.getMarkDeletedPosition().getEntryId()).isEqualTo(-1);
+        });
+        assertThat(cursor.getEstimatedSizeSinceMarkDeletePosition()).isZero();
+
+        // asyncMarkDelete currently accepts an ahead-of-LAC entry in the next ledger after consuming the old one.
+        // The estimator must not mistake that entry for the valid -1 sentinel just because the ledger is empty.
+        Position invalidPosition = PositionFactory.create(cursor.getMarkDeletedPosition().getLedgerId(), 0);
+        cursor.markDelete(invalidPosition);
+        assertThat(cursor.getMarkDeletedPosition()).isEqualTo(invalidPosition);
+        assertThat(ledger.getCurrentLedgerEntries()).isZero();
+        assertThat(ledger.getLastPosition()).isEqualTo(lastPosition);
+        assertThat(ledger.ledgerExists(lastPosition.getLedgerId())).isTrue();
+        assertThatThrownBy(cursor::getEstimatedSizeSinceMarkDeletePosition)
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("is ahead of the last position");
+    }
+
     @Test
     public void testSimpleRead() throws Exception {
         ManagedLedgerFactoryConfig factoryConf = new ManagedLedgerFactoryConfig();