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 — KAFKA-21344: Handle partition rotation for share fetches (#23951) · coderbruis/kafka@d193373

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • clients/clients-integration-tests/src/test/java/org/apache/kafka/clients/consumer
    • ShareConsumerFairnessTest.java
  • core/src
    • main
      • java/kafka/server/share
        • ShareFetchUtils.java
        • SharePartitionManager.java
      • scala/kafka/server
        • KafkaApis.scala
    • test
      • java/kafka/server/share
        • ShareFetchUtilsTest.java
        • SharePartitionManagerTest.java
      • scala/unit/kafka/server
        • KafkaApisTest.scala
  • server/src
    • main/java/org/apache/kafka/server/share
      • context
        • ShareSessionContext.java
      • fetch
        • PartitionRotateStrategy.java
        • ShareFetch.java
    • test/java/org/apache/kafka/server/share/fetch
      • PartitionRotateStrategyTest.java
      • ShareFetchTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎clients/clients-integration-tests/src/test/java/org/apache/kafka/clients/consumer/ShareConsumerFairnessTest.java‎

Copy file name to clipboardExpand all lines: clients/clients-integration-tests/src/test/java/org/apache/kafka/clients/consumer/ShareConsumerFairnessTest.java
+200-12Lines changed: 200 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
package org.apache.kafka.clients.consumer;
1818

1919
import org.apache.kafka.clients.producer.Producer;
20+
import org.apache.kafka.clients.producer.ProducerConfig;
2021
import org.apache.kafka.clients.producer.ProducerRecord;
22+
import org.apache.kafka.common.record.internal.DefaultRecordBatch;
23+
import org.apache.kafka.common.record.internal.SimpleRecord;
2124
import org.apache.kafka.common.test.ClusterInstance;
2225
import org.apache.kafka.common.test.api.ClusterConfigProperty;
2326
import org.apache.kafka.common.test.api.ClusterTest;
@@ -27,6 +30,8 @@
2730
import org.junit.jupiter.api.Timeout;
2831

2932
import java.time.Duration;
33+
import java.util.ArrayList;
34+
import java.util.List;
3035
import java.util.Map;
3136
import java.util.Set;
3237
import java.util.TreeMap;
@@ -59,24 +64,21 @@ public class ShareConsumerFairnessTest extends ShareConsumerTestBase {
5964
private static final int PARTITIONS = 2;
6065
private static final int RECORDS_PER_PARTITION = 8000;
6166
private static final int MAX_POLL_RECORDS = 100;
67+
private static final int POLLS_PER_PHASE = 20;
68+
private static final int RECORD_VALUE_SIZE = 1024;
69+
// Size on the log of a single record batch holding one record with a value of RECORD_VALUE_SIZE bytes.
70+
private static final int RECORD_SIZE = DefaultRecordBatch.sizeInBytes(List.of(new SimpleRecord(new byte[RECORD_VALUE_SIZE])));
6271

6372
public ShareConsumerFairnessTest(ClusterInstance cluster) {
6473
super(cluster);
6574
}
6675

6776
@ClusterTest
68-
public void testPartitionsWithDeepBacklogAreServedFairly() throws Exception {
77+
public void testPartitionsServedFairlyInImplicitMode() {
6978
String topic = "fairness";
7079
String groupId = "fairness-group";
7180
createTopic(topic, PARTITIONS, 1);
72-
try (Producer<byte[], byte[]> producer = createProducer()) {
73-
for (int i = 0; i < RECORDS_PER_PARTITION; i++) {
74-
for (int p = 0; p < PARTITIONS; p++) {
75-
producer.send(new ProducerRecord<>(topic, p, null, null, "value".getBytes()));
76-
}
77-
}
78-
producer.flush();
79-
}
81+
produceRecords(topic, PARTITIONS);
8082
alterShareAutoOffsetReset(groupId, "earliest");
8183

8284
Map<Integer, Integer> recordsByPartition = new TreeMap<>();
@@ -102,12 +104,198 @@ public void testPartitionsWithDeepBacklogAreServedFairly() throws Exception {
102104

103105
assertEquals(Map.of(0, RECORDS_PER_PARTITION, 1, RECORDS_PER_PARTITION), recordsByPartition);
104106
for (int p = 0; p < PARTITIONS; p++) {
105-
// Both partitions have a deep backlog, hence neither should have been starved while the other was
106-
// being served, i.e. each has a meaningful share of the records when the first partition completes.
107+
// Both partitions have a deep backlog and the fetches alternate between them, hence the other partition
108+
// is only a few polls behind when the first partition completes. Allow a generous buffer, a starved
109+
// partition is far below it.
107110
int recordsOfPartition = recordsWhenFirstPartitionCompleted.getOrDefault(p, 0);
108-
assertTrue(recordsOfPartition * 5 >= RECORDS_PER_PARTITION,
111+
assertTrue(recordsOfPartition * 4 >= RECORDS_PER_PARTITION * 3,
109112
"Partition " + p + " was starved, records by partition when the first partition completed: "
110113
+ recordsWhenFirstPartitionCompleted);
111114
}
112115
}
116+
117+
@ClusterTest
118+
public void testPartitionsServedFairlyWithExplicitAcknowledgements() {
119+
verifyPartitionsServedFairlyWithExplicitAcknowledgements("fairness-epoch-parity", PARTITIONS);
120+
verifyPartitionsServedFairlyWithExplicitAcknowledgements("fairness-epoch-parity-odd", 3);
121+
}
122+
123+
@ClusterTest
124+
public void testPartitionsRotateWhenAllPartitionsReturnRecordsWithExplicitAcknowledgement() {
125+
verifyFirstPositionRotatesWhenAllPartitionsReturnRecords("fairness-rotation", PARTITIONS, "explicit");
126+
verifyFirstPositionRotatesWhenAllPartitionsReturnRecords("fairness-rotation-odd", 3, "explicit");
127+
}
128+
129+
@ClusterTest
130+
public void testPartitionsRotateWhenAllPartitionsReturnRecordsWithImplicitAcknowledgement() {
131+
verifyFirstPositionRotatesWhenAllPartitionsReturnRecords("fairness-rotation-implicit", 3, "implicit");
132+
}
133+
134+
/**
135+
* A partition which does not return records keeps its position at the front of the share session, hence
136+
* it is read first as soon as it has records, ahead of the partition which was served all along.
137+
*/
138+
@ClusterTest
139+
public void testPartitionWithoutRecordsIsReadFirstWhenRecordsArrive() {
140+
String topic = "fairness-idle-partition";
141+
String groupId = "fairness-idle-partition-group";
142+
int lateRecords = MAX_POLL_RECORDS / 2;
143+
createTopic(topic, PARTITIONS, 1);
144+
// Only partition 0 has records initially.
145+
try (Producer<byte[], byte[]> producer = createProducer()) {
146+
for (int i = 0; i < RECORDS_PER_PARTITION; i++) {
147+
producer.send(new ProducerRecord<>(topic, 0, null, null, "value".getBytes()));
148+
}
149+
producer.flush();
150+
}
151+
alterShareAutoOffsetReset(groupId, "earliest");
152+
153+
try (ShareConsumer<byte[], byte[]> consumer = createShareConsumer(groupId, Map.of(
154+
ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(MAX_POLL_RECORDS),
155+
ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG, "record_limit",
156+
ConsumerConfig.SHARE_ACKNOWLEDGEMENT_MODE_CONFIG, "explicit"))) {
157+
consumer.subscribe(Set.of(topic));
158+
Map<Integer, Integer> recordsByPartition = pollAndCommit(consumer);
159+
assertEquals(Map.of(0, MAX_POLL_RECORDS * POLLS_PER_PHASE), recordsByPartition);
160+
161+
// Partition 1 gets records, fewer than a single poll can return.
162+
try (Producer<byte[], byte[]> producer = createProducer()) {
163+
for (int i = 0; i < lateRecords; i++) {
164+
producer.send(new ProducerRecord<>(topic, 1, null, null, "value".getBytes()));
165+
}
166+
producer.flush();
167+
}
168+
169+
// The next poll returns all the records of partition 1 and fills up from partition 0.
170+
Map<Integer, Integer> nextPoll = new TreeMap<>();
171+
pollRecords(consumer).forEach(record -> nextPoll.merge(record.partition(), 1, Integer::sum));
172+
assertEquals(Map.of(0, MAX_POLL_RECORDS - lateRecords, 1, lateRecords), nextPoll);
173+
}
174+
}
175+
176+
private void verifyPartitionsServedFairlyWithExplicitAcknowledgements(String topic, int partitions) {
177+
String groupId = topic + "-group";
178+
createTopic(topic, partitions, 1);
179+
produceRecords(topic, partitions);
180+
alterShareAutoOffsetReset(groupId, "earliest");
181+
182+
Map<Integer, Integer> afterSingleAcknowledgement;
183+
Map<Integer, Integer> afterMultipleAcknowledgements;
184+
try (ShareConsumer<byte[], byte[]> consumer = createShareConsumer(groupId, Map.of(
185+
ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(MAX_POLL_RECORDS),
186+
ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG, "record_limit",
187+
ConsumerConfig.SHARE_ACKNOWLEDGEMENT_MODE_CONFIG, "explicit"))) {
188+
consumer.subscribe(Set.of(topic));
189+
afterSingleAcknowledgement = pollAndCommit(consumer);
190+
191+
// Commit the acknowledgements of one poll in two requests, which flips the parity of the epoch.
192+
List<ConsumerRecord<byte[], byte[]>> records = pollRecords(consumer);
193+
int half = records.size() / 2;
194+
records.subList(0, half).forEach(consumer::acknowledge);
195+
consumer.commitSync();
196+
records.subList(half, records.size()).forEach(consumer::acknowledge);
197+
consumer.commitSync();
198+
199+
afterMultipleAcknowledgements = pollAndCommit(consumer);
200+
}
201+
202+
// Each phase consumes far fewer records than the backlog of either partition, hence both partitions have
203+
// records throughout and each should get a meaningful share of the records of every phase.
204+
String recordsByPhase = "records by partition before the epoch parity changed: " + afterSingleAcknowledgement
205+
+ ", after: " + afterMultipleAcknowledgements;
206+
for (Map<Integer, Integer> phase : List.of(afterSingleAcknowledgement, afterMultipleAcknowledgements)) {
207+
int phaseRecords = phase.values().stream().mapToInt(Integer::intValue).sum();
208+
for (int p = 0; p < partitions; p++) {
209+
assertTrue(phase.getOrDefault(p, 0) * partitions * 2 >= phaseRecords,
210+
"Partition " + p + " was starved, " + recordsByPhase);
211+
}
212+
}
213+
}
214+
215+
private void verifyFirstPositionRotatesWhenAllPartitionsReturnRecords(String topic, int partitions, String acknowledgementMode) {
216+
String groupId = topic + "-group";
217+
// Records per partition a single fetch can return, capped by the fetch bytes of the partition.
218+
int recordsPerPartitionPerFetch = 100;
219+
createTopic(topic, partitions, 1);
220+
// Enough records per partition to outlast the polls even if a partition were read first on every poll.
221+
produceRecords(topic, partitions, POLLS_PER_PHASE * recordsPerPartitionPerFetch, RECORD_VALUE_SIZE);
222+
alterShareAutoOffsetReset(groupId, "earliest");
223+
224+
Map<Integer, Integer> recordsByPartition;
225+
try (ShareConsumer<byte[], byte[]> consumer = createShareConsumer(groupId, Map.of(
226+
ConsumerConfig.FETCH_MAX_BYTES_CONFIG, String.valueOf(partitions * recordsPerPartitionPerFetch * RECORD_SIZE),
227+
// Every partition but the last returns the records its fetch bytes allow, the last one gets half of it.
228+
ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(recordsPerPartitionPerFetch * partitions - recordsPerPartitionPerFetch / 2),
229+
ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG, "record_limit",
230+
ConsumerConfig.SHARE_ACKNOWLEDGEMENT_MODE_CONFIG, acknowledgementMode))) {
231+
consumer.subscribe(Set.of(topic));
232+
recordsByPartition = acknowledgementMode.equals("explicit") ? pollAndCommit(consumer) : pollImplicit(consumer);
233+
}
234+
235+
// With the first position rotating, every partition takes every position in turn and the partitions
236+
// consume the same number of records. Without rotation the last partition is stuck with half the share.
237+
int totalRecords = recordsByPartition.values().stream().mapToInt(Integer::intValue).sum();
238+
for (int p = 0; p < partitions; p++) {
239+
assertTrue(recordsByPartition.getOrDefault(p, 0) * partitions * 4 >= totalRecords * 3,
240+
"Partition " + p + " did not take the first position, records by partition: " + recordsByPartition);
241+
}
242+
}
243+
244+
private void produceRecords(String topic, int partitions) {
245+
produceRecords(topic, partitions, RECORDS_PER_PARTITION, "value".getBytes().length);
246+
}
247+
248+
/**
249+
* Produces the given number of records of the given value size to every partition, each record in its own
250+
* batch so the size of the records on the log is known.
251+
*/
252+
private void produceRecords(String topic, int partitions, int recordsPerPartition, int valueSize) {
253+
try (Producer<byte[], byte[]> producer = createProducer(Map.of(ProducerConfig.BATCH_SIZE_CONFIG, 0))) {
254+
for (int i = 0; i < recordsPerPartition; i++) {
255+
for (int p = 0; p < partitions; p++) {
256+
producer.send(new ProducerRecord<>(topic, p, null, null, new byte[valueSize]));
257+
}
258+
}
259+
producer.flush();
260+
}
261+
}
262+
263+
/**
264+
* Polls until {@link #POLLS_PER_PHASE} polls have returned records, and commits the acknowledgements of each poll
265+
* in one request.
266+
*/
267+
private Map<Integer, Integer> pollAndCommit(ShareConsumer<byte[], byte[]> consumer) {
268+
Map<Integer, Integer> recordsByPartition = new TreeMap<>();
269+
for (int poll = 0; poll < POLLS_PER_PHASE; poll++) {
270+
for (ConsumerRecord<byte[], byte[]> record : pollRecords(consumer)) {
271+
recordsByPartition.merge(record.partition(), 1, Integer::sum);
272+
consumer.acknowledge(record);
273+
}
274+
consumer.commitSync();
275+
}
276+
return recordsByPartition;
277+
}
278+
279+
/**
280+
* Polls until {@link #POLLS_PER_PHASE} polls have returned records, with implicit acknowledgement the records
281+
* of a poll are acknowledged on the next poll.
282+
*/
283+
private Map<Integer, Integer> pollImplicit(ShareConsumer<byte[], byte[]> consumer) {
284+
Map<Integer, Integer> recordsByPartition = new TreeMap<>();
285+
for (int poll = 0; poll < POLLS_PER_PHASE; poll++) {
286+
pollRecords(consumer).forEach(record -> recordsByPartition.merge(record.partition(), 1, Integer::sum));
287+
}
288+
return recordsByPartition;
289+
}
290+
291+
/**
292+
* Polls until records are returned, the test timeout fails the test if no records are delivered.
293+
*/
294+
private List<ConsumerRecord<byte[], byte[]>> pollRecords(ShareConsumer<byte[], byte[]> consumer) {
295+
List<ConsumerRecord<byte[], byte[]>> records = new ArrayList<>();
296+
while (records.isEmpty()) {
297+
consumer.poll(Duration.ofMillis(200)).forEach(records::add);
298+
}
299+
return records;
300+
}
113301
}
Collapse file

‎core/src/main/java/kafka/server/share/ShareFetchUtils.java‎

Copy file name to clipboardExpand all lines: core/src/main/java/kafka/server/share/ShareFetchUtils.java
+3-2Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@
3333
import org.slf4j.Logger;
3434
import org.slf4j.LoggerFactory;
3535

36-
import java.util.HashMap;
3736
import java.util.Iterator;
3837
import java.util.LinkedHashMap;
3938
import java.util.List;
@@ -57,7 +56,9 @@ static Map<TopicIdPartition, ShareFetchResponseData.PartitionData> processFetchR
5756
PartitionMetadataProvider metadataProvider,
5857
BiConsumer<SharePartitionKey, Throwable> exceptionHandler
5958
) {
60-
Map<TopicIdPartition, ShareFetchResponseData.PartitionData> response = new HashMap<>();
59+
// Preserve the fetch order of the partitions in the response, the share session uses it to re-order
60+
// the partitions for the subsequent fetch.
61+
Map<TopicIdPartition, ShareFetchResponseData.PartitionData> response = new LinkedHashMap<>();
6162

6263
// Acquired records count for the share fetch request.
6364
int acquiredRecordsCount = 0;
Collapse file

‎core/src/main/java/kafka/server/share/SharePartitionManager.java‎

Copy file name to clipboardExpand all lines: core/src/main/java/kafka/server/share/SharePartitionManager.java
+1-9Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@
4747
import org.apache.kafka.server.share.fetch.DelayedShareFetchGroupKey;
4848
import org.apache.kafka.server.share.fetch.DelayedShareFetchKey;
4949
import org.apache.kafka.server.share.fetch.DelayedShareFetchPartitionKey;
50-
import org.apache.kafka.server.share.fetch.PartitionRotateStrategy;
51-
import org.apache.kafka.server.share.fetch.PartitionRotateStrategy.PartitionRotateMetadata;
5250
import org.apache.kafka.server.share.fetch.ShareFetch;
5351
import org.apache.kafka.server.share.metrics.ShareGroupMetrics;
5452
import org.apache.kafka.server.share.persister.Persister;
@@ -309,7 +307,6 @@ private SharePartitionManager(
309307
* @param memberId The member id, generated by the group-coordinator, this is used to identify the client.
310308
* @param shareAcquireMode The share acquire mode from the share fetch request.
311309
* @param fetchParams The fetch parameters from the share fetch request.
312-
* @param sessionEpoch The session epoch for the member.
313310
* @param maxFetchRecords The maximum number of records to fetch.
314311
* @param batchSize The number of records per acquired records batch.
315312
* @param topicIdPartitions The topic partitions to fetch for.
@@ -321,20 +318,15 @@ public CompletableFuture<Map<TopicIdPartition, PartitionData>> fetchMessages(
321318
String memberId,
322319
FetchParams fetchParams,
323320
byte shareAcquireMode,
324-
int sessionEpoch,
325321
int maxFetchRecords,
326322
int batchSize,
327323
List<TopicIdPartition> topicIdPartitions
328324
) {
329325
log.trace("Fetch request for topicIdPartitions: {} with groupId: {} fetch params: {}",
330326
topicIdPartitions, groupId, fetchParams);
331327

332-
List<TopicIdPartition> rotatedTopicIdPartitions = PartitionRotateStrategy
333-
.type(PartitionRotateStrategy.StrategyType.ROUND_ROBIN)
334-
.rotate(topicIdPartitions, new PartitionRotateMetadata(sessionEpoch));
335-
336328
CompletableFuture<Map<TopicIdPartition, PartitionData>> future = new CompletableFuture<>();
337-
processShareFetch(new ShareFetch(fetchParams, groupId, memberId, future, rotatedTopicIdPartitions, shareAcquireMode, batchSize, maxFetchRecords, brokerTopicStats));
329+
processShareFetch(new ShareFetch(fetchParams, groupId, memberId, future, topicIdPartitions, shareAcquireMode, batchSize, maxFetchRecords, brokerTopicStats));
338330

339331
return future;
340332
}
Collapse file

‎core/src/main/scala/kafka/server/KafkaApis.scala‎

Copy file name to clipboardExpand all lines: core/src/main/scala/kafka/server/KafkaApis.scala
+5-5Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3420,7 +3420,7 @@ class KafkaApis(val requestChannel: RequestChannel,
34203420
if (shareFetchRequest.version() >= 2 && shareFetchRequest.data.isRenewAck)
34213421
CompletableFuture.completedFuture(mutable.Map.empty[TopicIdPartition, ShareFetchResponseData.PartitionData])
34223422
else
3423-
handleFetchFromShareFetchRequest(request, shareSessionEpoch, erroneousAndValidPartitionData, sharePartitionManager, authorizedTopics)
3423+
handleFetchFromShareFetchRequest(request, erroneousAndValidPartitionData, sharePartitionManager, authorizedTopics)
34243424

34253425
def combineShareFetchAndShareAcknowledgeResponses(fetchResult: CompletableFuture[Map[TopicIdPartition, ShareFetchResponseData.PartitionData]],
34263426
acknowledgeResult: CompletableFuture[Map[TopicIdPartition, ShareAcknowledgeResponseData.PartitionData]],
@@ -3516,7 +3516,6 @@ class KafkaApis(val requestChannel: RequestChannel,
35163516

35173517
// Visible for Testing
35183518
def handleFetchFromShareFetchRequest(request: Request,
3519-
shareSessionEpoch: Int,
35203519
erroneousAndValidPartitionData: ErroneousAndValidPartitionData,
35213520
sharePartitionManagerInstance: SharePartitionManager,
35223521
authorizedTopics: Set[String]
@@ -3577,19 +3576,20 @@ class KafkaApis(val requestChannel: RequestChannel,
35773576
shareFetchRequest.data.memberId,
35783577
params,
35793578
shareFetchRequest.data.shareAcquireMode,
3580-
shareSessionEpoch,
35813579
shareFetchRequest.data.maxRecords,
35823580
shareFetchRequest.data.batchSize,
35833581
interestedTopicPartitions
35843582
).thenApply{ result =>
3585-
val combinedResult = mutable.Map.empty[TopicIdPartition, ShareFetchResponseData.PartitionData]
3583+
// Preserve the fetch order of the partitions, the share session uses it to re-order the partitions
3584+
// for the subsequent fetch.
3585+
val combinedResult = mutable.LinkedHashMap.empty[TopicIdPartition, ShareFetchResponseData.PartitionData]
35863586
result.asScala.foreach { case (tp, data) =>
35873587
combinedResult += (tp -> data)
35883588
}
35893589
erroneous.foreach { case (tp, data) =>
35903590
combinedResult += (tp -> data)
35913591
}
3592-
combinedResult.toMap
3592+
combinedResult
35933593
}
35943594
}
35953595
}

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.