chia7712 commented on code in PR #23663:
URL: https://github.com/apache/kafka/pull/23663#discussion_r4651736491
##########
clients/src/main/java/org/apache/kafka/clients/producer/internals/TxnPartitionEntry.java:
##########
@@ -149,6 +183,17 @@ void adjustSequencesDueToFailedBatch(long baseSequence,
int recordCount) {
inFlightBatch.resetProducerState(new
ProducerIdAndEpoch(inFlightBatch.producerId(), inFlightBatch.producerEpoch()),
newSequence);
});
+
+ // The failed batch was never appended, so it no longer occupies a
sequence range, and the completed batches
+ // after it move down along with the in-flight ones. The failed batch
itself may have been recorded as
+ // completed ahead of the oldest in-flight batch when it was removed
from the in-flight set, so drop it first.
+ completedSequencesAheadOfOldestInflight.remove(baseSequence);
Review Comment:
```java
completedSequencesAheadOfOldestInflight.remove(baseSequence);
var tail =
completedSequencesAheadOfOldestInflight.tailSet(baseSequence, false);
var shifted = tail.stream().map(s -> s -
recordCount).collect(Collectors.toUnmodifiableList());
tail.clear();
completedSequencesAheadOfOldestInflight.addAll(shifted);
```
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java:
##########
@@ -2398,6 +2400,270 @@ public void testSequenceNumberIncrement() throws
InterruptedException {
assertEquals(1L, transactionManager.sequenceNumber(tp0));
}
+ @Test
+ public void
testNewBatchesAreHeldBackWhileOldestInFlightBatchCouldLeaveBrokerDeduplicationWindow()
throws Exception {
+ final long producerId = 343434L;
+ TransactionManager transactionManager = createTransactionManager();
+ setupWithTransactionState(transactionManager);
+ prepareAndReceiveInitProducerId(producerId, Errors.NONE);
+ assertTrue(transactionManager.hasProducerId());
+
+ // Each `runOnce` drains at most one batch per partition. No response
is given yet, so the batches stay in
+ // flight and fill up the window the broker retains for duplicate
detection.
+ int window = RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER;
+ for (int i = 0; i < window; i++) {
+ appendToAccumulator(tp0);
+ sender.runOnce();
+ assertEquals(i + 1, sender.inFlightBatches(tp0).size());
+ }
+ List<ClientRequest> requests = new ArrayList<>(client.requests());
+ assertEquals(window, requests.size());
+
+ // Acknowledge every batch but the first, as a new leader would while
the first is still in flight to the
+ // previous leader. The first batch is now the oldest one the broker
retains and there is no room after it,
+ // even though only one batch is still in flight.
+ for (int i = 1; i < window; i++) {
+ client.respondToRequest(requests.get(i), produceResponse(tp0, i,
Errors.NONE, 0));
+ }
+ sender.runOnce(); // receive the responses
+ assertEquals(1, sender.inFlightBatches(tp0).size());
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // A new batch for tp0 is held back: appending it would make the
broker forget the first batch, so a retry
+ // of that batch would fail with OUT_OF_ORDER_SEQUENCE. Other
partitions of the same node are unaffected.
+ Future<RecordMetadata> heldBack = appendToAccumulator(tp0);
+ appendToAccumulator(tp1);
+ sender.runOnce();
+ assertEquals(1, sender.inFlightBatches(tp0).size());
+ assertFalse(heldBack.isDone());
+ assertEquals(1, sender.inFlightBatches(tp1).size());
+ assertTrue(accumulator.hasUndrained());
+
+ // Once the first batch completes, the held back batch is sent.
+ client.respondToRequest(requests.get(0), produceResponse(tp0, 0,
Errors.NONE, 0));
+ sender.runOnce(); // receive the response
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ sender.runOnce(); // send the held back batch
+ assertEquals(1, sender.inFlightBatches(tp0).size());
+ assertEquals(window,
sender.inFlightBatches(tp0).get(0).baseSequence());
+ assertFalse(accumulator.hasUndrained());
+ }
+
+ @Test
+ public void
testNewBatchesAreHeldBackWhileOldestBatchIsStuckOnPreviousLeader() throws
Exception {
+ final long producerId = 343434L;
+ final Node previousLeader = new Node(0, "localhost", 1969);
+ final Node newLeader = new Node(1, "localhost", 1970);
+ TransactionManager transactionManager = createTransactionManager();
+ setupWithTransactionState(transactionManager, false, null, false);
+ client.updateMetadata(metadataWithTp0Leader(previousLeader, 100));
+ prepareAndReceiveInitProducerId(producerId, Errors.NONE);
+ assertTrue(transactionManager.hasProducerId());
+
+ // The first batch is sent to the previous leader, which never answers.
+ Future<RecordMetadata> stuck = appendToAccumulator(tp0);
+ runUntilRequestsInFlight(previousLeader, 1);
+ ClientRequest stuckRequest = client.requests().peek();
+ assertEquals(0, sender.inFlightBatches(tp0).get(0).baseSequence());
+
+ // The leader moves to another broker. The following batches are sent
there and acknowledged, so the new
+ // leader now holds four batches after the stuck one in its
deduplication window.
+ client.updateMetadata(metadataWithTp0Leader(newLeader, 101));
+ int window = RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER;
+ for (int i = 1; i < window; i++) {
+ Future<RecordMetadata> future = appendToAccumulator(tp0);
+ runUntilRequestsInFlight(newLeader, 1);
+ client.respondFrom(produceResponse(tp0, i, Errors.NONE, 0),
newLeader);
+ sender.runOnce(); // receive the response
+ assertEquals(i, future.get().offset());
+ }
+ assertEquals(1, client.inFlightRequestCount());
+ assertEquals(1, sender.inFlightBatches(tp0).size());
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // A new batch for tp0 is held back while the first batch is
unresolved. Without this the new leader would
+ // forget the first batch, and the first batch's retry would fail with
OUT_OF_ORDER_SEQUENCE.
+ Future<RecordMetadata> heldBack = appendToAccumulator(tp0);
+ sender.runOnce(); // nothing is sent
+ sender.runOnce(); // make sure nothing is sent on a later pass either
+ assertEquals(0, client.inFlightRequestCount(newLeader.idString()));
+ assertEquals(1, sender.inFlightBatches(tp0).size());
+ assertEquals(0, sender.inFlightBatches(tp0).get(0).baseSequence());
+ assertFalse(heldBack.isDone());
+ assertTrue(accumulator.hasUndrained());
+
+ // The previous leader finally rejects the first batch. Its retry goes
to the new leader straight away,
+ // and is still recognised there. Only then is the held back batch
sent.
+ client.respondToRequest(stuckRequest, produceResponse(tp0, -1,
Errors.NOT_LEADER_OR_FOLLOWER, 0));
+ sender.runOnce(); // receive the response, re-enqueue the first batch
+ runUntilRequestsInFlight(newLeader, 1);
+ assertEquals(0, sender.inFlightBatches(tp0).get(0).baseSequence());
+ assertFalse(heldBack.isDone());
+ client.respondFrom(produceResponse(tp0, 0, Errors.NONE, 0), newLeader);
+ sender.runOnce(); // receive the response
+ assertEquals(0L, stuck.get().offset());
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ runUntilRequestsInFlight(newLeader, 1);
+ assertEquals(window,
sender.inFlightBatches(tp0).get(0).baseSequence());
+ client.respondFrom(produceResponse(tp0, window, Errors.NONE, 0),
newLeader);
+ sender.runOnce();
+ assertEquals(window, heldBack.get().offset());
+ assertFalse(accumulator.hasUndrained());
+ }
+
+ private ClientRequest lastRequest() {
+ List<ClientRequest> requests = new ArrayList<>(client.requests());
+ return requests.get(requests.size() - 1);
+ }
+
+ private ProducerBatch lastInFlightBatch(TopicPartition tp) {
+ List<ProducerBatch> batches = sender.inFlightBatches(tp);
+ return batches.get(batches.size() - 1);
+ }
+
+ private MetadataResponse metadataWithTp0Leader(Node leader, int
leaderEpoch) {
+ return RequestTestUtils.metadataUpdateWith("kafka-cluster", 2,
Collections.emptyMap(),
Review Comment:
```java
private MetadataResponse metadataWithTp0Leader(Node leader, int
leaderEpoch) {
return RequestTestUtils.metadataUpdateWith("kafka-cluster", 2,
Map.of(),
Map.of(TOPIC_NAME, 2), tp -> leaderEpoch,
(error, tp, leaderId, epoch, replicas, isr, offline) -> new
MetadataResponse.PartitionMetadata(
error, tp, tp0.equals(tp) ? Optional.of(leader.id()) :
leaderId, epoch, replicas, isr, offline),
ApiKeys.METADATA.latestVersion(), TOPIC_IDS);
}
```
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java:
##########
@@ -2398,6 +2400,270 @@ public void testSequenceNumberIncrement() throws
InterruptedException {
assertEquals(1L, transactionManager.sequenceNumber(tp0));
}
+ @Test
+ public void
testNewBatchesAreHeldBackWhileOldestInFlightBatchCouldLeaveBrokerDeduplicationWindow()
throws Exception {
+ final long producerId = 343434L;
+ TransactionManager transactionManager = createTransactionManager();
+ setupWithTransactionState(transactionManager);
+ prepareAndReceiveInitProducerId(producerId, Errors.NONE);
+ assertTrue(transactionManager.hasProducerId());
+
+ // Each `runOnce` drains at most one batch per partition. No response
is given yet, so the batches stay in
+ // flight and fill up the window the broker retains for duplicate
detection.
+ int window = RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER;
+ for (int i = 0; i < window; i++) {
+ appendToAccumulator(tp0);
+ sender.runOnce();
+ assertEquals(i + 1, sender.inFlightBatches(tp0).size());
+ }
+ List<ClientRequest> requests = new ArrayList<>(client.requests());
Review Comment:
```java
List<ClientRequest> requests = List.copyOf(client.requests());
```
##########
clients/src/test/java/org/apache/kafka/clients/producer/internals/TransactionManagerTest.java:
##########
@@ -634,6 +635,230 @@ public void testDefaultSequenceNumber(boolean
transactionV2Enabled) {
assertEquals(3, transactionManager.sequenceNumber(tp0));
}
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void testBrokerDeduplicationWindowIsTrackedPerPartition(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.empty(), transactionV2Enabled);
+ initializeIdempotentProducerId(producerId, epoch);
+
+ List<ProducerBatch> batches = new ArrayList<>();
+ for (int i = 0; i < RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER;
i++) {
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ batches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
String.valueOf(i)));
+ }
+ // Four batches have been sent after the oldest one, so one more could
make the broker forget it.
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // The window is tracked per partition, so a full window on tp0 says
nothing about tp1.
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp1));
+
+ // Completing the oldest batch, as happens when responses arrive in
order, makes room for another batch.
+ completeIdempotentBatch(batches.get(0), 500L);
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ batches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
"5"));
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void
testBatchesCompletedAheadOfOldestInflightBatchStayInBrokerDeduplicationWindow(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.empty(), transactionV2Enabled);
+ initializeIdempotentProducerId(producerId, epoch);
+
+ List<ProducerBatch> batches = new ArrayList<>();
+ for (int i = 0; i < RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER;
i++) {
+ batches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
String.valueOf(i)));
+ }
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // Completing every batch except the oldest, as a new leader does
while the oldest is still in flight to
+ // the previous one, does not make room: those batches were still
appended after the oldest one, so the
+ // broker would forget it if one more were sent.
+ for (int i = 1; i < batches.size(); i++) {
+ completeIdempotentBatch(batches.get(i), 500L + i);
+ }
+ assertEquals(0, transactionManager.firstInFlightSequence(tp0));
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // Once the oldest batch completes nothing is in flight anymore, and
the window is empty again.
+ completeIdempotentBatch(batches.get(0), 500L);
+ assertFalse(transactionManager.hasInflightBatches(tp0));
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // Batches that completed ahead of the oldest one only count while a
batch older than them is in flight.
+ List<ProducerBatch> nextBatches = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ nextBatches.add(writeIdempotentBatchWithValue(transactionManager,
tp0, String.valueOf(10 + i)));
+ }
+ completeIdempotentBatch(nextBatches.get(2), 600L);
+ completeIdempotentBatch(nextBatches.get(0), 601L);
+ // Only the third batch is ahead of the second, which is now the
oldest in flight.
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ nextBatches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
"13"));
+ nextBatches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
"14"));
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ nextBatches.add(writeIdempotentBatchWithValue(transactionManager, tp0,
"15"));
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void
testSplitBatchKeepsBatchesCompletedAheadOfItInBrokerDeduplicationWindow(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.empty(), transactionV2Enabled);
+ initializeIdempotentProducerId(producerId, epoch);
+ transactionManager.maybeUpdateProducerIdAndEpoch(tp0);
+
+ // A batch with two records at sequence 0, followed by batches at
sequences 2 and 3.
+ ProducerBatch bigBatch = writeBatchWithValues(transactionManager, tp0,
false, "0", "1");
+ assertEquals(2, bigBatch.recordCount);
+ ProducerBatch second =
writeIdempotentBatchWithValue(transactionManager, tp0, "2");
+ ProducerBatch third =
writeIdempotentBatchWithValue(transactionManager, tp0, "3");
+ assertEquals(2, second.baseSequence());
+ assertEquals(3, third.baseSequence());
+
+ // The second batch is acknowledged while the first is still in
flight. The first is then rejected as too
+ // large and split, which re-adds the split batches with the sequences
of the records they hold.
+ completeIdempotentBatch(second, 500L);
+ transactionManager.removeInFlightBatch(bigBatch);
+ for (int sequence = 0; sequence < bigBatch.recordCount; sequence++) {
+ ProducerBatch splitBatch = batchWithValue(tp0,
String.valueOf(sequence));
+
splitBatch.setProducerState(transactionManager.producerIdAndEpoch(), sequence,
false);
+ transactionManager.addInFlightBatch(splitBatch);
+ splitBatch.close();
+ }
+
+ // The batches at sequences 1, 2 and 3 were all sent after the split
batch at sequence 0, so only one more
+ // batch fits in the window, even though the second batch completed
before the split.
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ writeIdempotentBatchWithValue(transactionManager, tp0, "4");
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void
testSplitOfBatchBehindOldestInflightBatchIsNotCountedTwiceInBrokerDeduplicationWindow(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.empty(), transactionV2Enabled);
+ initializeIdempotentProducerId(producerId, epoch);
+ transactionManager.maybeUpdateProducerIdAndEpoch(tp0);
+
+ // A batch at sequence 0, a batch with two records at sequence 1, and
a batch at sequence 3.
+ ProducerBatch first =
writeIdempotentBatchWithValue(transactionManager, tp0, "0");
+ ProducerBatch bigBatch = writeBatchWithValues(transactionManager, tp0,
false, "1", "2");
+ ProducerBatch third =
writeIdempotentBatchWithValue(transactionManager, tp0, "3");
+ assertEquals(0, first.baseSequence());
+ assertEquals(1, bigBatch.baseSequence());
+ assertEquals(2, bigBatch.recordCount);
+ assertEquals(3, third.baseSequence());
+
+ // The third batch is acknowledged, then the big batch is rejected as
too large and split while the first
+ // batch is still in flight. The big batch is removed and re-added
with the sequences it had, so it must
+ // not be counted both as completed and as in flight.
+ completeIdempotentBatch(third, 500L);
+ transactionManager.removeInFlightBatch(bigBatch);
+ for (int sequence = bigBatch.baseSequence(); sequence <
bigBatch.baseSequence() + bigBatch.recordCount; sequence++) {
+ ProducerBatch splitBatch = batchWithValue(tp0,
String.valueOf(sequence));
+
splitBatch.setProducerState(transactionManager.producerIdAndEpoch(), sequence,
false);
+ transactionManager.addInFlightBatch(splitBatch);
+ splitBatch.close();
+ }
+
+ // Sequences 1, 2 and 3 were sent after the first batch, so one more
batch fits in the window.
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ writeIdempotentBatchWithValue(transactionManager, tp0, "4");
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void
testFatallyFailedBatchShiftsBatchesCompletedAheadOfOldestInflightBatch(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.of(transactionalId),
transactionV2Enabled);
+ doInitTransactions();
+ transactionManager.beginTransaction();
+
+ // Five batches, of which batch 2 holds two records, so the batches
have sequences 0, 1, 2, 4 and 5.
+ List<ProducerBatch> batches = new ArrayList<>();
+ batches.add(writeTransactionalBatchWithValue(transactionManager, tp0,
"0"));
+ batches.add(writeTransactionalBatchWithValue(transactionManager, tp0,
"1"));
+ batches.add(writeBatchWithValues(transactionManager, tp0, true, "2",
"3"));
+ batches.add(writeTransactionalBatchWithValue(transactionManager, tp0,
"4"));
+ batches.add(writeTransactionalBatchWithValue(transactionManager, tp0,
"5"));
+ assertEquals(2, batches.get(2).recordCount);
+ assertEquals(4, batches.get(3).baseSequence());
+ assertEquals(5, batches.get(4).baseSequence());
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // Batches 1 and 4 complete while batch 0 is still in flight.
+ completeIdempotentBatch(batches.get(1), 501L);
+ completeIdempotentBatch(batches.get(4), 505L);
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+
+ // Batch 2 fails fatally and the sequences after it are moved down by
its two records. Batch 4 was appended
+ // after batch 0 and keeps taking up room in the window at its new
sequence, batch 1 is unaffected, and the
+ // failed batch itself no longer counts.
+ transactionManager.handleFailedBatch(batches.get(2), new
TimeoutException(), true);
+ assertEquals(0, transactionManager.firstInFlightSequence(tp0));
+ assertEquals(2, batches.get(3).baseSequence());
+ assertEquals(4, transactionManager.sequenceNumber(tp0));
+
+ // Batches 1, 3 and 4 are ahead of batch 0, so exactly one more batch
fits in the window.
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ writeTransactionalBatchWithValue(transactionManager, tp0, "6");
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ public void
testEpochBumpForgetsBatchesCompletedAheadOfOldestInflightBatch(boolean
transactionV2Enabled) {
+ initializeTransactionManager(Optional.empty(), transactionV2Enabled);
+ initializeIdempotentProducerId(producerId, epoch);
+
+ ProducerBatch b0 = writeIdempotentBatchWithValue(transactionManager,
tp0, "0");
+ ProducerBatch b1 = writeIdempotentBatchWithValue(transactionManager,
tp0, "1");
+ ProducerBatch b2 = writeIdempotentBatchWithValue(transactionManager,
tp0, "2");
+ completeIdempotentBatch(b2, 502L);
+
+ // The epoch is bumped and the in-flight batches are resent from
sequence 0 under the new epoch. The broker's
+ // state for the partition starts over with them, so batch 2 no longer
takes up room in its window.
+ transactionManager.requestIdempotentEpochBumpForPartition(tp0);
+ transactionManager.bumpIdempotentEpochAndResetIdIfNeeded();
+ assertEquals((short) (epoch + 1), b0.producerEpoch());
+ assertEquals(0, b0.baseSequence());
+ assertEquals(1, b1.baseSequence());
+ assertEquals(2, transactionManager.sequenceNumber(tp0));
+
+ // Only batch 1 is ahead of batch 0, so three more batches fit in the
window.
+ for (int i = 0; i < RecordBatch.NUM_BATCHES_RETAINED_PER_PRODUCER - 2;
i++) {
+
assertFalse(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ writeIdempotentBatchWithValue(transactionManager, tp0,
String.valueOf(10 + i));
+ }
+
assertTrue(transactionManager.wouldExceedBrokerDeduplicationWindow(tp0));
+ }
+
+ private ProducerBatch writeBatchWithValues(TransactionManager manager,
+ TopicPartition tp,
+ boolean isTransactional,
+ String... values) {
+ manager.maybeUpdateProducerIdAndEpoch(tp);
+ long now = time.milliseconds();
+ ProducerBatch batch = new ProducerBatch(tp,
MemoryRecords.builder(ByteBuffer.allocate(1024),
+ Compression.NONE, TimestampType.CREATE_TIME, 0L), now);
+ for (String value : values) {
+ batch.tryAppend(now, new byte[0], value.getBytes(), new Header[0],
null, now);
Review Comment:
```java
value.getBytes(StandardCharsets.UTF_8)
```
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]