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

[PR] [fix][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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

   ### Motivation
   
   With the transaction coordinator enabled, the pending-ack store of a segment topic's subscription
   (`MetadataPendingAckStore`, PIP-473) records each transactional acknowledgment as a `/txn/op` ack record in the
   metadata store. It deletes a transaction's records only when it applies that transaction's outcome; `closeAsync()`
   only closes. #26882 made the segment delete clean up the transaction buffer's state and write records, but left
   these out. So when a segment, or just a subscription, is deleted while a transaction that acknowledged on it is
   still open, its ack records outlive the subscription:
   
   - The coordinator GC (`TransactionCoordinatorV5.gcOneTxn`) keeps a finalized transaction while it has op records.
     The header is never deleted, and every GC cycle re-publishes the outcome to
     `/txn/subscription-events/<segment>:<subscription>`, appending a record that nothing reads.
   - The records only go away if a subscription with the same name comes back on a segment with the same name. Its
     pending-ack store recovers the transaction as open, which is harmless: nothing is held back, and the outcome of a
     transaction its handle never saw is a no-op. It deletes the records once the transaction ends.
   
   This affects deleting a scalable topic, a segment (controller GC, namespace delete), and a subscription of a
   scalable topic.
   
   Separately, `TxnMetadataStore.deleteWriteOpsForSegment` (#26882) deletes every record the writes-by-segment index
   scan returns. A store with a native index (Oxia) doesn't apply the scan's filter, and its point lookups also match
   keys that extend the one looked up. So deleting segment `0000-7fff-1` also deletes the write records of segment
   `0000-7fff-12` of the same topic (checked against an Oxia container).
   
   ### Example
   
   ```java
   Transaction txn = client.newTransaction();
   consumer.acknowledge(msg.id(), txn);   // /txn/op/<txn>-<seq> {kind: ACK, segment, subscription: "sub"}
   consumer.close();
   admin.scalableTopics().deleteSubscription(topic, "sub");
   txn.abort();
   // /txn/op/<txn>-<seq> is still there, and the ABORTED header is never garbage-collected
   ```
   
   The subscription delete goes `ScalableTopicController.deleteSubscription` → `Segments.deleteSubscription` →
   `PersistentSubscription.delete()` → `MetadataPendingAckStore.closeAsync()`:
   
   ```java
   public CompletableFuture<Void> closeAsync() {
       closed = true;
       closeSubscriptionQuietly();
       return CompletableFuture.completedFuture(null);
   }
   ```
   
   It then reaches `PersistentTopic.unsubscribe`, which deletes the legacy pending-ack managed ledger (a segment has
   none) and the cursor. `Segments.deleteSegment` deletes the write records and the transaction buffer's state, not the
   ack records.
   
   ### Modifications
   
   - `Segments.deleteSubscription` deletes the subscription's ack records on the segment once its cursor is deleted, or
     found missing (new `TxnMetadataStore.deleteAckOpsForSegmentSubscription`). This is best effort, like the
     segment's cleanup: the subscription is gone, and the controller doesn't retry.
   
     ```java
     .thenCompose(__ -> deleteSubscriptionTxnState(segmentTopic, subscription))
     ```
   - `Segments.deleteSegment` also deletes the segment's ack records for every subscription (new
     `TxnMetadataStore.deleteAckOpsForSegment`). As with the write records, this happens only once the segment is out of
     its topic's layout:
   
     ```java
     return FutureUtil.waitForAll(List.of(
             txnStore.deleteWriteOpsForSegment(segment),
             txnStore.deleteAckOpsForSegment(segment),
             txnStore.deleteAllSegmentState(segment)));
     ```
   
     It does a single scan of the segment's range of the `acks-by-segment-subscription` index,
     `[<encoded-segment>:, <encoded-segment>:~]` (`TxnPaths.ackIndexSegmentLowerBound/UpperBound`). URL encoding
     escapes `:` and `~`, and the key of a segment whose id extends this one's continues with a digit, so the range
     holds only this segment's keys. The scan doesn't depend on which subscriptions are loaded, also finds the records
     of subscriptions deleted earlier, and on ZooKeeper costs one listing of `/txn/op` regardless of the number of
     subscriptions.
   - The cleanups re-check every record the index scan returns (`TxnMetadataStore.scanAndDeleteOpsOnSegment`, now also
     used by `deleteWriteOpsForSegment`). This guards against the over-matching point lookups of a native index: the
     write records of segment `0000-7fff-12` when deleting `0000-7fff-1`, and the ack records of subscription `sub2`
     when deleting `sub`.
   - `MetadataPendingAckStore.closeAsync()` completes only once the ack writes in progress are done, and no write starts
     after it is called (the closed check and the tracking of a write happen under the store's lock), so no ack record
     lands after the cleanup. A failed write fails its ack, not the close.
   
   Not in this change, as in #26882: the `/txn/segment-events` and `/txn/subscription-events` streams.
   
   ### Verifying this change
   
   - [ ] Make sure that the change passes the CI checks.
   
   This change added tests and can be verified as follows:
   
   - `ScalableTopicSegmentDeleteTxnStateTest`, with V5 transactional acks (`QueueConsumer.acknowledge(msgId, txn)`).
     Both tests fail without the change:
     - deleting the scalable topic deletes the ack records of a transaction still open;
     - deleting one of two subscriptions acknowledged in the same transaction deletes its ack records and keeps the
       other's.
   - `TxnMetadataStoreTest`: `deleteAckOpsForSegmentSubscription`, `deleteAckOpsForSegment` and
     `deleteWriteOpsForSegment` on a store whose index scans return every record (these fail without the record check).
   - `TxnPathsTest`: the bounds of a segment's range of the ack index.
   - `MetadataPendingAckStoreTest`: the close waits for a write in progress (fails without the change), and still
     completes when that write fails.
   - Checked manually against a single-shard Oxia container: point lookups over-match as described, and the segment's
     range of the ack index deletes exactly that segment's records.
   
   ### Does this pull request potentially affect one of the following parts:
   
   *If the box was checked, please highlight the changes*
   
   - [ ] 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][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/metadata/TxnMetadataStore.java:
##########
@@ -233,6 +214,56 @@ public CompletableFuture<Void> deleteAckOpsForSegmentSubscriptionAndTxn(String s
                 collector -> listAcksBySegmentSubscription(segment, subscription, collector));
     }
 
+    /**
+     * Collect every {@code /txn/op} ack record for {@code (segment, subscription)}, of any txn, for
+     * {@link #deleteOps} — used when the subscription is deleted: the PendingAckStore deletes them as it applies the
+     * txns' outcomes, which it never does for a txn still open by then. A snapshot: the records a subscription
+     * re-created with the same name writes afterwards aren't in it.
+     *
+     * @return the paths of the records, mapped to their txn ids
+     */
+    public CompletableFuture<Map<String, String>> collectAckOpsForSegmentSubscription(String segment,
+                                                                                     String subscription) {
+        return collectOpsOnSegment(segment,
+                op -> op.getKind() == TxnOpKind.ACK && segment.equals(op.getSegment())
+                        && subscription.equals(op.getSubscription()),
+                collector -> listAcksBySegmentSubscription(segment, subscription, collector));
+    }
+
+    /**
+     * Delete every {@code /txn/op} ack record for {@code segment}, of any subscription and txn — used when the
+     * segment is deleted, for the same reason as {@link #collectAckOpsForSegmentSubscription}. A single scan,
+     * whatever the number of subscriptions, which also finds the records of subscriptions deleted before.
+     */
+    public CompletableFuture<Void> deleteAckOpsForSegment(String segment) {
+        return collectOpsOnSegment(segment,
+                op -> op.getKind() == TxnOpKind.ACK && segment.equals(op.getSegment()),
+                collector -> listAcksBySegment(segment, collector))
+                .thenCompose(this::deleteOps);
+    }
+
+    /**
+     * Delete the {@code /txn/op} records collected by {@link #collectAckOpsForSegmentSubscription}, each with its
+     * txn's partition key. Best-effort: tolerates concurrent deletions via {@link MetadataStore#deleteIfExists}.
+     */
+    public CompletableFuture<Void> deleteOps(Map<String, String> txnIdByPath) {
+        List<CompletableFuture<Void>> deletes = new ArrayList<>(txnIdByPath.size());
+        txnIdByPath.forEach((path, txnIdKey) -> deletes.add(
+                store.deleteIfExists(path, Optional.empty(), Set.of(new Option.PartitionKey(txnIdKey)))));

Review Comment:
   **P2: Preserve the observed record version in the cleanup snapshot.**
   
   An Oxia sequence path is not a permanent record identity: after its tail is deleted, a later append under the same transaction can reuse that path. With overlapping subscription deletions, both can capture the same old ACK; one cleanup removes it, a recreated subscription acknowledges using the same still-open transaction, and the delayed cleanup then unconditionally deletes the replacement's ACK here.
   
   I reproduced the storage-level interleaving against a single-shard `oxia/oxia:nightly-beta` container (revision `68e9015dcce9b55a3cf6d4651118aa8e792d3452`): collect snapshots A/B → delete B → append another ACK under the same OPEN transaction → observe the same path with a different version → delete A. The new record disappears. As a control, deleting with the old observed version returns `BadVersionException` and preserves the replacement. The native-store behavior is runtime-confirmed; the overlapping admin-request schedule was code-traced, not exercised end-to-end.
   
   Please capture `Stat.version` alongside the path/transaction ID and use it as `expectedVersion`, treating NotFound/version mismatch as a stale snapshot rather than deleting the new record. Add coverage for same-transaction path reuse; the current in-memory/different-transaction case does not exercise it. Otherwise the live subscription can lose its durable acknowledgment and coordinator participant record.



-- 
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][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Segments.java:
##########
@@ -272,6 +272,7 @@ public void deleteSubscription(
                     }
                     return sub.delete();
                 })
+                .thenCompose(__ -> deleteSubscriptionTxnState(segmentTopic, subscription))

Review Comment:
   **P1: Preserve the transactional ACKs of a recreated subscription.**
   
   Could we prevent same-name recreation until this cleanup finishes, or delete only record paths captured from the old instance? `sub.delete()` has already removed the old cursor and released the subscription name. A concurrent V5 consumer can recreate it and append a transactional ACK before this scan runs; the cleanup matches only segment/subscription names and therefore deletes the replacement's record too.
   
   I reproduced this with a real broker and V5 `QueueConsumer`, pausing only the cleanup scan: delete the old subscription → recreate `sub` → acknowledge in a new transaction → resume cleanup. Deletion returned HTTP 204 and the replacement remained live, but its ACK-record count went **1 → 0**. The coordinator enumerates participants from these records, so it can commit/abort without notifying the live subscription, leaving its pending acknowledgments unresolved.
   
   The new close barrier protects only the old store. One safe option is to capture its exact record paths after draining writes while recreation is still fenced, then delete only that snapshot after cursor deletion succeeds. Alternatively, keep a per-subscription recreation fence through cleanup completion. Please cover this interleaving with a regression test.



-- 
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][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/Segments.java:
##########
@@ -272,6 +272,7 @@ public void deleteSubscription(
                     }
                     return sub.delete();
                 })
+                .thenCompose(__ -> deleteSubscriptionTxnState(segmentTopic, subscription))

Review Comment:
   Fixed in bc162252a9c. `PersistentSubscription.delete()` now collects the subscription's ack records while it is still fenced and its pending-ack store is closed, then deletes the cursor, then deletes only that snapshot (a failed cursor delete keeps them). The endpoint's post-delete scan is gone. `SegmentSubscriptionDeleteTxnAckRecordsTest` covers your interleaving (hold after the cursor delete, re-create `sub`, ack in a new transaction, release) and fails against a post-delete scan.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
   



-- 
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][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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


##########
pulsar-broker/src/main/java/org/apache/pulsar/broker/transaction/metadata/TxnMetadataStore.java:
##########
@@ -233,6 +214,56 @@ public CompletableFuture<Void> deleteAckOpsForSegmentSubscriptionAndTxn(String s
                 collector -> listAcksBySegmentSubscription(segment, subscription, collector));
     }
 
+    /**
+     * Collect every {@code /txn/op} ack record for {@code (segment, subscription)}, of any txn, for
+     * {@link #deleteOps} — used when the subscription is deleted: the PendingAckStore deletes them as it applies the
+     * txns' outcomes, which it never does for a txn still open by then. A snapshot: the records a subscription
+     * re-created with the same name writes afterwards aren't in it.
+     *
+     * @return the paths of the records, mapped to their txn ids
+     */
+    public CompletableFuture<Map<String, String>> collectAckOpsForSegmentSubscription(String segment,
+                                                                                     String subscription) {
+        return collectOpsOnSegment(segment,
+                op -> op.getKind() == TxnOpKind.ACK && segment.equals(op.getSegment())
+                        && subscription.equals(op.getSubscription()),
+                collector -> listAcksBySegmentSubscription(segment, subscription, collector));
+    }
+
+    /**
+     * Delete every {@code /txn/op} ack record for {@code segment}, of any subscription and txn — used when the
+     * segment is deleted, for the same reason as {@link #collectAckOpsForSegmentSubscription}. A single scan,
+     * whatever the number of subscriptions, which also finds the records of subscriptions deleted before.
+     */
+    public CompletableFuture<Void> deleteAckOpsForSegment(String segment) {
+        return collectOpsOnSegment(segment,
+                op -> op.getKind() == TxnOpKind.ACK && segment.equals(op.getSegment()),
+                collector -> listAcksBySegment(segment, collector))
+                .thenCompose(this::deleteOps);
+    }
+
+    /**
+     * Delete the {@code /txn/op} records collected by {@link #collectAckOpsForSegmentSubscription}, each with its
+     * txn's partition key. Best-effort: tolerates concurrent deletions via {@link MetadataStore#deleteIfExists}.
+     */
+    public CompletableFuture<Void> deleteOps(Map<String, String> txnIdByPath) {
+        List<CompletableFuture<Void>> deletes = new ArrayList<>(txnIdByPath.size());
+        txnIdByPath.forEach((path, txnIdKey) -> deletes.add(
+                store.deleteIfExists(path, Optional.empty(), Set.of(new Option.PartitionKey(txnIdKey)))));

Review Comment:
   Fixed in 2b6f8848c6. The snapshot is now a list of `OpRecord(path, txnId, version)`, and `deleteOps` deletes each record only at the version it was collected at, treating NotFound and BadVersion as a stale snapshot. The segment sweeps get the same protection, since a txn's op sequence is shared by all its participants. Added `TxnMetadataStoreTest#deleteOps_keepsARecordWrittenAtACollectedPathSince`, which fails with an unconditional delete. I also checked on a single-shard Oxia container that the same-txn append after the delete reuses the path (v2 → v3) and survives the stale delete.
   
   _🤖 Addressed by [Claude Code](https://claude.com/claude-code)_
   



-- 
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][broker] Delete the ack records of open transactions when deleting a segment or a subscription [pulsar]

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


-- 
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