Skip to content

[Bug] Unloading a topic while a cursor switches to a new cursor ledger loses the cursor's acks #27047

Closed

Description

@volodymyr-aloware

Search before reporting

  • I searched in the issues and found nothing similar.

Read release policy

  • I understand that unsupported versions don't get bug fixes. I will try to reproduce the issue on a supported version of Pulsar client and Pulsar broker.

User environment

  • Broker: stock apachepulsar/pulsar:5.0.0 with no plugins, a ZooKeeper metadata store and one separate bookie, all in Docker.
  • Client: Java client 5.0.0.
  • The code path below is unchanged on master at 4c0231d.

Issue Description

When a topic is unloaded while one of its cursors is switching to a new cursor ledger, the acks the cursor took since the switch began are lost, and the messages are delivered again after the topic loads. With the reproduction below, a stock 5.0.0 broker redelivered all 30 acked messages in 16 of 20 runs on public/default, and in 15 of 20 on a second namespace.

How it happens (ManagedCursorImpl; line numbers are from the master commit above):

  1. A recovered cursor starts in NoLedger (recoveredCursor(), L894). The first mark-delete after a topic load therefore calls startCreatingNewMetadataLedger() (L3576), which sets the state to SwitchingLedger. While the switch runs, mark-deletes wait in pendingMarkDeleteOps, and lastMarkDeleteEntry keeps the old position.
  2. When the new ledger is ready, switchToNewLedger() (L4019) writes the cursor's z-node through persistPositionMetaStore().
  3. asyncClose() (L3428) does not wait for the switch. persistPositionWhenClosing() (L3285) writes the same z-node from lastMarkDeleteEntry through persistPositionMetaStore(-1, …) (L3340).
  4. Each persistPositionMetaStore() call reads cursorLedgerStat when it starts, so the two writes carry the same version and one of them fails with BadVersionException. Either outcome loses acks:
    • The close writes first. It persists lastMarkDeleteEntry, which is the position from before the queued mark-deletes. The "Closed cursor" line logs the in-memory markDeletePosition (3407:29), but the z-node gets 3407:-1. The switch then fails ("Metadata ledger creation failed"), and the queued mark-deletes fail with it. After the reload the cursor is recovered at 3407:-1, so every ack since the switch began is gone. This was the common case: 31 switch failures against 6 close failures in the 40 runs.
    • The switch writes first. The close gets BadVersionException. persistPositionMetaStore() refreshes the stat "so that the caller can retry", but persistPositionWhenClosing() does not retry: it calls closeFailed, the cursor stays in state Closing, and the managed ledger close "proceeds anyway". The z-node keeps what the switch wrote, so the acks after that write are lost.

The window is the switch's duration: about 10–15 ms with ZooKeeper and a separate bookie. A switch happens on the first ack after every topic load, which is the case a rolling restart or a bundle move hits, and on cursor-ledger rollovers (managedLedgerCursorRolloverTimeInSeconds, managedLedgerCursorMaxEntriesPerLedger). pulsar standalone, with a RocksDB metadata store and an in-process bookie, did not reproduce it in 20 runs: there the switch completes in 1–2 ms, before the unload request arrives.

Expected: the close persists the cursor's latest state, either by waiting for the in-flight switch or by retrying after the stat refresh.

Actual: the acks since the switch began are lost and the messages are redelivered.

Error messages

The close writes first (topic close-race-6562c0b6):

15:23:42,464 INFO  ManagedCursorImpl - Recovered cursor {cursor=sub-unload, ..., position=3407:-1}
15:23:42,493 INFO  PulsarWebResource - Unloading topic {topic=persistent://public/default/close-race-6562c0b6}
15:23:42,510 WARN  ManagedCursorImpl - Failed to update cursor metadata due to version conflict {cursor=sub-unload, exception=...BadVersionException...}
15:23:42,511 INFO  ManagedCursorImpl - Closed cursor {cursor=sub-unload, ..., markDeletePosition=3407:29}
15:23:42,522 ERROR ManagedCursorImpl - Metadata ledger creation failed {cursor=sub-unload, error=...BadVersionException...}
15:23:43,560 INFO  ManagedCursorImpl - Recovered cursor {cursor=sub-unload, ..., position=3407:-1}

The switch writes first (topic close-race-a578f2b6):

15:23:47,572 INFO  PulsarWebResource - Unloading topic {topic=persistent://public/default/close-race-a578f2b6}
15:23:47,587 WARN  ManagedCursorImpl - Failed to update cursor metadata due to version conflict {cursor=sub-unload, exception=...BadVersionException...}
15:23:47,589 INFO  ManagedCursorImpl - Updated cursor with new ledger {cursor=sub-unload, ledgerId=3425, ...}
15:23:47,590 WARN  ManagedCursorImpl - Failed to update cursor info when closing {cursor=sub-unload, errorMessage=...BadVersionException...}
15:23:47,591 WARN  ManagedCursorImpl - Persistent position failure when closing, the state will remain in state-closing and will no longer work
15:23:47,591 ERROR PersistentTopic - Failed to close managed ledger, proceeding anyway.

Reproducing the issue

Run this against a broker with a ZooKeeper metadata store and a separate bookie. Each run publishes 90 messages, acks 30, closes the consumer, unloads the topic straight away, and then counts the acked messages that come back.

try (PulsarClient client = PulsarClient.builder().serviceUrl(serviceUrl).build();
     PulsarAdmin admin = PulsarAdmin.builder().serviceHttpUrl(adminUrl).build()) {
    for (int run = 0; run < 20; run++) {
        String topic = "persistent://public/default/close-race-" + UUID.randomUUID().toString().substring(0, 8);
        try (Producer<byte[]> producer = client.newProducer().topic(topic).enableBatching(false).create()) {
            for (int i = 0; i < 90; i++) {
                producer.send(("m" + i).getBytes());
            }
        }
        Consumer<byte[]> first = client.newConsumer().topic(topic).subscriptionName("sub-unload")
                .subscriptionType(SubscriptionType.Shared)
                .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest).subscribe();
        Set<String> acked = new HashSet<>();
        for (int i = 0; i < 30; i++) {
            Message<byte[]> m = first.receive(10, TimeUnit.SECONDS);
            acked.add(new String(m.getValue()));
            first.acknowledge(m);
        }
        first.close();
        admin.topics().unload(topic);
        Thread.sleep(1000);

        Consumer<byte[]> second = client.newConsumer().topic(topic).subscriptionName("sub-unload")
                .subscriptionType(SubscriptionType.Shared).subscribe();
        Set<String> after = new HashSet<>();
        long deadline = System.currentTimeMillis() + 15_000;
        while (after.size() < 60 && System.currentTimeMillis() < deadline) {
            Message<byte[]> m = second.receive(2, TimeUnit.SECONDS);
            if (m != null) {
                after.add(new String(m.getValue()));
                second.acknowledge(m);
            }
        }
        after.retainAll(acked);
        System.out.printf("run %d: %d acked messages came back%n", run, after.size());
        second.close();
    }
}

On the stock 5.0.0 broker, 16 of 20 runs printed 30.

Additional information

Possible fixes; either one closes the window for both outcomes:

  • In asyncClose(), when a cursor-ledger switch is in flight, wait for it before persistPositionWhenClosing(), so that the close writes after the switch and after the queued mark-deletes. That would mean keeping the switch's completion as a future.
  • Have the close's write include the mark-deletes still queued in pendingMarkDeleteOps, and retry persistPositionMetaStore() after the stat refresh it already does on BadVersionException.

Related: #26944 fixed a close that overlaps a mark-delete's write to the cursor ledger. This report is the same close racing the metadata-store write of a ledger switch.

As a workaround, a broker plugin can delay a topic's close until ManagedCursorImpl.getState() leaves SwitchingLedger. On the same broker with that wait in place, 0 of 20 runs redelivered an acked message.

Are you willing to submit a PR?

  • I'm willing to submit a PR!

Activity

  1. NimeshXTV commented on Nov 17, 2026

    @NimeshXTV
    Contributor

    Hi ! id like to take a look at this issue, would you mind assigning it to me ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions