GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][txn] Fix reuse of recycled pooled objects in transaction code p… · apache/pulsar@ba3d039

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src
    • main/java/org/apache/pulsar/broker/service/persistent
      • PersistentTopic.java
    • test/java/org/apache/pulsar/broker/service
      • PersistentTopicTest.java
  • pulsar-client/src
    • main/java/org/apache/pulsar/client/impl
      • TransactionMetaStoreHandler.java
    • test/java/org/apache/pulsar/client/impl
      • TransactionMetaStoreHandlerTest.java
  • pulsar-transaction/coordinator/src
    • main/java/org/apache/pulsar/transaction/coordinator/impl
      • TxnLogBufferedWriter.java
    • test/java/org/apache/pulsar/transaction/coordinator/impl
      • TxnLogBufferedWriterTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
+27-11Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5177,25 +5177,41 @@ public void publishTxnMessage(TxnID txnID, ByteBuf headersAndPayload, PublishCon
51775177
messageDeduplication.isDuplicate(publishContext, headersAndPayload);
51785178
switch (status) {
51795179
case NotDup:
5180+
// Handle success and failure in a single stage so that an exception thrown while handling the
5181+
// success can't complete the (recycled) publish context a second time as a failure.
51805182
transactionBuffer.appendBufferToTxn(txnID, publishContext.getSequenceId(), headersAndPayload)
5181-
.thenAccept(position -> {
5183+
.handle((position, throwable) -> {
5184+
if (throwable != null) {
5185+
throwable = FutureUtil.unwrapCompletionException(throwable);
5186+
if (throwable instanceof NotAllowedException) {
5187+
publishContext.completed((NotAllowedException) throwable, -1, -1);
5188+
decrementPendingWriteOpsAndCheck();
5189+
} else {
5190+
addFailed(ManagedLedgerException.getManagedLedgerException(throwable),
5191+
publishContext);
5192+
}
5193+
return null;
5194+
}
51825195
// Message has been successfully persisted
5183-
messageDeduplication.recordMessagePersisted(publishContext,
5184-
position);
5185-
publishContext.setProperty("txn_id", txnID.toString());
5196+
try {
5197+
messageDeduplication.recordMessagePersisted(publishContext,
5198+
position);
5199+
publishContext.setProperty("txn_id", txnID.toString());
5200+
} catch (Throwable t) {
5201+
// The publish context hasn't been completed yet, so it can still be failed once
5202+
addFailed(ManagedLedgerException.getManagedLedgerException(t), publishContext);
5203+
return null;
5204+
}
51865205
publishContext.completed(null, position.getLedgerId(),
51875206
position.getEntryId());
51885207

51895208
decrementPendingWriteOpsAndCheck();
5209+
return null;
51905210
})
51915211
.exceptionally(throwable -> {
5192-
throwable = FutureUtil.unwrapCompletionException(throwable);
5193-
if (throwable instanceof NotAllowedException) {
5194-
publishContext.completed((NotAllowedException) throwable, -1, -1);
5195-
decrementPendingWriteOpsAndCheck();
5196-
} else {
5197-
addFailed(ManagedLedgerException.getManagedLedgerException(throwable), publishContext);
5198-
}
5212+
// Only reached when the handler above throws; the publish context is not completed again.
5213+
log.warn("[{}] Failed to handle the result of appending a transactional message,"
5214+
+ " txnId: {}", topic, txnID, throwable);
51995215
return null;
52005216
});
52015217
break;
Collapse file

‎pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java‎

Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java
+29Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import static org.mockito.Mockito.doAnswer;
3232
import static org.mockito.Mockito.doNothing;
3333
import static org.mockito.Mockito.doReturn;
34+
import static org.mockito.Mockito.doThrow;
3435
import static org.mockito.Mockito.eq;
3536
import static org.mockito.Mockito.matches;
3637
import static org.mockito.Mockito.mock;
@@ -74,6 +75,7 @@
7475
import java.util.concurrent.ExecutorService;
7576
import java.util.concurrent.Executors;
7677
import java.util.concurrent.Future;
78+
import java.util.concurrent.RejectedExecutionException;
7779
import java.util.concurrent.ScheduledFuture;
7880
import java.util.concurrent.TimeUnit;
7981
import java.util.concurrent.TimeoutException;
@@ -112,6 +114,8 @@
112114
import org.apache.pulsar.broker.service.persistent.PersistentTopic;
113115
import org.apache.pulsar.broker.service.persistent.PulsarCompactorSubscription;
114116
import org.apache.pulsar.broker.testcontext.PulsarTestContext;
117+
import org.apache.pulsar.broker.transaction.buffer.TransactionBuffer;
118+
import org.apache.pulsar.broker.transaction.buffer.TransactionBufferProvider;
115119
import org.apache.pulsar.client.admin.PulsarAdmin;
116120
import org.apache.pulsar.client.admin.Topics;
117121
import org.apache.pulsar.client.api.MessageId;
@@ -359,6 +363,31 @@ public void setMetadataFromEntryData(ByteBuf entryData) {
359363
"Topics without a replicated-subscription controller should not maintain the snapshot timestamp");
360364
}
361365

366+
@Test
367+
public void testPublishTxnMessageCompletesPublishContextOnce() throws Exception {
368+
pulsarTestContext.getConfig().setTransactionCoordinatorEnabled(true);
369+
TransactionBuffer transactionBuffer = mock(TransactionBuffer.class);
370+
doReturn(CompletableFuture.completedFuture(PositionFactory.create(1, 2)))
371+
.when(transactionBuffer).appendBufferToTxn(any(), anyLong(), any());
372+
TransactionBufferProvider transactionBufferProvider = mock(TransactionBufferProvider.class);
373+
doReturn(transactionBuffer).when(transactionBufferProvider).newTransactionBuffer(any());
374+
doReturn(transactionBufferProvider).when(pulsarTestContext.getPulsarService()).getTransactionBufferProvider();
375+
PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService);
376+
assertThat(topic.getTransactionBuffer()).isSameAs(transactionBuffer);
377+
378+
// Completing the publish context fails after it may have already handed itself over, e.g. when the
379+
// connection's executor rejects the task.
380+
Topic.PublishContext publishContext = mock(Topic.PublishContext.class);
381+
doThrow(new RejectedExecutionException("rejected"))
382+
.when(publishContext).completed(any(), anyLong(), anyLong());
383+
384+
topic.publishTxnMessage(new TxnID(1, 2), Unpooled.wrappedBuffer("content".getBytes()), publishContext);
385+
386+
// The failure must not complete the publish context a second time.
387+
verify(publishContext, times(1)).completed(any(), anyLong(), anyLong());
388+
verify(publishContext).completed(null, 1, 2);
389+
}
390+
362391
@Test
363392
public void testDispatcherMultiConsumerReadFailed() {
364393
PersistentTopic topic =
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java
+19-1Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import java.io.Closeable;
2929
import java.io.IOException;
3030
import java.time.Duration;
31+
import java.util.ArrayList;
3132
import java.util.List;
3233
import java.util.concurrent.CompletableFuture;
3334
import java.util.concurrent.ConcurrentLinkedQueue;
@@ -170,7 +171,7 @@ public CompletableFuture<Void> connectionOpened(ClientCnx cnx) {
170171
LOG.info("Transaction coordinator client connect success! tcId : {}", transactionCoordinatorId);
171172
if (registerToConnection(cnx)) {
172173
this.connectionHandler.resetBackoff();
173-
pendingRequests.forEach((requestID, opBase) -> checkStateAndSendRequest(opBase));
174+
resendPendingRequests();
174175
}
175176
future.complete(null);
176177
});
@@ -215,6 +216,18 @@ private boolean registerToConnection(ClientCnx cnx) {
215216
}
216217
}
217218

219+
private void resendPendingRequests() {
220+
// this method is executed in internalPinnedExecutor.
221+
List<Long> failedRequestIds = new ArrayList<>();
222+
pendingRequests.forEach((requestId, op) -> {
223+
if (!checkStateAndSendRequest(op)) {
224+
// The op has been completed and recycled, it must not stay in pendingRequests.
225+
failedRequestIds.add(requestId);
226+
}
227+
});
228+
failedRequestIds.forEach(pendingRequests::remove);
229+
}
230+
218231
private void failPendingRequest() {
219232
// this method is executed in internalPinnedExecutor.
220233
pendingRequests.forEach((k, op) -> {
@@ -817,6 +830,11 @@ public void close() throws IOException {
817830
this.setState(State.Closed);
818831
}
819832

833+
@VisibleForTesting
834+
int getPendingRequestsCount() {
835+
return (int) pendingRequests.size();
836+
}
837+
820838
@VisibleForTesting
821839
public State getConnectHandleState() {
822840
return getState();
Collapse file

‎pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java‎

Copy file name to clipboardExpand all lines: pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java
+41Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
1818
*/
1919
package org.apache.pulsar.client.impl;
2020

21+
import static org.assertj.core.api.Assertions.assertThat;
2122
import static org.mockito.ArgumentMatchers.any;
2223
import static org.mockito.ArgumentMatchers.anyLong;
24+
import static org.mockito.Mockito.doAnswer;
2325
import static org.mockito.Mockito.mock;
2426
import static org.mockito.Mockito.times;
2527
import static org.mockito.Mockito.verify;
@@ -29,7 +31,12 @@
2931
import io.netty.channel.Channel;
3032
import java.time.Duration;
3133
import java.util.concurrent.CompletableFuture;
34+
import java.util.concurrent.ExecutionException;
35+
import java.util.concurrent.TimeUnit;
36+
import lombok.Cleanup;
3237
import org.apache.pulsar.client.api.PulsarClient;
38+
import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException;
39+
import org.apache.pulsar.client.api.transaction.TxnID;
3340
import org.awaitility.Awaitility;
3441
import org.testng.annotations.Test;
3542

@@ -62,4 +69,38 @@ public void testStateChangeFailure() throws Exception {
6269

6370
client.close();
6471
}
72+
73+
@Test
74+
public void testFailedResendOnReconnectRemovesPendingRequest() throws Exception {
75+
@Cleanup
76+
final PulsarClientImpl client = (PulsarClientImpl) PulsarClient.builder()
77+
.serviceUrl("pulsar://localhost:6650").build();
78+
final CompletableFuture<Void> connectFuture = new CompletableFuture<>();
79+
final TransactionMetaStoreHandler handler = new TransactionMetaStoreHandler(
80+
0L, client, "topic", connectFuture);
81+
82+
// Not connected yet: the request stays queued until the connection is opened.
83+
handler.setState(HandlerState.State.Connecting);
84+
final CompletableFuture<TxnID> txnFuture = handler.newTransactionAsync(1, TimeUnit.MINUTES);
85+
Awaitility.await().untilAsserted(() -> assertEquals(handler.getPendingRequestsCount(), 1));
86+
87+
final ClientCnx cnx = mock(ClientCnx.class);
88+
when(cnx.getRemoteEndpointProtocolVersion()).thenReturn(19);
89+
when(cnx.sendRequestWithId(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null));
90+
when(cnx.channel()).thenReturn(mock(Channel.class));
91+
// The handler is closed concurrently after it switched to Ready, but before it resends the pending
92+
// requests, so resending them fails.
93+
doAnswer(invocation -> {
94+
handler.close();
95+
return null;
96+
}).when(cnx).registerTransactionMetaStoreHandler(anyLong(), any());
97+
98+
handler.connectionOpened(cnx).get(10, TimeUnit.SECONDS);
99+
100+
assertThat(txnFuture).failsWithin(Duration.ofSeconds(10))
101+
.withThrowableOfType(ExecutionException.class)
102+
.withCauseInstanceOf(TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException.class);
103+
// The failed request has been completed and its op recycled, so it must not stay pending.
104+
assertEquals(handler.getPendingRequestsCount(), 0);
105+
}
65106
}
Collapse file

‎pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java‎

Copy file name to clipboardExpand all lines: pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java
+12-1Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
package org.apache.pulsar.transaction.coordinator.impl;
2020

2121
import static org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerInterceptException;
22+
import com.google.common.annotations.VisibleForTesting;
2223
import io.netty.buffer.ByteBuf;
2324
import io.netty.buffer.Unpooled;
2425
import io.netty.util.Recycler;
@@ -271,9 +272,15 @@ private void internalAsyncAddData(T data, AddDataCallback callback, Object ctx){
271272
trigFlushIfReachMaxRecordsOrMaxSize();
272273
}
273274

274-
private void trigFlushByTimingTask(){
275+
@VisibleForTesting
276+
void trigFlushByTimingTask(){
275277
CompletableFuture
276278
.runAsync(() -> {
279+
// A timing flush that was queued before "close()" may run after the close task has recycled the
280+
// flush context, which may already be reused by another writer that shares this executor.
281+
if (state == State.CLOSING || state == State.CLOSED) {
282+
return;
283+
}
277284
if (flushContext.asyncAddArgsList.isEmpty()) {
278285
return;
279286
}
@@ -387,6 +394,10 @@ public CompletableFuture<Void> close() {
387394
new ManagedLedgerException.ManagedLedgerFencedException(
388395
new Exception("Transaction log buffered write has closed")
389396
));
397+
// The recycled flush context may be reused by another writer, don't keep a reference to it.
398+
flushContext = null;
399+
dataArray.clear();
400+
bytesSize = 0;
390401
// Cancel the timing task.
391402
if (!timeout.isCancelled()) {
392403
this.timeout.cancel();
Collapse file

‎pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java‎

Copy file name to clipboardExpand all lines: pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java
+63Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@
4040
import java.util.concurrent.ConcurrentHashMap;
4141
import java.util.concurrent.ExecutionException;
4242
import java.util.concurrent.Executor;
43+
import java.util.concurrent.ExecutorService;
44+
import java.util.concurrent.Executors;
4345
import java.util.concurrent.ScheduledExecutorService;
4446
import java.util.concurrent.ThreadPoolExecutor;
4547
import java.util.concurrent.TimeUnit;
@@ -540,6 +542,67 @@ public void testPendingScheduleTriggerTaskCount() throws Exception {
540542
threadPoolExecutor.shutdown();
541543
}
542544

545+
/**
546+
* A timing flush that runs after {@link TxnLogBufferedWriter#close()} must not touch the flush context that the
547+
* close task recycled: writers share the executor thread, so another writer may already be using the recycled
548+
* flush context.
549+
*/
550+
@Test
551+
public void testTimingFlushAfterCloseDoesNotAffectOtherWriter() throws Exception {
552+
ManagedLedger managedLedger = Mockito.mock(ManagedLedger.class);
553+
Mockito.when(managedLedger.getName()).thenReturn(mlName);
554+
Mockito.doAnswer(invocation -> {
555+
AsyncCallbacks.AddEntryCallback callback = invocation.getArgument(1);
556+
callback.addComplete(PositionFactory.create(1, 1), invocation.getArgument(0),
557+
invocation.getArgument(2));
558+
return null;
559+
}).when(managedLedger).asyncAddEntry(Mockito.any(ByteBuf.class), Mockito.any(), Mockito.any());
560+
// Both writers share the same single thread, like the writers of the topics that share a ML executor.
561+
ExecutorService sharedExecutor =
562+
Executors.newSingleThreadExecutor(new DefaultThreadFactory("txn-shared-executor"));
563+
HashedWheelTimer transactionTimer = new HashedWheelTimer(new DefaultThreadFactory("transaction-timer"),
564+
1, TimeUnit.MILLISECONDS);
565+
SumStrDataSerializer dataSerializer = new SumStrDataSerializer();
566+
TxnLogBufferedWriter.AddDataCallback callbackA = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class);
567+
TxnLogBufferedWriter.AddDataCallback callbackB = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class);
568+
try {
569+
TxnLogBufferedWriter<Integer> writerA = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor,
570+
transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true,
571+
DISABLED_BUFFERED_WRITER_METRICS);
572+
// Flush once, so that writer A's current flush context is obtained on the shared executor thread.
573+
writerA.asyncAddData(1, callbackA, 1);
574+
writerA.asyncAddData(1, callbackA, 2);
575+
Awaitility.await().untilAsserted(() ->
576+
Mockito.verify(callbackA, Mockito.times(2)).addComplete(Mockito.any(), Mockito.any()));
577+
// Closing recycles writer A's current flush context on the shared executor thread.
578+
writerA.close().get();
579+
580+
TxnLogBufferedWriter<Integer> writerB = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor,
581+
transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true,
582+
DISABLED_BUFFERED_WRITER_METRICS);
583+
// The flush obtains a new flush context, which may be the one that writer A recycled.
584+
writerB.asyncAddData(1, callbackB, 1);
585+
writerB.asyncAddData(1, callbackB, 2);
586+
// This request stays in writer B's current flush context.
587+
writerB.asyncAddData(1, callbackB, 3);
588+
sharedExecutor.submit(() -> { }).get();
589+
590+
// A timing flush of the closed writer A, e.g. one that was queued before the close task ran.
591+
writerA.trigFlushByTimingTask();
592+
sharedExecutor.submit(() -> { }).get();
593+
Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any());
594+
595+
writerB.trigFlushByTimingTask();
596+
Awaitility.await().untilAsserted(() ->
597+
Mockito.verify(callbackB, Mockito.times(3)).addComplete(Mockito.any(), Mockito.any()));
598+
Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any());
599+
writerB.close().get();
600+
} finally {
601+
transactionTimer.stop();
602+
sharedExecutor.shutdownNow();
603+
}
604+
}
605+
543606
private static class JsonDataSerializer implements TxnLogBufferedWriter.DataSerializer<Integer>{
544607

545608
private static ObjectMapper objectMapper = new ObjectMapper();

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.