You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "Radiancebobo (via GitHub)" <gi...@apache.org> on 2026/10/16 12:29:18 UTC

[PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Radiancebobo opened a new pull request, #26940:
URL: https://github.com/apache/pulsar/pull/26940

   ### Motivation
   
   In a production incident, one broker repeatedly emitted the following log for several hours, and the incident
   only cleared after the broker was restarted:
   
   ```text
   2026-10-10T12:54:56,683+0000 [metadata-store-11-1] INFO  org.apache.bookkeeper.client.MetadataUpdateLoop - UpdateLoop(ledgerId=xxxx,loopId=xxxxx) conflict writing metadata to store, update local value and try again
   ```
   
   
   When a ledger metadata update fails with a version conflict, BookKeeper rereads the metadata and retries the update.
   In Pulsar, `PulsarLedgerManager.readLedgerMetadata()` reads through the metadata cache, so this reread can return
   the same stale version that caused the failed write.
   
   Before this change, `PulsarLedgerManager.writeLedgerMetadata()` translated a metadata store `BadVersionException`
   into `BKMetadataVersionException` without invalidating the corresponding ledger metadata cache entry.
   
   For example, if the cache contains version 7 while the metadata store contains version 8:
   
   1. BookKeeper attempts a conditional write with expected version 7.
   2. The metadata store rejects the write with `BadVersionException`.
   3. Pulsar returns `BKMetadataVersionException` to BookKeeper.
   4. BookKeeper rereads the ledger metadata, but the cache still returns version 7.
   5. BookKeeper retries the conditional write with version 7 and encounters the same conflict.
   
   BookKeeper 4.18.1 does not impose a maximum retry count on this path. If the stale cache entry remains available,
   the update can keep retrying without making progress and repeatedly emit:
   
   ```text
   conflict writing metadata to store, update local value and try again
   ```
   
   Cache expiration and change notifications can eventually refresh the value, but the conflict retry should not
   depend on either mechanism to stop reusing stale metadata.
   
   The fix invalidates the affected ledger cache entry before reporting the version conflict, so the retry can load
   metadata from the store. The ordering matters because completing the future can immediately execute BookKeeper's
   retry callback on the same thread.
   
   This addresses the stale-cache retry path. Concurrent writers can still cause legitimate version conflicts, and
   this change does not add a retry limit or guarantee completion under continuous contention.
   
   ### Modifications
   
   - Invalidate the corresponding ledger metadata cache entry when `writeLedgerMetadata()` encounters
     `BadVersionException`, before completing the returned future with `BKMetadataVersionException`.
   - Use `FutureUtil.unwrapCompletionException()` to identify the underlying failure through nested
     `CompletionException` and `ExecutionException` wrappers. Other write failures continue to return `ZKException`,
     with the underlying failure as the cause.
   - Add `PulsarLedgerManagerTest` using a real metadata cache with controlled backend reads and writes to verify:
     - A cached version 7 remains stale when the backend advances to version 8 without a notification.
     - A reread performed immediately in the failed write's callback returns version 8 and its updated ensemble.
     - Direct and wrapped version conflicts retain the `BKMetadataVersionException` contract.
     - Other write failures preserve the cache and propagate the underlying cause.
   
   Invalidation only removes the local cache entry; subsequent writes still use the existing conditional-write
   version check. The successful write path is unchanged. Under contention, invalidation can increase backend reads,
   including when another operation has already refreshed the cache.
   
   ### Verifying this change
   
   - [ ] Make sure that the change passes the CI checks.
   
   This change added tests and can be verified as follows:
   
   - Reproduced the stale-cache defect before the fix: the retry read returned version 7 instead of version 8.
   - Reproduced incorrect exception classification with nested asynchronous exception wrappers before unwrapping them.
   - Passed all 4 regression cases in `PulsarLedgerManagerTest` and all 9 existing cases in
     `PulsarLedgerMetadataListenerTest`, with no skipped tests and retries disabled.
   - Passed the metadata module's Checkstyle and Spotless checks.
   
   Commands run locally:
   
   ```bash
   ./gradlew :pulsar-metadata:test \
     --tests org.apache.pulsar.metadata.bookkeeper.PulsarLedgerManagerTest \
     --tests org.apache.pulsar.metadata.bookkeeper.PulsarLedgerMetadataListenerTest \
     -PtestRetryCount=0 -PtestFailFast=false
   ./gradlew :pulsar-metadata:checkstyleMain :pulsar-metadata:checkstyleTest :pulsar-metadata:spotlessCheck
   ./gradlew quickCheck
   ```
   
   
   ### Does this pull request potentially affect one of the following parts:
   
   - [ ] Dependencies (add or upgrade a dependency)
   - [ ] The public API
   - [ ] The schema
   - [ ] The default values of configurations
   - [ ] The threading model
   - [ ] The binary protocol
   - [ ] The REST endpoints
   - [ ] The admin CLI options
   - [ ] The metrics
   - [ ] Anything that affects deployment
   


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Posted by "codelipenghui (via GitHub)" <gi...@apache.org>.
codelipenghui commented on code in PR #26940:
URL: https://github.com/apache/pulsar/pull/26940#discussion_r4297179001


##########
pulsar-metadata/src/test/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManagerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.pulsar.metadata.bookkeeper;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.client.BKException;
+import org.apache.bookkeeper.client.LedgerMetadataBuilder;
+import org.apache.bookkeeper.client.api.DigestType;
+import org.apache.bookkeeper.client.api.LedgerMetadata;
+import org.apache.bookkeeper.meta.LedgerMetadataSerDe;
+import org.apache.bookkeeper.net.BookieId;
+import org.apache.bookkeeper.versioning.LongVersion;
+import org.apache.bookkeeper.versioning.Versioned;
+import org.apache.pulsar.metadata.api.GetResult;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.MetadataStoreConfig;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.MetadataStoreFactory;
+import org.apache.pulsar.metadata.api.Stat;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class PulsarLedgerManagerTest {

Review Comment:
   Master now has its own `PulsarLedgerManagerTest` (added in #26669, extending `BaseMetadataStoreTest`), so this new file conflicts and CI hasn't run yet.
   
   When merging master, please don't carry over methods named `setup()`/`cleanup()`: in that class they would override `BaseMetadataStoreTest`'s `@BeforeClass setup()`/`@AfterClass cleanup()` (abstract in `TestRetrySupport`). Method annotations aren't inherited, so TestNG would only see `@BeforeMethod`/`@AfterMethod`, and the ZK/RocksDB/mock-zk fixtures used by the `impl` data-provider tests would never be started or closed.
   
   Making these tests self-contained (create the spied store and manager in each test with try-with-resources), or keeping them in a separately named class, avoids that.



##########
pulsar-metadata/src/main/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManager.java:
##########
@@ -242,11 +242,14 @@ public CompletableFuture<Versioned<LedgerMetadata>> writeLedgerMetadata(long led
                 .thenAccept(stat -> {
                     promise.complete(new Versioned<>(metadata, new LongVersion(stat.getVersion())));
                 }).exceptionally(ex -> {
-                    if (ex.getCause() instanceof MetadataStoreException.BadVersionException) {
+                    Throwable cause = FutureUtil.unwrapCompletionException(ex);
+                    if (cause instanceof MetadataStoreException.BadVersionException) {
+                        // Invalidate before completing the promise: its callbacks can immediately retry the read.
+                        cache.invalidate(getLedgerPath(ledgerId));
                         promise.completeExceptionally(new BKException.BKMetadataVersionException());
                     } else {
                         log.warn().exceptionMessage(ex).log("Conditional update ledger metadata failed");

Review Comment:
   Optional, since `cause` is now available here: `log.warn().attr("ledgerId", ledgerId).exceptionMessage(cause).log(...)` would identify the ledger and avoid logging the `CompletionException` wrapper, matching the create path on master.



##########
pulsar-metadata/src/test/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManagerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.pulsar.metadata.bookkeeper;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.client.BKException;
+import org.apache.bookkeeper.client.LedgerMetadataBuilder;
+import org.apache.bookkeeper.client.api.DigestType;
+import org.apache.bookkeeper.client.api.LedgerMetadata;
+import org.apache.bookkeeper.meta.LedgerMetadataSerDe;
+import org.apache.bookkeeper.net.BookieId;
+import org.apache.bookkeeper.versioning.LongVersion;
+import org.apache.bookkeeper.versioning.Versioned;
+import org.apache.pulsar.metadata.api.GetResult;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.MetadataStoreConfig;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.MetadataStoreFactory;
+import org.apache.pulsar.metadata.api.Stat;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class PulsarLedgerManagerTest {
+    private static final long LEDGER_ID = 1L;
+    private static final List<BookieId> UPDATED_ENSEMBLE = List.of(BookieId.parse("bookie-2:3181"));
+
+    private MetadataStore store;
+    private PulsarLedgerManager manager;
+    private LedgerMetadata metadata;
+    private String ledgerPath;
+    private CompletableFuture<Stat> pendingPut;
+
+    @BeforeMethod
+    public void setup() throws Exception {
+        // Use the real metadata cache, but control backend reads and writes without delivering notifications.
+        store = spy(MetadataStoreFactory.create("memory:local", MetadataStoreConfig.builder().build()));
+        manager = new PulsarLedgerManager(store, "/ledgers");
+        ledgerPath = manager.getLedgerPath(LEDGER_ID);
+        metadata = LedgerMetadataBuilder.create()
+                .withId(LEDGER_ID)
+                .withEnsembleSize(1)
+                .withWriteQuorumSize(1)
+                .withAckQuorumSize(1)
+                .withPassword(new byte[0])
+                .withDigestType(DigestType.CRC32C)
+                .newEnsembleEntry(0L, List.of(BookieId.parse("bookie-1:3181")))
+                .build();
+        setBackendMetadata(metadata, 7L);
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+        pendingPut = new CompletableFuture<>();
+        doReturn(pendingPut).when(store).put(eq(ledgerPath), any(byte[].class), eq(Optional.of(7L)));
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void cleanup() throws Exception {
+        try {
+            if (manager != null) {
+                manager.close();
+            }
+        } finally {
+            if (store != null) {
+                store.close();
+            }
+        }
+    }
+
+    @DataProvider
+    public Object[][] badVersionFailures() {
+        Throwable conflict = new MetadataStoreException.BadVersionException("stale version");
+        return new Object[][] {
+                {conflict},
+                {new CompletionException(conflict)},
+                {new CompletionException(new ExecutionException(conflict))}
+        };
+    }
+
+    @Test(dataProvider = "badVersionFailures", timeOut = 30000)
+    public void testRetryReadsFreshMetadataOnBadVersion(Throwable failure) throws Exception {
+        LedgerMetadata updatedMetadata = LedgerMetadataBuilder.from(metadata)
+                .replaceEnsembleEntry(0L, UPDATED_ENSEMBLE).build();
+        setBackendMetadata(updatedMetadata, 8L);
+        // Confirm the read is still cached until the conflicting write fails.
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+
+        CompletableFuture<Versioned<LedgerMetadata>> retryRead = manager
+                .writeLedgerMetadata(LEDGER_ID, metadata, new LongVersion(7L))
+                .handle((result, error) -> {
+                    assertThat(error).isInstanceOf(BKException.BKMetadataVersionException.class);
+                    // Register before completing the backend write: this callback runs inline on failure.
+                    return manager.readLedgerMetadata(LEDGER_ID);
+                }).thenCompose(read -> read);
+        pendingPut.completeExceptionally(failure);
+
+        Versioned<LedgerMetadata> fresh = retryRead.get(10, TimeUnit.SECONDS);
+        assertThat(fresh.getVersion()).isEqualTo(new LongVersion(8L));
+        assertThat(fresh.getValue().getEnsembleAt(0L)).isEqualTo(UPDATED_ENSEMBLE);
+    }
+
+    @Test(timeOut = 30000)
+    public void testOtherWriteFailurePreservesCacheAndCause() throws Exception {
+        MetadataStoreException failure = new MetadataStoreException("backend unavailable");
+        CompletableFuture<Void> checked = manager.writeLedgerMetadata(LEDGER_ID, metadata, new LongVersion(7L))
+                .handle((result, error) -> {
+                    assertThat(error).isInstanceOf(BKException.ZKException.class).hasCause(failure);
+                    return null;
+                });
+        pendingPut.completeExceptionally(new CompletionException(new ExecutionException(failure)));
+        checked.get(10, TimeUnit.SECONDS);
+
+        setBackendMetadata(metadata, 8L);
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+    }
+
+    private void setBackendMetadata(LedgerMetadata value, long version) throws Exception {
+        GetResult result = new GetResult(new LedgerMetadataSerDe().serialize(value),
+                new Stat(ledgerPath, version, 0L, 0L, false, version == 0));

Review Comment:
   Nit: the sixth `Stat` argument is `createdBySelf`; this constructor already derives `firstVersion` from `version == 0`. Passing `false` here would avoid suggesting otherwise.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Posted by "Radiancebobo (via GitHub)" <gi...@apache.org>.
Radiancebobo commented on code in PR #26940:
URL: https://github.com/apache/pulsar/pull/26940#discussion_r4301154202


##########
pulsar-metadata/src/main/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManager.java:
##########
@@ -242,11 +242,14 @@ public CompletableFuture<Versioned<LedgerMetadata>> writeLedgerMetadata(long led
                 .thenAccept(stat -> {
                     promise.complete(new Versioned<>(metadata, new LongVersion(stat.getVersion())));
                 }).exceptionally(ex -> {
-                    if (ex.getCause() instanceof MetadataStoreException.BadVersionException) {
+                    Throwable cause = FutureUtil.unwrapCompletionException(ex);
+                    if (cause instanceof MetadataStoreException.BadVersionException) {
+                        // Invalidate before completing the promise: its callbacks can immediately retry the read.
+                        cache.invalidate(getLedgerPath(ledgerId));
                         promise.completeExceptionally(new BKException.BKMetadataVersionException());
                     } else {
                         log.warn().exceptionMessage(ex).log("Conditional update ledger metadata failed");

Review Comment:
   Thanks for the suggestion. I updated the warning to include `ledgerId` and log the unwrapped `cause`, consistent with the create path on master. 



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Posted by "Radiancebobo (via GitHub)" <gi...@apache.org>.
Radiancebobo commented on code in PR #26940:
URL: https://github.com/apache/pulsar/pull/26940#discussion_r4301150489


##########
pulsar-metadata/src/test/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManagerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.pulsar.metadata.bookkeeper;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.client.BKException;
+import org.apache.bookkeeper.client.LedgerMetadataBuilder;
+import org.apache.bookkeeper.client.api.DigestType;
+import org.apache.bookkeeper.client.api.LedgerMetadata;
+import org.apache.bookkeeper.meta.LedgerMetadataSerDe;
+import org.apache.bookkeeper.net.BookieId;
+import org.apache.bookkeeper.versioning.LongVersion;
+import org.apache.bookkeeper.versioning.Versioned;
+import org.apache.pulsar.metadata.api.GetResult;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.MetadataStoreConfig;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.MetadataStoreFactory;
+import org.apache.pulsar.metadata.api.Stat;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class PulsarLedgerManagerTest {
+    private static final long LEDGER_ID = 1L;
+    private static final List<BookieId> UPDATED_ENSEMBLE = List.of(BookieId.parse("bookie-2:3181"));
+
+    private MetadataStore store;
+    private PulsarLedgerManager manager;
+    private LedgerMetadata metadata;
+    private String ledgerPath;
+    private CompletableFuture<Stat> pendingPut;
+
+    @BeforeMethod
+    public void setup() throws Exception {
+        // Use the real metadata cache, but control backend reads and writes without delivering notifications.
+        store = spy(MetadataStoreFactory.create("memory:local", MetadataStoreConfig.builder().build()));
+        manager = new PulsarLedgerManager(store, "/ledgers");
+        ledgerPath = manager.getLedgerPath(LEDGER_ID);
+        metadata = LedgerMetadataBuilder.create()
+                .withId(LEDGER_ID)
+                .withEnsembleSize(1)
+                .withWriteQuorumSize(1)
+                .withAckQuorumSize(1)
+                .withPassword(new byte[0])
+                .withDigestType(DigestType.CRC32C)
+                .newEnsembleEntry(0L, List.of(BookieId.parse("bookie-1:3181")))
+                .build();
+        setBackendMetadata(metadata, 7L);
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+        pendingPut = new CompletableFuture<>();
+        doReturn(pendingPut).when(store).put(eq(ledgerPath), any(byte[].class), eq(Optional.of(7L)));
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void cleanup() throws Exception {
+        try {
+            if (manager != null) {
+                manager.close();
+            }
+        } finally {
+            if (store != null) {
+                store.close();
+            }
+        }
+    }
+
+    @DataProvider
+    public Object[][] badVersionFailures() {
+        Throwable conflict = new MetadataStoreException.BadVersionException("stale version");
+        return new Object[][] {
+                {conflict},
+                {new CompletionException(conflict)},
+                {new CompletionException(new ExecutionException(conflict))}
+        };
+    }
+
+    @Test(dataProvider = "badVersionFailures", timeOut = 30000)
+    public void testRetryReadsFreshMetadataOnBadVersion(Throwable failure) throws Exception {
+        LedgerMetadata updatedMetadata = LedgerMetadataBuilder.from(metadata)
+                .replaceEnsembleEntry(0L, UPDATED_ENSEMBLE).build();
+        setBackendMetadata(updatedMetadata, 8L);
+        // Confirm the read is still cached until the conflicting write fails.
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+
+        CompletableFuture<Versioned<LedgerMetadata>> retryRead = manager
+                .writeLedgerMetadata(LEDGER_ID, metadata, new LongVersion(7L))
+                .handle((result, error) -> {
+                    assertThat(error).isInstanceOf(BKException.BKMetadataVersionException.class);
+                    // Register before completing the backend write: this callback runs inline on failure.
+                    return manager.readLedgerMetadata(LEDGER_ID);
+                }).thenCompose(read -> read);
+        pendingPut.completeExceptionally(failure);
+
+        Versioned<LedgerMetadata> fresh = retryRead.get(10, TimeUnit.SECONDS);
+        assertThat(fresh.getVersion()).isEqualTo(new LongVersion(8L));
+        assertThat(fresh.getValue().getEnsembleAt(0L)).isEqualTo(UPDATED_ENSEMBLE);
+    }
+
+    @Test(timeOut = 30000)
+    public void testOtherWriteFailurePreservesCacheAndCause() throws Exception {
+        MetadataStoreException failure = new MetadataStoreException("backend unavailable");
+        CompletableFuture<Void> checked = manager.writeLedgerMetadata(LEDGER_ID, metadata, new LongVersion(7L))
+                .handle((result, error) -> {
+                    assertThat(error).isInstanceOf(BKException.ZKException.class).hasCause(failure);
+                    return null;
+                });
+        pendingPut.completeExceptionally(new CompletionException(new ExecutionException(failure)));
+        checked.get(10, TimeUnit.SECONDS);
+
+        setBackendMetadata(metadata, 8L);
+        assertThat(manager.readLedgerMetadata(LEDGER_ID).get(10, TimeUnit.SECONDS).getVersion())
+                .isEqualTo(new LongVersion(7L));
+    }
+
+    private void setBackendMetadata(LedgerMetadata value, long version) throws Exception {
+        GetResult result = new GetResult(new LedgerMetadataSerDe().serialize(value),
+                new Stat(ledgerPath, version, 0L, 0L, false, version == 0));

Review Comment:
   Good catch. I changed the `createdBySelf` argument to `false`. The constructor continues to derive `firstVersion` from `version == 0`. 



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Posted by "Radiancebobo (via GitHub)" <gi...@apache.org>.
Radiancebobo commented on code in PR #26940:
URL: https://github.com/apache/pulsar/pull/26940#discussion_r4301143372


##########
pulsar-metadata/src/test/java/org/apache/pulsar/metadata/bookkeeper/PulsarLedgerManagerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.pulsar.metadata.bookkeeper;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import org.apache.bookkeeper.client.BKException;
+import org.apache.bookkeeper.client.LedgerMetadataBuilder;
+import org.apache.bookkeeper.client.api.DigestType;
+import org.apache.bookkeeper.client.api.LedgerMetadata;
+import org.apache.bookkeeper.meta.LedgerMetadataSerDe;
+import org.apache.bookkeeper.net.BookieId;
+import org.apache.bookkeeper.versioning.LongVersion;
+import org.apache.bookkeeper.versioning.Versioned;
+import org.apache.pulsar.metadata.api.GetResult;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.apache.pulsar.metadata.api.MetadataStoreConfig;
+import org.apache.pulsar.metadata.api.MetadataStoreException;
+import org.apache.pulsar.metadata.api.MetadataStoreFactory;
+import org.apache.pulsar.metadata.api.Stat;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class PulsarLedgerManagerTest {

Review Comment:
   Thanks for catching this. I merged the latest master and kept the cache regression tests in a separate `PulsarLedgerManagerCacheTest` class. This prevents its `setup()` and `cleanup()` methods from interfering with the `BaseMetadataStoreTest` lifecycle in the existing `PulsarLedgerManagerTest`.



-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][metadata] Invalidate ledger metadata cache on version conflicts [pulsar]

Posted by "merlimat (via GitHub)" <gi...@apache.org>.
merlimat merged PR #26940:
URL: https://github.com/apache/pulsar/pull/26940


-- 
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: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org