dajac commented on code in PR #23733: URL: https://github.com/apache/kafka/pull/23733#discussion_r4268711005
########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/KeepStickyExtraPartitions.java: ########## @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntList; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; + +import java.util.Arrays; + +/** + * The first step deciding the {@link Quotas}: every member owning more than the minimum quota of a + * topic keeps one of its extra partitions, so that it only gives up what it owns beyond its quota. + * When more owners qualify than the topic has extra partitions, the ones with the smallest + * assignments keep them, the assignment sizes counting the extra partitions kept for the previous + * topics, then the members in member order. + */ +final class KeepStickyExtraPartitions { + /** + * The members and topics of the group. + */ + private final IndexedGroup group; + + /** + * The current assignment, which tells the owners of every topic. + */ + private final CurrentAssignment current; + + /** + * The quotas, which the step completes. + */ + private final Quotas quotas; + + /** + * @param group The members and topics of the group. + * @param current The current assignment. + * @param quotas The quotas, at the minimum quota. + */ + KeepStickyExtraPartitions(IndexedGroup group, CurrentAssignment current, Quotas quotas) { + this.group = group; + this.current = current; + this.quotas = quotas; + } + + /** + * Lets the owners of more than the minimum quota of every topic keep an extra partition. + */ + void run() { + var counts = new int[group.memberCount()]; + var owners = new IntList(16); + var candidates = new IntList(16); Review Comment: Renamed them to `ownedPartitionCounts`, `owners` and `ownersAboveMinQuota`, each with a one-line comment. I went with `ownersAboveMinQuota` rather than `currentMembersWithExtraPartitions` because these members own more than the minimum quota but don't have an extra partition yet at that point. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The + * extra partition goes to the cohort holding the smallest assignment, and among its members those + * with the smallest assignment are served round robin in member order. The member with the + * smallest assignment may already have an extra partition of the topic, and another member of the + * cohort then gets it: the balance step moves it if it has to. Without owners, a homogeneous group Review Comment: Yes, the fresh assignment. Reworded as suggested. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The Review Comment: No, it isn't guaranteed. Reworded to: "When the subscriptions of the cohorts are subsets of each other, this leads to more balanced assignment sizes." ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/Quotas.java: ########## @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntList; + +/** + * The quotas of the members: for every topic, how many of its partitions each subscriber gets. + * + * <p>A topic with {@code P} partitions and {@code N} subscribers has a minimum quota of + * {@code P / N} partitions and {@code P % N} extra partitions, which go to as many distinct + * subscribers, one each. The quota of a subscriber is thus the minimum quota, or one more when it + * gets an extra partition, and the assignment size of a member is the sum of its quotas. + * + * <p>The quotas start at the minimum quota. The steps deciding the quotas give the extra + * partitions with {@link #giveExtraPartition} and move them with {@link #moveExtraPartition}, + * every extra partition going to a distinct subscriber of its topic. + */ +final class Quotas { + /** + * The empty list of members with an extra partition shared by all the topics without extra + * partitions. It never changes: {@link #giveExtraPartition} rejects such a topic, and + * {@link #moveExtraPartition} a giver without an extra partition of the topic. + */ + private static final IntList NONE = new IntList(0); + + /** + * The members and topics of the group. + */ + private final IndexedGroup group; + + /** + * Per topic, its minimum quota: the number of partitions that every subscriber gets. + */ + private final int[] minQuotas; + + /** + * Per topic, the number of subscribers getting one partition more than the minimum quota. + */ + private final int[] extraPartitions; + + /** + * Per cohort, the sum of the minimum quotas of its topics: the smallest assignment size of + * its members. + */ + private final int[] minAssignmentSizes; + + /** + * Per topic, the members getting one of its extra partitions. Review Comment: Right, only if `giveExtraPartition` is misused. Its Javadoc now states the precondition (the member must not already have an extra partition of the topic), and misuse stays undefined. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The + * extra partition goes to the cohort holding the smallest assignment, and among its members those + * with the smallest assignment are served round robin in member order. The member with the + * smallest assignment may already have an extra partition of the topic, and another member of the + * cohort then gets it: the balance step moves it if it has to. Without owners, a homogeneous group + * is served round robin. + * + * <p>On exit every topic has exactly its number of extra partitions, on distinct subscribers. + */ +final class AssignRemainingExtraPartitions { + /** + * The state of a cohort while the extra partitions are handed out. + */ + private static final class CohortState { + /** + * The members of the cohort. + */ + final int[] members; + + /** + * The position in the members of the next member to serve, round robin. + */ + int cursor; + + /** + * The lowest number of extra partitions of the members. + */ + int lowest; + + /** + * How many members have the lowest number of extra partitions. + */ + int atLowest; + + /** + * How many members have an extra partition of the topic being handed out. + */ + int holders; + + CohortState(int[] members) { + this.members = members; + } + } + + /** + * The members and topics of the group. + */ + private final IndexedGroup group; + + /** + * The quotas, which the step completes. + */ + private final Quotas quotas; + + /** + * The cohorts of the topic being handed out which can still take an extra partition of it, by + * increasing smallest assignment size among their members, whether that member has an extra + * partition of the topic or not, then in cohort order, see {@link #sizeAndCohort(int)}. + */ + private LongHeap candidates; Review Comment: How about `receivingCohorts`? I renamed it to that for now. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The + * extra partition goes to the cohort holding the smallest assignment, and among its members those + * with the smallest assignment are served round robin in member order. The member with the + * smallest assignment may already have an extra partition of the topic, and another member of the + * cohort then gets it: the balance step moves it if it has to. Without owners, a homogeneous group + * is served round robin. + * + * <p>On exit every topic has exactly its number of extra partitions, on distinct subscribers. + */ +final class AssignRemainingExtraPartitions { + /** + * The state of a cohort while the extra partitions are handed out. + */ + private static final class CohortState { + /** + * The members of the cohort. + */ + final int[] members; + + /** + * The position in the members of the next member to serve, round robin. + */ + int cursor; + + /** + * The lowest number of extra partitions of the members. + */ + int lowest; + + /** + * How many members have the lowest number of extra partitions. + */ + int atLowest; + + /** + * How many members have an extra partition of the topic being handed out. + */ + int holders; Review Comment: Renamed to `lowestExtraPartitions`, `membersWithLowestExtraPartitions` and `membersWithExtraPartitionOfTopic`, and `hasExtra` to `hasExtraPartitionOfTopic`. I added "OfTopic" to the last two because they are about the topic being assigned, not all the topics. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The + * extra partition goes to the cohort holding the smallest assignment, and among its members those + * with the smallest assignment are served round robin in member order. The member with the + * smallest assignment may already have an extra partition of the topic, and another member of the + * cohort then gets it: the balance step moves it if it has to. Without owners, a homogeneous group + * is served round robin. + * + * <p>On exit every topic has exactly its number of extra partitions, on distinct subscribers. + */ +final class AssignRemainingExtraPartitions { + /** + * The state of a cohort while the extra partitions are handed out. + */ + private static final class CohortState { + /** + * The members of the cohort. + */ + final int[] members; + + /** + * The position in the members of the next member to serve, round robin. + */ + int cursor; + + /** + * The lowest number of extra partitions of the members. + */ + int lowest; + + /** + * How many members have the lowest number of extra partitions. + */ + int atLowest; + + /** + * How many members have an extra partition of the topic being handed out. + */ + int holders; + + CohortState(int[] members) { + this.members = members; + } + } + + /** + * The members and topics of the group. + */ + private final IndexedGroup group; + + /** + * The quotas, which the step completes. + */ + private final Quotas quotas; + + /** + * The cohorts of the topic being handed out which can still take an extra partition of it, by + * increasing smallest assignment size among their members, whether that member has an extra + * partition of the topic or not, then in cohort order, see {@link #sizeAndCohort(int)}. + */ + private LongHeap candidates; + + /** + * Per cohort, its state. + */ + private CohortState[] cohortStates; + + /** + * Per member, whether it has an extra partition of the topic being handed out. + */ + private boolean[] hasExtra; + + /** + * @param group The members and topics of the group. + * @param quotas The quotas, as the first step left them, which the step completes. + */ + AssignRemainingExtraPartitions(IndexedGroup group, Quotas quotas) { + this.group = group; + this.quotas = quotas; + } + + /** + * @return The key of the cohort in the heap of candidates: the pair of the smallest assignment + * size among its members and the cohort, so that the heap orders the cohorts by that + * assignment size, then cohort order. That assignment size does not change while the + * cohort is a candidate, since only the members of a polled cohort get an extra + * partition. + */ + private long sizeAndCohort(int cohort) { + return IntPair.pack(quotas.minAssignmentSize(cohort) + cohortStates[cohort].lowest, cohort); + } + + /** + * Hands out the extra partitions that no owner kept. When the owners kept them all, as in a + * stable group, returns at once without allocating anything. + */ + void run() { + if (!hasExtraPartitionsToHandOut()) { + return; + } + cohortStates = new CohortState[group.cohortCount()]; + for (int cohort = 0; cohort < cohortStates.length; cohort++) { + cohortStates[cohort] = new CohortState(group.membersOf(cohort)); + findLowest(cohortStates[cohort]); + } + hasExtra = new boolean[group.memberCount()]; + candidates = new LongHeap(16); + for (int topic : topicsToHandOut()) { + handOutTopic(topic); + } + } + + /** + * @return {@code true} if a topic has extra partitions that no owner kept. + */ + private boolean hasExtraPartitionsToHandOut() { + for (int topic = 0; topic < group.topicCount(); topic++) { + if (quotas.membersWithExtraPartition(topic).size() < quotas.extraPartitions(topic)) { + return true; + } + } + return false; + } + + /** + * Hands out the extra partitions of the topic that no owner kept, one at a time, each to the + * next member of the cohort holding the smallest assignment among those still having a member + * without one. + */ + private void handOutTopic(int topic) { + // The members keeping an extra partition of the topic, which grows as the topic is handed + // out. + var members = quotas.membersWithExtraPartition(topic); + for (int i = 0; i < members.size(); i++) { + hasExtra[members.get(i)] = true; + cohortStates[group.cohortOf(members.get(i))].holders++; + } + // The cohorts of the topic with a member still without an extra partition of it, the only + // ones that can take one. + candidates.clear(); + for (int cohort : group.cohortsOf(topic)) { + var state = cohortStates[cohort]; + if (state.holders < state.members.length) { + candidates.add(sizeAndCohort(cohort)); + } + } + // The extra partitions that no owner kept, counted once since the members grow while they + // are handed out. There is at least one: topicsToHandOut only lists the topics with some. + for (int toHandOut = quotas.extraPartitions(topic) - members.size(); toHandOut > 0; toHandOut--) { + int cohort = IntPair.low(candidates.poll()); + var state = cohortStates[cohort]; + int member = nextMember(state); + int count = quotas.extraPartitionCount(member); + quotas.giveExtraPartition(member, topic); + hasExtra[member] = true; + // The last member of the cohort at the lowest number of extra partitions moves up. + if (count == state.lowest && --state.atLowest == 0) { + findLowest(state); + } + if (++state.holders < state.members.length) { + candidates.add(sizeAndCohort(cohort)); + } + } + // Resets the scratch state for the next topic, including the members just served. + for (int i = 0; i < members.size(); i++) { + hasExtra[members.get(i)] = false; + cohortStates[group.cohortOf(members.get(i))].holders = 0; + } + } + + /** + * @return The topics with extra partitions nobody kept, by increasing number of subscribers, + * then topic order. + */ + private int[] topicsToHandOut() { + // Pairs of the number of subscribers and the topic, which sort by subscribers, then topic. + var keys = new long[group.topicCount()]; + int count = 0; + for (int topic = 0; topic < group.topicCount(); topic++) { + if (quotas.extraPartitions(topic) > quotas.membersWithExtraPartition(topic).size()) { + keys[count++] = IntPair.pack(group.subscriberCount(topic), topic); + } + } + Arrays.sort(keys, 0, count); + var topics = new int[count]; + for (int i = 0; i < count; i++) { + topics[i] = IntPair.low(keys[i]); + } + return topics; + } + + /** + * Finds the lowest number of extra partitions of the members of the cohort, and how many of + * them have it. + */ + private void findLowest(CohortState state) { + int min = Integer.MAX_VALUE; + int count = 0; + for (int member : state.members) { + int extras = quotas.extraPartitionCount(member); + if (extras < min) { + min = extras; + count = 1; + } else if (extras == min) { + count++; + } + } + state.lowest = min; + state.atLowest = count; + } + + /** + * @return The next member of the cohort, in round robin order from the cursor, having the + * lowest number of extra partitions among its members and no extra partition of the + * topic. If every member having the lowest number has one, the first member without + * one having the fewest extra partitions. + */ + private int nextMember(CohortState state) { + var members = state.members; + for (int step = 0; step < members.length; step++) { + int index = (state.cursor + step) % members.length; + int member = members[index]; + if (quotas.extraPartitionCount(member) == state.lowest && !hasExtra[member]) { + state.cursor = (index + 1) % members.length; + return member; + } + } + // Every member at the lowest number has an extra partition of the topic. + int best = -1; + for (int member : members) { + if (!hasExtra[member] && (best < 0 || quotas.extraPartitionCount(member) < quotas.extraPartitionCount(best))) { + best = member; + } + } + return best; Review Comment: Agreed, this case deserves a look. When every member at the lowest count of the cohort already has an extra partition of the topic, each extra partition scans the cohort, and the cohort's key in the heap doesn't change, so it keeps receiving them. The results stay valid since the balance step evens out the assignment sizes afterwards, but it costs more and may move more partitions. We haven't measured how often it happens; I'll look into it in a follow-up. ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/KeepStickyExtraPartitions.java: ########## @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntList; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; + +import java.util.Arrays; + +/** + * The first step deciding the {@link Quotas}: every member owning more than the minimum quota of a + * topic keeps one of its extra partitions, so that it only gives up what it owns beyond its quota. + * When more owners qualify than the topic has extra partitions, the ones with the smallest + * assignments keep them, the assignment sizes counting the extra partitions kept for the previous + * topics, then the members in member order. + */ +final class KeepStickyExtraPartitions { Review Comment: That's what we tried to do with the names: the steps are verb phrases (`KeepStickyExtraPartitions`, `AssignRemainingExtraPartitions`, `BalanceExtraPartitions`) and the data classes are nouns (`IndexedGroup`, `CurrentAssignment`, `Quotas`). Does that work for you, or would you still prefer a suffix or a subpackage? ########## group-coordinator/src/main/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitions.java: ########## @@ -0,0 +1,265 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.coordinator.group.assignor.uniform2.util.IntPair; +import org.apache.kafka.coordinator.group.assignor.uniform2.util.LongHeap; + +import java.util.Arrays; + +/** + * The second step deciding the {@link Quotas}: assigns the extra partitions that no owner kept, + * one at a time, to subscribers not having one of the topic yet, among the ones with the smallest + * assignments. + * + * <p>The topics with the fewest subscribers go first, so that they get the smallest of their few + * candidates: when the subscriptions are nested, this alone balances the assignment sizes. The + * extra partition goes to the cohort holding the smallest assignment, and among its members those + * with the smallest assignment are served round robin in member order. The member with the + * smallest assignment may already have an extra partition of the topic, and another member of the + * cohort then gets it: the balance step moves it if it has to. Without owners, a homogeneous group + * is served round robin. + * + * <p>On exit every topic has exactly its number of extra partitions, on distinct subscribers. + */ +final class AssignRemainingExtraPartitions { + /** + * The state of a cohort while the extra partitions are handed out. + */ + private static final class CohortState { + /** + * The members of the cohort. + */ + final int[] members; + + /** + * The position in the members of the next member to serve, round robin. + */ + int cursor; + + /** + * The lowest number of extra partitions of the members. + */ + int lowest; + + /** + * How many members have the lowest number of extra partitions. + */ + int atLowest; + + /** + * How many members have an extra partition of the topic being handed out. + */ + int holders; + + CohortState(int[] members) { + this.members = members; + } + } + + /** + * The members and topics of the group. + */ + private final IndexedGroup group; + + /** + * The quotas, which the step completes. + */ + private final Quotas quotas; + + /** + * The cohorts of the topic being handed out which can still take an extra partition of it, by + * increasing smallest assignment size among their members, whether that member has an extra + * partition of the topic or not, then in cohort order, see {@link #sizeAndCohort(int)}. + */ + private LongHeap candidates; + + /** + * Per cohort, its state. + */ + private CohortState[] cohortStates; + + /** + * Per member, whether it has an extra partition of the topic being handed out. + */ + private boolean[] hasExtra; + + /** + * @param group The members and topics of the group. + * @param quotas The quotas, as the first step left them, which the step completes. + */ + AssignRemainingExtraPartitions(IndexedGroup group, Quotas quotas) { + this.group = group; + this.quotas = quotas; + } + + /** + * @return The key of the cohort in the heap of candidates: the pair of the smallest assignment + * size among its members and the cohort, so that the heap orders the cohorts by that + * assignment size, then cohort order. That assignment size does not change while the + * cohort is a candidate, since only the members of a polled cohort get an extra + * partition. + */ + private long sizeAndCohort(int cohort) { + return IntPair.pack(quotas.minAssignmentSize(cohort) + cohortStates[cohort].lowest, cohort); + } + + /** + * Hands out the extra partitions that no owner kept. When the owners kept them all, as in a + * stable group, returns at once without allocating anything. + */ + void run() { + if (!hasExtraPartitionsToHandOut()) { + return; + } + cohortStates = new CohortState[group.cohortCount()]; + for (int cohort = 0; cohort < cohortStates.length; cohort++) { + cohortStates[cohort] = new CohortState(group.membersOf(cohort)); + findLowest(cohortStates[cohort]); + } + hasExtra = new boolean[group.memberCount()]; + candidates = new LongHeap(16); + for (int topic : topicsToHandOut()) { + handOutTopic(topic); + } + } + + /** + * @return {@code true} if a topic has extra partitions that no owner kept. + */ + private boolean hasExtraPartitionsToHandOut() { + for (int topic = 0; topic < group.topicCount(); topic++) { + if (quotas.membersWithExtraPartition(topic).size() < quotas.extraPartitions(topic)) { + return true; + } + } + return false; + } + + /** + * Hands out the extra partitions of the topic that no owner kept, one at a time, each to the + * next member of the cohort holding the smallest assignment among those still having a member + * without one. + */ + private void handOutTopic(int topic) { + // The members keeping an extra partition of the topic, which grows as the topic is handed + // out. + var members = quotas.membersWithExtraPartition(topic); + for (int i = 0; i < members.size(); i++) { + hasExtra[members.get(i)] = true; + cohortStates[group.cohortOf(members.get(i))].holders++; + } + // The cohorts of the topic with a member still without an extra partition of it, the only + // ones that can take one. + candidates.clear(); + for (int cohort : group.cohortsOf(topic)) { + var state = cohortStates[cohort]; + if (state.holders < state.members.length) { + candidates.add(sizeAndCohort(cohort)); + } + } + // The extra partitions that no owner kept, counted once since the members grow while they + // are handed out. There is at least one: topicsToHandOut only lists the topics with some. Review Comment: It was meant to say why the bound is read before the loop: the loop adds to the members with an extra partition of the topic. It's now a named local, `remainingExtraPartitions`, with a plain comment saying that. ########## group-coordinator/src/test/java/org/apache/kafka/coordinator/group/assignor/uniform2/AssignRemainingExtraPartitionsTest.java: ########## @@ -0,0 +1,241 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.coordinator.group.assignor.uniform2; + +import org.apache.kafka.common.Uuid; + +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests of {@link AssignRemainingExtraPartitions}. The topic ids sort as T1 < T2 < T3 < + * T4, and the cohorts are numbered in the order of their first member. + */ +public class AssignRemainingExtraPartitionsTest { + private static final Uuid T1 = new Uuid(1L, 1L); + private static final Uuid T2 = new Uuid(2L, 1L); + private static final Uuid T3 = new Uuid(3L, 1L); + private static final Uuid T4 = new Uuid(4L, 1L); + + /** + * A subscribes to T1 and T2, B and D to T1 and T3, and C to T2 and T4. T1, 4 partitions over + * A, B and D, has 1 extra partition, and T2, 3 partitions over A and C, has 1 too; T3 and T4 + * have none. The minimum quotas give assignment sizes of 2 to A, B and D, and 3 to C. T2 has + * the fewest subscribers and goes first: its extra partition goes to A, the smaller of A and + * C. Then the one of T1 goes to B, since A now has 3. The assignment sizes are within one of + * each other where the subscriptions allow it. Handing out T1 first would have given both + * extra partitions to A, the first cohort on ties: 4 partitions for A and 2 for B, which + * subscribes to T1. + */ + @Test + public void testTopicsWithTheFewestSubscribersGoFirst() { + var spec = new GroupSpecFixture() + .withMember("A", Set.of(T1, T2)) + .withMember("B", Set.of(T1, T3)) + .withMember("C", Set.of(T2, T4)) + .withMember("D", Set.of(T1, T3)) + .build(); + var describer = new TopicsFixture() + .withTopic(T1, 4) + .withTopic(T2, 3) + .withTopic(T3, 2) + .withTopic(T4, 2) + .build(); + var fixture = new QuotasFixture(spec, describer); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("B"), T2, List.of("A")), fixture.membersWithExtraPartition()); + assertEquals(List.of(3, 3, 3, 2), fixture.assignmentSizes()); + } + + /** + * A subscribes to T1 and T2, B to T1 and T3. T1, 3 partitions, has 1 extra partition. T2 + * gives A 2 partitions and T3 gives B 1, so B has the smaller assignment and gets it. + */ + @Test + public void testExtraPartitionGoesToTheCohortWithTheSmallestAssignment() { + var fixture = twoCohortGroup(2, 1); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("B")), fixture.membersWithExtraPartition()); + assertEquals(List.of(3, 3), fixture.assignmentSizes()); + } + + /** + * The same group, with 1 partition for T2 and T3: A and B have the same assignment size, and + * the extra partition of T1 goes to the first cohort, A's. + */ + @Test + public void testTiesGoToTheFirstCohort() { + var fixture = twoCohortGroup(1, 1); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("A")), fixture.membersWithExtraPartition()); + assertEquals(List.of(3, 2), fixture.assignmentSizes()); + } + + /** + * A, B and C subscribe to T1, T2 and T3, of 4 partitions each: 1 extra partition each. Each + * goes to the next member having no extra partition yet, and every member ends with one. + */ + @Test + public void testMembersOfACohortAreServedInTurn() { + var spec = new GroupSpecFixture() + .withMember("A", Set.of(T1, T2, T3)) + .withMember("B", Set.of(T1, T2, T3)) + .withMember("C", Set.of(T1, T2, T3)) + .build(); + var describer = new TopicsFixture() + .withTopic(T1, 4) + .withTopic(T2, 4) + .withTopic(T3, 4) + .build(); + var fixture = new QuotasFixture(spec, describer); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("A"), T2, List.of("B"), T3, List.of("C")), fixture.membersWithExtraPartition()); + assertEquals(List.of(4, 4, 4), fixture.assignmentSizes()); + } + + /** + * A, B and C subscribe to T1, of 4 partitions, and T2, of 5: 1 extra partition of T1 and 2 + * of T2. A kept one of T2. The extra partition of T1 skips A, which has more extra partitions + * than B and C, and goes to B; the remaining one of T2 goes to C, the only member without + * any. + */ + @Test + public void testMembersWithTheFewestExtraPartitionsAreServedFirst() { + var spec = new GroupSpecFixture() + .withMember("A", Set.of(T1, T2)) + .withMember("B", Set.of(T1, T2)) + .withMember("C", Set.of(T1, T2)) + .build(); + var describer = new TopicsFixture() + .withTopic(T1, 4) + .withTopic(T2, 5) + .build(); + var fixture = new QuotasFixture(spec, describer); + fixture.addExtras("A", T2); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("B"), T2, List.of("A", "C")), fixture.membersWithExtraPartition()); + assertEquals(List.of(3, 3, 3), fixture.assignmentSizes()); + } + + /** + * A, B and C subscribe to T1, T2 and T3, of 5 partitions each: 2 extra partitions each. A + * kept one of T1, and B and C both of T2 and T3. The last extra partition of T1 cannot go to + * A, the member with the fewest extra partitions, which has one of T1 already: it goes to the + * member without one having the fewest extra partitions, B before C in member order. The + * balance step evens the assignment sizes out later. + */ + @Test + public void testAMemberWithMoreExtraPartitionsGetsOneWhenTheOthersHaveOneOfTheTopic() { + var spec = new GroupSpecFixture() + .withMember("A", Set.of(T1, T2, T3)) + .withMember("B", Set.of(T1, T2, T3)) + .withMember("C", Set.of(T1, T2, T3)) + .build(); + var describer = new TopicsFixture() + .withTopic(T1, 5) + .withTopic(T2, 5) + .withTopic(T3, 5) + .build(); + var fixture = new QuotasFixture(spec, describer); + fixture.addExtras("A", T1); + fixture.addExtras("B", T2, T3); + fixture.addExtras("C", T2, T3); + + new AssignRemainingExtraPartitions(fixture.group, fixture.quotas).run(); + + assertEquals(Map.of(T1, List.of("A", "B"), T2, List.of("B", "C"), T3, List.of("B", "C")), fixture.membersWithExtraPartition()); + assertEquals(List.of(4, 6, 5), fixture.assignmentSizes()); + } + + /** + * A subscribes to T1 only, B and C to T1 and T2. T1, 5 partitions, has 2 extra partitions, + * and A kept one. A has the smallest assignment, but its cohort has no member left without an + * extra partition of T1, and the other one goes to B. + */ + @Test + public void testACohortWhoseMembersAllHaveAnExtraPartitionGetsNoMore() { Review Comment: Added `testACohortThatFillsUpGetsNoMore`: A and B get the first two extra partitions of T1, their cohort is then full, and the third goes to C. -- 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]
