dajac commented on code in PR #23688:
URL: https://github.com/apache/kafka/pull/23688#discussion_r4585079833
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -1387,6 +1411,7 @@ private void convertToClassicGroup(
// Directly update the states instead of replaying the records because
// the classicGroup reference is needed for triggering the rebalance.
+ cancelTargetAssignmentUpdate(consumerGroup.groupId());
Review Comment:
nit: The comment above is about updating `groups` directly, not about the
cancellation. Could we give the cancellation its own comment?
```suggestion
// The consumer group no longer exists after the conversion, so we
cancel any
// in-flight assignor run.
cancelTargetAssignmentUpdate(consumerGroup.groupId());
// Directly update the states instead of replaying the records
because
// the classicGroup reference is needed for triggering the rebalance.
```
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4346,6 +4379,34 @@ static boolean canComputeNextTargetAssignment(
return currentTimeMs >= assignmentTimestampMs + assignmentIntervalMs;
}
+ /**
+ * Cancels any stale offloaded target assignment updates for a group.
+ * Must be called whenever the group epoch is bumped.
+ *
+ * @param groupId The group id.
+ * @param newGroupEpoch The new group epoch.
+ */
+ private void maybeCancelStaleTargetAssignmentUpdate(String groupId, int
newGroupEpoch) {
+ Integer assignmentEpoch = inflightOffloadedAssignorEpochs.get(groupId);
+ if (assignmentEpoch != null && assignmentEpoch >= newGroupEpoch) {
+ // The group epoch was less than the epoch of the in-flight
assignor run. This means we
+ // failed to commit a previous bump and the assignor run is using
stale information.
+ // To ensure that we schedule another assignor run even if the
group epoch matches the
+ // epoch of the in-flight assignor run, we cancel the in-flight
run.
+ cancelTargetAssignmentUpdate(groupId);
+ }
+ }
+
+ /**
+ * Cancels any offloaded target assignment updates for a group.
+ *
+ * @param groupId The group id.
+ */
+ private void cancelTargetAssignmentUpdate(String groupId) {
+ executor.cancel(groupTargetAssignmentUpdateKey(groupId));
+ inflightOffloadedAssignorEpochs.remove(groupId);
Review Comment:
Should we log the cancellation? Today a cancelled run logs `Scheduled
computing...`, maybe `Computed...`, and then nothing, so the logs don't say
what happened to it.
```suggestion
executor.cancel(groupTargetAssignmentUpdateKey(groupId));
Integer assignmentEpoch =
inflightOffloadedAssignorEpochs.remove(groupId);
if (assignmentEpoch != null) {
log.info("[GroupId {}] Cancelled computing a new target
assignment for epoch {}.",
groupId, assignmentEpoch);
}
```
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4370,57 +4431,115 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ String groupId = group.groupId();
+
+ String targetAssignmentUpdateKey =
groupTargetAssignmentUpdateKey(groupId);
+ if (executor.isScheduled(targetAssignmentUpdateKey)) {
Review Comment:
No test fails when this check is removed. It is needed when offloading is
disabled for the group while a run is in flight. Without it, the next heartbeat
computes the target assignment inline and the in-flight run writes its result
afterwards, possibly over a newer target assignment. No test fails either when
the group config is ignored below and only the broker config is used. Could we
add a test for it? The following one covers both.
<details>
<summary>Test</summary>
```java
@Test
public void
testConsumerGroupAsyncTargetAssignmentWithOffloadDisabledWhileInFlight() {
String groupId = "fooup";
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
MockPartitionAssignor assignor = new MockPartitionAssignor("range");
CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
.addTopic(fooTopicId, fooTopicName, 6)
.buildCoordinatorMetadataImage();
GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
0)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
.withMetadataImage(metadataImage)
.build();
// Member 1 joins the group. The assignor run for epoch 2 is
scheduled on the executor.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId1)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
memberId1, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
))
)));
// Assignor offloading is disabled for the group.
Properties groupConfig = new Properties();
groupConfig.put(GroupConfig.CONSUMER_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
false);
context.updateGroupConfig(groupId, groupConfig);
// Member 1 heartbeats while the run is in flight. The target
assignment is not
// computed in the heartbeat.
CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result2 = context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId1)
.setMemberEpoch(1));
assertResponseEquals(
new ConsumerGroupHeartbeatResponseData()
.setMemberId(memberId1)
.setMemberEpoch(1)
.setHeartbeatIntervalMs(5000),
result2.response()
);
assertEquals(List.of(), result2.records());
// The run completes and its target assignment is written.
assertEquals(
List.of(
new MockCoordinatorExecutor.ExecutorResult<>(
GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
new CoordinatorResult<>(List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId1, mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
)),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
2, context.time.milliseconds())
))
)
),
context.processTasks()
);
// Member 2 joins the group. The target assignment for epoch 3 is
computed in the heartbeat.
CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result3 = context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId2)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
assertResponseEquals(
new ConsumerGroupHeartbeatResponseData()
.setMemberId(memberId2)
.setMemberEpoch(3)
.setHeartbeatIntervalMs(5000)
.setAssignment(new
ConsumerGroupHeartbeatResponseData.Assignment()
.setTopicPartitions(List.of())),
result3.response()
);
ConsumerGroupMember expectedMember2 = new
ConsumerGroupMember.Builder(memberId2)
.setState(MemberState.STABLE)
.setMemberEpoch(3)
.setPreviousMemberEpoch(0)
.setClientId(DEFAULT_CLIENT_ID)
.setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
.setRebalanceTimeoutMs(5000)
.setSubscribedTopicNames(List.of(fooTopicName))
.setServerAssignorName("range")
.setAssignedPartitions(Map.of())
.build();
assertRecordsEquals(
List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId,
expectedMember2),
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 3,
computeGroupHash(Map.of(
fooTopicName, computeTopicHash(fooTopicName,
metadataImage)
))),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, Map.of()),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
3, context.time.milliseconds()),
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId,
expectedMember2)
),
result3.records()
);
assertFalse(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
}
```
</details>
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4346,6 +4379,34 @@ static boolean canComputeNextTargetAssignment(
return currentTimeMs >= assignmentTimestampMs + assignmentIntervalMs;
}
+ /**
+ * Cancels any stale offloaded target assignment updates for a group.
+ * Must be called whenever the group epoch is bumped.
+ *
+ * @param groupId The group id.
+ * @param newGroupEpoch The new group epoch.
+ */
+ private void maybeCancelStaleTargetAssignmentUpdate(String groupId, int
newGroupEpoch) {
+ Integer assignmentEpoch = inflightOffloadedAssignorEpochs.get(groupId);
+ if (assignmentEpoch != null && assignmentEpoch >= newGroupEpoch) {
+ // The group epoch was less than the epoch of the in-flight
assignor run. This means we
+ // failed to commit a previous bump and the assignor run is using
stale information.
+ // To ensure that we schedule another assignor run even if the
group epoch matches the
+ // epoch of the in-flight assignor run, we cancel the in-flight
run.
+ cancelTargetAssignmentUpdate(groupId);
+ }
+ }
+
+ /**
+ * Cancels any offloaded target assignment updates for a group.
+ *
+ * @param groupId The group id.
+ */
+ private void cancelTargetAssignmentUpdate(String groupId) {
+ executor.cancel(groupTargetAssignmentUpdateKey(groupId));
+ inflightOffloadedAssignorEpochs.remove(groupId);
+ }
+
/**
* Updates the target assignment according to the updated member and
subscription metadata.
Review Comment:
nit: With offloading, this method only schedules the assignor run and
returns the last target assignment. The new one is installed later by
`handleOffloadedConsumerTargetAssignmentResult`. Could we say so here and in
`@return`?
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4370,57 +4431,115 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ String groupId = group.groupId();
+
+ String targetAssignmentUpdateKey =
groupTargetAssignmentUpdateKey(groupId);
+ if (executor.isScheduled(targetAssignmentUpdateKey)) {
+ // There is already an async assignor run in progress. We must not
start another run,
+ // sync or async, until it has completed or been cancelled,
otherwise the older run's
+ // result could be installed after the newer run's result.
+ return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
+ }
+
boolean canComputeNextTargetAssignment =
canComputeNextTargetAssignment(
group.assignmentTimestamp(),
- consumerGroupAssignmentIntervalMs(group.groupId()),
+ consumerGroupAssignmentIntervalMs(groupId),
time.milliseconds()
);
if (!canComputeNextTargetAssignment) {
Review Comment:
All the new tests either set the assignment interval to 0 or stop after the
first run. Skipping this check when the assignor is offloaded passes all of
them. Should we add a variant of `testConsumerGroupAssignmentInterval` with
offloading enabled? Both are enabled by default.
<details>
<summary>Test</summary>
```java
@Test
public void
testConsumerGroupAsyncTargetAssignmentWithAssignmentInterval() {
String groupId = "fooup";
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
MockPartitionAssignor assignor = new MockPartitionAssignor("range");
CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
.addTopic(fooTopicId, fooTopicName, 6)
.buildCoordinatorMetadataImage();
GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
1000)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
.withMetadataImage(metadataImage)
.build();
// Member 1 joins the group. The group has no assignment yet so the
assignor is scheduled
// right away.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId1)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
// Member 2 joins the group while the assignor runs.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId2)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
// The assignor completes after 100 ms and the target assignment for
epoch 2 is written.
context.time.sleep(100);
long assignmentTimestamp = context.time.milliseconds();
assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
memberId1, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
))
)));
List<MockCoordinatorExecutor.ExecutorResult<CoordinatorRecord>>
tasks = context.processTasks();
assertEquals(1, tasks.size());
assertEquals(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
tasks.get(0).key());
assertUnorderedRecordsEquals(
List.of(
List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId1, mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
)),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, Map.of())
),
List.of(GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
2, assignmentTimestamp))
),
tasks.get(0).result().records()
);
// Member 1 heartbeats just before the assignment interval has
elapsed. It receives the
// assignment for epoch 2 and the next assignor run is not scheduled.
context.time.sleep(999);
CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result = context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId1)
.setMemberEpoch(1));
assertResponseEquals(
new ConsumerGroupHeartbeatResponseData()
.setMemberId(memberId1)
.setMemberEpoch(2)
.setHeartbeatIntervalMs(5000)
.setAssignment(new
ConsumerGroupHeartbeatResponseData.Assignment()
.setTopicPartitions(List.of(
new
ConsumerGroupHeartbeatResponseData.TopicPartitions()
.setTopicId(fooTopicId)
.setPartitions(List.of(0, 1, 2, 3, 4, 5))
))),
result.response()
);
assertFalse(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
// Member 2 heartbeats once the assignment interval has elapsed. The
assignor is scheduled
// for epoch 3.
context.time.sleep(1);
result = context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId2)
.setMemberEpoch(1));
assertResponseEquals(
new ConsumerGroupHeartbeatResponseData()
.setMemberId(memberId2)
.setMemberEpoch(2)
.setHeartbeatIntervalMs(5000),
result.response()
);
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
// The assignor completes and the target assignment for epoch 3 is
written.
assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
memberId1, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2)
)),
memberId2, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 3, 4, 5)
))
)));
tasks = context.processTasks();
assertEquals(1, tasks.size());
assertEquals(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
tasks.get(0).key());
assertUnorderedRecordsEquals(
List.of(
List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId1, mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2)
)),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, mkAssignment(
mkTopicAssignment(fooTopicId, 3, 4, 5)
))
),
List.of(GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
3, context.time.milliseconds()))
),
tasks.get(0).result().records()
);
}
```
</details>
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4370,57 +4431,115 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ String groupId = group.groupId();
+
+ String targetAssignmentUpdateKey =
groupTargetAssignmentUpdateKey(groupId);
+ if (executor.isScheduled(targetAssignmentUpdateKey)) {
+ // There is already an async assignor run in progress. We must not
start another run,
+ // sync or async, until it has completed or been cancelled,
otherwise the older run's
+ // result could be installed after the newer run's result.
+ return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
+ }
+
boolean canComputeNextTargetAssignment =
canComputeNextTargetAssignment(
group.assignmentTimestamp(),
- consumerGroupAssignmentIntervalMs(group.groupId()),
+ consumerGroupAssignmentIntervalMs(groupId),
time.milliseconds()
);
if (!canComputeNextTargetAssignment) {
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ boolean offloadAssignor = consumerGroupAssignorOffloadEnable(groupId);
+
String preferredServerAssignor = group.computePreferredServerAssignor(
member,
updatedMember
).orElse(defaultConsumerGroupAssignor.name());
- try {
- UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember,
Assignment> updatedMembersAndTargetAssignment =
- new UpdatedMembersAndTargetAssignmentView<>(
- group.members(),
- group.staticMembers(),
- group.targetAssignment(),
- ConsumerGroupMember::instanceId
- );
-
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
+ ConsumerGroupPartitionAssignor assignor =
consumerGroupAssignors.get(preferredServerAssignor);
- long startTimeMs = time.milliseconds();
- GroupSpec groupSpec = new
GroupSpecBuilder.ConsumerGroupSpecBuilder()
- .withMembers(updatedMembersAndTargetAssignment.members())
- .withSubscriptionType(subscriptionType)
-
.withTargetAssignment(updatedMembersAndTargetAssignment.targetAssignment())
- .withMetadataImage(metadataImage)
-
.withResolvedRegularExpressions(group.resolvedRegularExpressions())
- .build();
+ UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember, Assignment>
updatedMembersAndTargetAssignment =
+ new UpdatedMembersAndTargetAssignmentView<>(
+ group.members(),
+ group.staticMembers(),
+ group.targetAssignment(),
+ ConsumerGroupMember::instanceId
+ );
+
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
- TargetAssignmentBuilder assignmentResultBuilder =
- new TargetAssignmentBuilder(groupEpoch,
consumerGroupAssignors.get(preferredServerAssignor))
- .withTime(time)
- .withMetadataImage(metadataImage)
- .withGroupSpec(groupSpec);
+ // Use the same metadata image throughout.
+ CoordinatorMetadataImage metadataImage = this.metadataImage;
+ long groupSpecStartTimeMs = time.milliseconds();
+ GroupSpec groupSpec = new GroupSpecBuilder.ConsumerGroupSpecBuilder()
+ .withMembers(updatedMembersAndTargetAssignment.members())
+ .withSubscriptionType(subscriptionType)
+
.withTargetAssignment(updatedMembersAndTargetAssignment.targetAssignment())
+ .withMetadataImage(metadataImage)
+ .withResolvedRegularExpressions(group.resolvedRegularExpressions())
+ .build();
+ long groupSpecTimeMs = time.milliseconds() - groupSpecStartTimeMs;
+
+ Supplier<TargetAssignmentBuilder.TargetAssignmentResult>
buildTargetAssignment = () -> {
+ long assignorStartTimeMs = time.milliseconds();
TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
- assignmentResultBuilder.build();
- long assignorTimeMs = time.milliseconds() - startTimeMs;
+ new TargetAssignmentBuilder(groupEpoch, assignor)
+ .withTime(time)
+ .withMetadataImage(metadataImage)
+ .withGroupSpec(groupSpec)
+ .build();
+ long assignorTimeMs = time.milliseconds() - assignorStartTimeMs;
if (log.isDebugEnabled()) {
- log.debug("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms: {}.",
- group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs, assignmentResult.targetAssignment());
+ log.debug("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms after building the group spec in {}ms: {}.",
+ groupId, groupEpoch, preferredServerAssignor,
assignorTimeMs, groupSpecTimeMs, assignmentResult.targetAssignment());
} else {
- log.info("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms.",
- group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs);
+ log.info("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms after building the group spec in {}ms.",
+ groupId, groupEpoch, preferredServerAssignor,
assignorTimeMs, groupSpecTimeMs);
+ }
+
+ return assignmentResult;
+ };
+
+ if (offloadAssignor) {
+ Map<String, String> previousStaticMembers =
Map.copyOf(updatedMembersAndTargetAssignment.staticMembers());
Review Comment:
`testConsumerGroupAsyncTargetAssignmentWithReplacedStaticMember` passes
without this copy. It replaces the static member whose heartbeat scheduled the
run, and the view already holds that member on top of the group's map. The copy
matters when a static member which was already in the group is replaced while
the run is in flight. Without it, the new member gets an empty target
assignment. I think that this is the common case. A static member restarts
while a run triggered by another member is in flight. Could we add a test for
it?
<details>
<summary>Test</summary>
```java
@Test
public void
testConsumerGroupAsyncTargetAssignmentWithReplacedExistingStaticMember() {
String groupId = "fooup";
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
String memberId3 = Uuid.randomUuid().toString();
String instanceId1 = "instance-id-1";
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
MockPartitionAssignor assignor = new MockPartitionAssignor("range");
CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
.addTopic(fooTopicId, fooTopicName, 6)
.buildCoordinatorMetadataImage();
long groupMetadataHash = computeGroupHash(Map.of(
fooTopicName, computeTopicHash(fooTopicName, metadataImage)));
ConsumerGroupMember member1 = new
ConsumerGroupMember.Builder(memberId1)
.setInstanceId(instanceId1)
.setState(MemberState.STABLE)
.setMemberEpoch(10)
.setPreviousMemberEpoch(10)
.setClientId(DEFAULT_CLIENT_ID)
.setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
.setRebalanceTimeoutMs(5000)
.setSubscribedTopicNames(List.of(fooTopicName))
.setServerAssignorName("range")
.setAssignedPartitions(toAssignmentWithEpochs(mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)), 10))
.build();
GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
.withMetadataImage(metadataImage)
.withConsumerGroup(new ConsumerGroupBuilder(groupId, 10)
.withMember(member1)
.withAssignment(memberId1,
mkAssignment(mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)))
.withAssignmentEpoch(10)
.withMetadataHash(groupMetadataHash))
.build();
// Member 2 joins the group and gets no assignment yet.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId2)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
// Assignor is scheduled on executor.
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
// The static member temporarily leaves the group.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId1)
.setInstanceId(instanceId1)
.setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH));
// The static member re-joins the group with a new member id.
context.consumerGroupHeartbeat(
new ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId3)
.setInstanceId(instanceId1)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of()));
// Assignor completes on executor.
assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
memberId1, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2)
)),
memberId2, new MemberAssignmentImpl(mkAssignment(
mkTopicAssignment(fooTopicId, 3, 4, 5)
))
)));
// The target assignment is written, with the replaced static member
id.
List<MockCoordinatorExecutor.ExecutorResult<CoordinatorRecord>>
tasks = context.processTasks();
assertEquals(1, tasks.size());
assertEquals(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
tasks.get(0).key());
assertUnorderedRecordsEquals(
List.of(
List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId3, mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2)
)),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, mkAssignment(
mkTopicAssignment(fooTopicId, 3, 4, 5)
))
),
List.of(GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
11, context.time.milliseconds()))
),
tasks.get(0).result().records()
);
}
```
</details>
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4370,57 +4431,115 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ String groupId = group.groupId();
+
+ String targetAssignmentUpdateKey =
groupTargetAssignmentUpdateKey(groupId);
+ if (executor.isScheduled(targetAssignmentUpdateKey)) {
+ // There is already an async assignor run in progress. We must not
start another run,
+ // sync or async, until it has completed or been cancelled,
otherwise the older run's
+ // result could be installed after the newer run's result.
+ return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
+ }
+
boolean canComputeNextTargetAssignment =
canComputeNextTargetAssignment(
group.assignmentTimestamp(),
- consumerGroupAssignmentIntervalMs(group.groupId()),
+ consumerGroupAssignmentIntervalMs(groupId),
time.milliseconds()
);
if (!canComputeNextTargetAssignment) {
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ boolean offloadAssignor = consumerGroupAssignorOffloadEnable(groupId);
+
String preferredServerAssignor = group.computePreferredServerAssignor(
member,
updatedMember
).orElse(defaultConsumerGroupAssignor.name());
- try {
- UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember,
Assignment> updatedMembersAndTargetAssignment =
- new UpdatedMembersAndTargetAssignmentView<>(
- group.members(),
- group.staticMembers(),
- group.targetAssignment(),
- ConsumerGroupMember::instanceId
- );
-
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
+ ConsumerGroupPartitionAssignor assignor =
consumerGroupAssignors.get(preferredServerAssignor);
- long startTimeMs = time.milliseconds();
- GroupSpec groupSpec = new
GroupSpecBuilder.ConsumerGroupSpecBuilder()
- .withMembers(updatedMembersAndTargetAssignment.members())
- .withSubscriptionType(subscriptionType)
-
.withTargetAssignment(updatedMembersAndTargetAssignment.targetAssignment())
- .withMetadataImage(metadataImage)
-
.withResolvedRegularExpressions(group.resolvedRegularExpressions())
- .build();
+ UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember, Assignment>
updatedMembersAndTargetAssignment =
+ new UpdatedMembersAndTargetAssignmentView<>(
+ group.members(),
+ group.staticMembers(),
+ group.targetAssignment(),
+ ConsumerGroupMember::instanceId
+ );
+
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
- TargetAssignmentBuilder assignmentResultBuilder =
- new TargetAssignmentBuilder(groupEpoch,
consumerGroupAssignors.get(preferredServerAssignor))
- .withTime(time)
- .withMetadataImage(metadataImage)
- .withGroupSpec(groupSpec);
+ // Use the same metadata image throughout.
+ CoordinatorMetadataImage metadataImage = this.metadataImage;
Review Comment:
nit: This local shadows the `metadataImage` field. The lambda below must
capture the local because `onMetadataUpdate` replaces the field on the
coordinator thread while the run is in flight. With the same name, dropping the
local would still compile and the lambda would read the field from the assignor
thread, and no test would notice. Could we rename it (e.g. `image`) and say
this in the comment? A test where a member leaves and the metadata image
changes while the run is in flight, checking what the assignor was given, would
cover it.
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4365,46 +4431,86 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
}
+ boolean offloadAssignor =
consumerGroupAssignorOffloadEnable(group.groupId());
+
String preferredServerAssignor = group.computePreferredServerAssignor(
member,
updatedMember
).orElse(defaultConsumerGroupAssignor.name());
- try {
- UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember,
Assignment> updatedMembersAndTargetAssignment =
- new UpdatedMembersAndTargetAssignmentView<>(
- group.members(),
- group.staticMembers(),
- group.targetAssignment(),
- ConsumerGroupMember::instanceId
- );
-
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
- long startTimeMs = time.milliseconds();
- GroupSpec groupSpec = new
GroupSpecBuilder.ConsumerGroupSpecBuilder()
- .withMembers(updatedMembersAndTargetAssignment.members())
- .withSubscriptionType(subscriptionType)
-
.withTargetAssignment(updatedMembersAndTargetAssignment.targetAssignment())
- .withInvertedTargetAssignment(group.invertedTargetAssignment())
- .withMetadataImage(metadataImage)
-
.withResolvedRegularExpressions(group.resolvedRegularExpressions())
- .build();
+ UpdatedMembersAndTargetAssignmentView<ConsumerGroupMember, Assignment>
updatedMembersAndTargetAssignment =
+ new UpdatedMembersAndTargetAssignmentView<>(
+ group.members(),
+ group.staticMembers(),
+ group.targetAssignment(),
+ ConsumerGroupMember::instanceId
+ );
+
updatedMembersAndTargetAssignment.addOrUpdateMember(updatedMember.memberId(),
updatedMember);
- TargetAssignmentBuilder assignmentResultBuilder =
+ // Use the same metadata image throughout.
+ CoordinatorMetadataImage metadataImage = this.metadataImage;
+
+ long groupSpecStartTimeMs = time.milliseconds();
+ GroupSpec groupSpec = new GroupSpecBuilder.ConsumerGroupSpecBuilder()
+ .withMembers(updatedMembersAndTargetAssignment.members())
+ .withSubscriptionType(subscriptionType)
+
.withTargetAssignment(updatedMembersAndTargetAssignment.targetAssignment())
+ .withInvertedTargetAssignment(group.invertedTargetAssignment())
+ .withMetadataImage(metadataImage)
+ .withResolvedRegularExpressions(group.resolvedRegularExpressions())
+ .withAssignorOffload(offloadAssignor)
+ .build();
+ long groupSpecTimeMs = time.milliseconds() - groupSpecStartTimeMs;
+
+ Supplier<TargetAssignmentBuilder.TargetAssignmentResult>
buildTargetAssignment = () -> {
+ long assignorStartTimeMs = time.milliseconds();
+ TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
new TargetAssignmentBuilder(groupEpoch,
consumerGroupAssignors.get(preferredServerAssignor))
.withTime(time)
.withMetadataImage(metadataImage)
- .withGroupSpec(groupSpec);
-
- TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
- assignmentResultBuilder.build();
- long assignorTimeMs = time.milliseconds() - startTimeMs;
+ .withGroupSpec(groupSpec)
+ .build();
+ long assignorTimeMs = time.milliseconds() - assignorStartTimeMs;
if (log.isDebugEnabled()) {
- log.debug("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms: {}.",
- group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs, assignmentResult.targetAssignment());
+ log.debug("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms after building the group spec in {}ms: {}.",
+ group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs, groupSpecTimeMs, assignmentResult.targetAssignment());
} else {
- log.info("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms.",
- group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs);
+ log.info("[GroupId {}] Computed a new target assignment for
epoch {} with '{}' assignor in {}ms after building the group spec in {}ms.",
+ group.groupId(), groupEpoch, preferredServerAssignor,
assignorTimeMs, groupSpecTimeMs);
+ }
+
+ return assignmentResult;
+ };
+
+ if (offloadAssignor) {
+ Map<String, String> previousStaticMembers =
Map.copyOf(updatedMembersAndTargetAssignment.staticMembers());
+
+ inflightOffloadedAssignorEpochs.put(group.groupId(), groupEpoch);
+ executor.schedule(
+ targetAssignmentUpdateKey,
+ buildTargetAssignment::get,
+ (result, exception) ->
handleOffloadedConsumerTargetAssignmentResult(
+ group.groupId(),
+ groupEpoch,
+ previousStaticMembers,
+ result,
+ exception
+ )
+ );
+
+ // fromLastTargetAssignment looks up the assignment by instance
id, so it's fine not to
+ // use updatedMembersAndTargetAssignment.
+ return
UpdateTargetAssignmentResult.fromLastTargetAssignment(group, updatedMember);
Review Comment:
This passes now that #24108 is merged. However, the tests added by #24108
run with offloading disabled because `GroupMetadataManagerTestContext` disables
it by default, so nothing covers this case with offloading. Could we add the
test above to this PR?
##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java:
##########
@@ -537,6 +537,7 @@ public GroupMetadataManagerTestContext build() {
GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(new MockPartitionAssignor("range"))
);
+
config.putIfAbsent(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
false);
Review Comment:
I would rather not change the default of a config in the test context. It is
hidden: a test which does not set the config runs with the assignor in the
heartbeat while brokers offload by default, and nothing in the test says so.
Without this line, 50 tests in `GroupMetadataManagerTest` fail and all the
other tests pass. Could we remove it and set the config explicitly in the tests
which need it?
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4434,11 +4553,73 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
} else {
return new UpdateTargetAssignmentResult<>(groupEpoch,
Assignment.EMPTY);
}
- } catch (PartitionAssignorException ex) {
- String msg = String.format("Failed to compute a new target
assignment for epoch %d: %s",
- groupEpoch, ex.getMessage());
- log.error("[GroupId {}] {}.", group.groupId(), msg, ex);
- throw new UnknownServerException(msg, ex);
+ }
+ }
+
+ /**
+ * Handle the result of the asynchronous task that computes a consumer
group's
+ * target assignment when assignor offloading is enabled.
+ *
+ * @param groupId The group id.
+ * @param targetAssignmentEpoch The assignment epoch.
+ * @param previousStaticMembers The static members at schedule time,
keyed by instance id.
+ * @param result The computed target assignment.
+ * @param exception The exception if the computation failed.
+ * @return A CoordinatorResult containing the records to mutate the group
state.
+ */
+ private CoordinatorResult<Void, CoordinatorRecord>
handleOffloadedConsumerTargetAssignmentResult(
+ String groupId,
+ int targetAssignmentEpoch,
+ Map<String, String> previousStaticMembers,
+ TargetAssignmentBuilder.TargetAssignmentResult result,
+ Throwable exception
+ ) {
+ if (!inflightOffloadedAssignorEpochs.remove(groupId,
targetAssignmentEpoch)) {
+ // The assignment epoch doesn't match the expected in-flight
assignment epoch.
+ // This should never happen since we only allow a single in-flight
assignor run per
+ // group and cancel assignor tasks before removing their epoch
from the in-flight map.
+ log.error("[GroupId {}] Discarding unexpected offloaded target
assignment for epoch {} (expected in-flight epoch was {}).",
+ groupId, targetAssignmentEpoch,
inflightOffloadedAssignorEpochs.get(groupId));
+ return new CoordinatorResult<>(List.of());
+ }
+
+ if (exception != null) {
+ log.error("[GroupId {}] Failed to compute a new target assignment
for epoch {}: {}.",
+ groupId, targetAssignmentEpoch, exception.getMessage(),
exception);
+ return new CoordinatorResult<>(List.of());
+ }
+
+ try {
+ ConsumerGroup consumerGroup = consumerGroup(groupId);
+ if (consumerGroup.groupEpoch() < targetAssignmentEpoch) {
+ // The assignment epoch is greater than the group epoch. This
means that the
+ // assignment was built off a group state that was not
successfully written to the
+ // log and was reverted. Discard the assignment.
+ log.info("[GroupId {}] Discarding stale offloaded target
assignment for epoch {} (current group epoch is {}).",
+ groupId, targetAssignmentEpoch,
consumerGroup.groupEpoch());
+ return new CoordinatorResult<>(List.of());
+ }
Review Comment:
Following up on
https://github.com/apache/kafka/pull/23688#discussion_r4257331179, which is
outdated now: I think that the assignment epoch check which was after this one
is still reachable, through a new group this time. Upgrading a classic group at
generation 0 bumps the group epoch to 1 and schedules a run for epoch 1. If
that write is reverted and the classic group becomes empty before the run
completes, the next consumer member creates a new consumer group in
`getOrMaybeCreateConsumerGroup`. The new group starts at epoch 1 and assignment
epoch 1 and is bumped to 2, so `maybeCancelStaleTargetAssignmentUpdate` keeps
the run, the new group waits for it, and its result is installed at epoch 1. In
the test below, member 2 is alone in the group but gets half of the partitions
because the run was computed with member 1.
It needs the run to still be queued when the classic group becomes empty, so
it is unlikely. Could we cancel the run when `getOrMaybeCreateConsumerGroup`
creates a new group? The test passes with
`cancelTargetAssignmentUpdate(groupId)` in the two branches that create a
group. I would also bring the check back. This case shows that a path which
needs a cancel is easy to miss, and the check makes sure that the result of a
stale run is never written.
<details>
<summary>Test</summary>
```java
@Test
public void
testConsumerGroupAsyncTargetAssignmentCancelledWhenNewGroupReplacesEmptyClassicGroup()
{
String groupId = "fooup";
String memberId1 = Uuid.randomUuid().toString();
String memberId2 = Uuid.randomUuid().toString();
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
.addTopic(fooTopicId, fooTopicName, 6)
.buildCoordinatorMetadataImage();
GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_MIGRATION_POLICY_CONFIG,
ConsumerGroupMigrationPolicy.UPGRADE.toString())
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
0)
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG, List.of(new
org.apache.kafka.coordinator.group.assignor.RangeAssignor()))
.withMetadataImage(metadataImage)
.build();
JoinGroupRequestData.JoinGroupRequestProtocolCollection protocols =
new JoinGroupRequestData.JoinGroupRequestProtocolCollection(1);
protocols.add(new JoinGroupRequestData.JoinGroupRequestProtocol()
.setName("range")
.setMetadata(Utils.toArray(ConsumerProtocol.serializeSubscription(new
ConsumerPartitionAssignor.Subscription(
List.of(fooTopicName),
null,
List.of()
))))
);
Map<String, byte[]> assignments = Map.of(
memberId1,
Utils.toArray(ConsumerProtocol.serializeAssignment(new
ConsumerPartitionAssignor.Assignment(List.of())))
);
// Create a classic group with member 1 at generation 0.
ClassicGroup group = context.createClassicGroup(groupId);
group.setProtocolName(Optional.of("range"));
group.add(
new ClassicGroupMember(
memberId1,
Optional.empty(),
"client-id",
"client-host",
10000,
5000,
"consumer",
protocols,
assignments.get(memberId1)
)
);
group.transitionTo(PREPARING_REBALANCE);
group.transitionTo(COMPLETING_REBALANCE);
group.transitionTo(STABLE);
context.replay(GroupCoordinatorRecordHelpers.newGroupMetadataRecord(group,
assignments));
context.commit();
ConsumerGroupHeartbeatRequestData joinRequest = new
ConsumerGroupHeartbeatRequestData()
.setGroupId(groupId)
.setMemberId(memberId2)
.setMemberEpoch(0)
.setRebalanceTimeoutMs(5000)
.setServerAssignor("range")
.setSubscribedTopicNames(List.of(fooTopicName))
.setTopicPartitions(List.of());
// Member 2 joins the classic group with the consumer protocol,
upgrading the group at
// epoch 0 and bumping the group epoch to 1. An assignor run for
epoch 1 is scheduled.
context.consumerGroupHeartbeat(joinRequest);
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
// Simulate a failed write to the log. The group is a classic group
again.
context.rollback();
// Member 1 leaves the classic group, which becomes empty.
group =
context.groupMetadataManager.getOrMaybeCreateClassicGroup(groupId, false);
group.remove(memberId1);
group.transitionTo(PREPARING_REBALANCE);
group.transitionTo(EMPTY);
context.replay(GroupCoordinatorRecordHelpers.newEmptyGroupMetadataRecord(group));
context.commit();
// Member 2 retries. The empty classic group is replaced by a new
consumer group, which
// starts at epoch 1 and is bumped to 2. The run for epoch 1 belongs
to the reverted
// upgrade, so it is cancelled and replaced.
context.consumerGroupHeartbeat(joinRequest);
assertEquals(2,
context.groupMetadataManager.consumerGroup(groupId).groupEpoch());
// Member 2 is the only member, so it gets all the partitions at
epoch 2.
assertEquals(
List.of(
new MockCoordinatorExecutor.ExecutorResult<>(
GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
new CoordinatorResult<>(List.of(
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, mkAssignment(
mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
)),
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
2, context.time.milliseconds())
))
)
),
context.processTasks()
);
assertEquals(List.of(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)),
context.executor.cancelledTasks());
}
```
</details>
##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java:
##########
@@ -32027,6 +32027,1249 @@ fooTopicName, computeTopicHash(fooTopicName,
metadataImage)
);
}
+ @Test
+ public void testConsumerGroupAsyncTargetAssignment() {
+ String groupId = "fooup";
+ String memberId1 = Uuid.randomUuid().toString();
+ String memberId2 = Uuid.randomUuid().toString();
+
+ Uuid fooTopicId = Uuid.randomUuid();
+ String fooTopicName = "foo";
+
+ MockPartitionAssignor assignor = new MockPartitionAssignor("range");
+
+ CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
+ .addTopic(fooTopicId, fooTopicName, 6)
+ .buildCoordinatorMetadataImage();
+
+ GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
0)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
+ .withMetadataImage(metadataImage)
+ .build();
+
+ // Member 1 joins the group and gets no assignment yet.
+ CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result1 = context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId1)
+ .setMemberEpoch(0)
+ .setRebalanceTimeoutMs(5000)
+ .setServerAssignor("range")
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setTopicPartitions(List.of()));
+
+ assertResponseEquals(
+ new ConsumerGroupHeartbeatResponseData()
+ .setMemberId(memberId1)
+ .setMemberEpoch(1)
+ .setHeartbeatIntervalMs(5000)
+ .setAssignment(new
ConsumerGroupHeartbeatResponseData.Assignment()
+ .setTopicPartitions(List.of())),
+ result1.response()
+ );
+
+ ConsumerGroupMember expectedMember1 = new
ConsumerGroupMember.Builder(memberId1)
+ .setState(MemberState.STABLE)
+ .setMemberEpoch(1)
+ .setPreviousMemberEpoch(0)
+ .setClientId(DEFAULT_CLIENT_ID)
+ .setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
+ .setRebalanceTimeoutMs(5000)
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setServerAssignorName("range")
+ .setAssignedPartitions(Map.of())
+ .build();
+
+ assertRecordsEquals(
+ List.of(
+
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId,
expectedMember1),
+
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 2,
computeGroupHash(Map.of(
+ fooTopicName, computeTopicHash(fooTopicName, metadataImage)
+ ))),
+
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId,
expectedMember1)
+ ),
+ result1.records()
+ );
+
+ // Assignor is scheduled on executor.
+
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Member 2 joins the group and gets no assignment yet.
+ CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result2 = context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId2)
+ .setMemberEpoch(0)
+ .setRebalanceTimeoutMs(5000)
+ .setServerAssignor("range")
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setTopicPartitions(List.of()));
+
+ assertResponseEquals(
+ new ConsumerGroupHeartbeatResponseData()
+ .setMemberId(memberId2)
+ .setMemberEpoch(1)
+ .setHeartbeatIntervalMs(5000)
+ .setAssignment(new
ConsumerGroupHeartbeatResponseData.Assignment()
+ .setTopicPartitions(List.of())),
+ result2.response()
+ );
+
+ ConsumerGroupMember expectedMember2 = new
ConsumerGroupMember.Builder(memberId2)
+ .setState(MemberState.STABLE)
+ .setMemberEpoch(1)
+ .setPreviousMemberEpoch(0)
+ .setClientId(DEFAULT_CLIENT_ID)
+ .setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
+ .setRebalanceTimeoutMs(5000)
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setServerAssignorName("range")
+ .setAssignedPartitions(Map.of())
+ .build();
+
+ assertRecordsEquals(
+ List.of(
+
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId,
expectedMember2),
+
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 3,
computeGroupHash(Map.of(
+ fooTopicName, computeTopicHash(fooTopicName, metadataImage)
+ ))),
+
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId,
expectedMember2)
+ ),
+ result2.records()
+ );
+
+ // Assignor completes on executor.
+ assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
+ memberId1, new MemberAssignmentImpl(mkAssignment(
+ mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
+ ))
+ )));
+
+ // The target assignment is written.
+ List<MockCoordinatorExecutor.ExecutorResult<CoordinatorRecord>> tasks
= context.processTasks();
+ assertEquals(1, tasks.size());
+
assertEquals(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
tasks.get(0).key());
+ assertUnorderedRecordsEquals(
+ List.of(
+ List.of(
+
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId1, mkAssignment(
+ mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
+ )),
+
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId,
memberId2, Map.of())
+ ),
+
List.of(GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
2, context.time.milliseconds()))
+ ),
+ tasks.get(0).result().records()
+ );
+
+ // The next assignment is not started automatically.
+
assertFalse(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Member 1 heartbeats again and receives the first assignment.
+ CoordinatorResult<ConsumerGroupHeartbeatResponseData,
CoordinatorRecord> result3 = context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId1)
+ .setMemberEpoch(1));
+
+ assertResponseEquals(
+ new ConsumerGroupHeartbeatResponseData()
+ .setMemberId(memberId1)
+ .setMemberEpoch(2)
+ .setHeartbeatIntervalMs(5000)
+ .setAssignment(new
ConsumerGroupHeartbeatResponseData.Assignment()
+ .setTopicPartitions(List.of(
+ new
ConsumerGroupHeartbeatResponseData.TopicPartitions()
+ .setTopicId(fooTopicId)
+ .setPartitions(List.of(0, 1, 2, 3, 4, 5))
+ ))),
+ result3.response()
+ );
+
+ ConsumerGroupMember expectedMember3 = new
ConsumerGroupMember.Builder(memberId1)
+ .setState(MemberState.STABLE)
+ .setMemberEpoch(2)
+ .setPreviousMemberEpoch(1)
+ .setClientId(DEFAULT_CLIENT_ID)
+ .setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
+ .setRebalanceTimeoutMs(5000)
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setServerAssignorName("range")
+ .setAssignedPartitions(toAssignmentWithEpochs(mkAssignment(
+ mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)), 2))
+ .build();
+
+ assertRecordsEquals(
+ List.of(
+
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId,
expectedMember3)
+ ),
+ result3.records()
+ );
+
+ // The next assignor run is scheduled.
+
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+ }
+
+ @Test
+ public void
testConsumerGroupAsyncTargetAssignmentWithJoiningClassicMember() throws
Exception {
+ // In testConsumerGroupAsyncTargetAssignment, a second member joins
using the consumer
+ // protocol while an assignor run is in flight. Here, the second
member uses the classic
+ // protocol and its heartbeat schedules the next run.
+ String groupId = "fooup";
+ String memberId1 = Uuid.randomUuid().toString();
+
+ Uuid fooTopicId = Uuid.randomUuid();
+ String fooTopicName = "foo";
+
+ MockPartitionAssignor assignor = new MockPartitionAssignor("range");
+
+ CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
+ .addTopic(fooTopicId, fooTopicName, 6)
+ .buildCoordinatorMetadataImage();
+
+ GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
0)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
+ .withMetadataImage(metadataImage)
+ .build();
+
+ // Member 1 joins the group and gets no assignment yet.
+ context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId1)
+ .setMemberEpoch(0)
+ .setRebalanceTimeoutMs(5000)
+ .setServerAssignor("range")
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setTopicPartitions(List.of()));
+
+ // Assignor is scheduled on executor.
+
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Member 2 joins the group using the classic protocol and gets no
assignment yet.
+ JoinGroupRequestData request2 = new
GroupMetadataManagerTestContext.JoinGroupRequestBuilder()
+ .withGroupId(groupId)
+ .withMemberId(UNKNOWN_MEMBER_ID)
+ .withDefaultProtocolTypeAndProtocols()
+ .build();
+ GroupMetadataManagerTestContext.JoinResult result2 =
context.sendClassicGroupJoin(request2);
+ result2.appendFuture.complete(null);
+ String memberId2 = result2.joinFuture.get().memberId();
+
+ assertEquals(
+ new JoinGroupResponseData()
+ .setMemberId(memberId2)
+ .setGenerationId(1)
+ .setProtocolType(ConsumerProtocol.PROTOCOL_TYPE)
+ .setProtocolName("range"),
+ result2.joinFuture.get()
+ );
+
+ ConsumerGroupMember expectedMember2 = new
ConsumerGroupMember.Builder(memberId2)
+ .setState(MemberState.STABLE)
+ .setMemberEpoch(1)
+ .setPreviousMemberEpoch(0)
+ .setClientId(DEFAULT_CLIENT_ID)
+ .setClientHost(DEFAULT_CLIENT_ADDRESS.toString())
+ .setRebalanceTimeoutMs(500)
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setAssignedPartitions(Map.of())
+ .setClassicMemberMetadata(
+ new ConsumerGroupMemberMetadataValue.ClassicMemberMetadata()
+ .setSessionTimeoutMs(500)
+
.setSupportedProtocols(ConsumerGroupMember.classicProtocolListFromJoinRequestProtocolCollection(
+ GroupMetadataManagerTestContext.toProtocols("range")))
+ )
+ .build();
+
+ assertRecordsEquals(
+ List.of(
+
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId,
expectedMember2),
+
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 3,
computeGroupHash(Map.of(
+ fooTopicName, computeTopicHash(fooTopicName, metadataImage)
+ ))),
+
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId,
expectedMember2)
+ ),
+ result2.records
+ );
+
+ // Assignor completes on executor.
+ assignor.prepareGroupAssignment(new GroupAssignment(Map.of(
+ memberId1, new MemberAssignmentImpl(mkAssignment(
+ mkTopicAssignment(fooTopicId, 0, 1, 2, 3, 4, 5)
+ ))
+ )));
+
+ // The target assignment is written.
+ context.processTasks();
+
+ // The next assignment is not started automatically.
+
assertFalse(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Member 2 heartbeats again and is told to rebalance, since its epoch
is behind the new target
+ // assignment epoch.
+ CoordinatorResult<HeartbeatResponseData, CoordinatorRecord> result3 =
context.sendClassicGroupHeartbeat(
+ new HeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId2)
+ .setGenerationId(1));
+
+ assertEquals(Errors.REBALANCE_IN_PROGRESS.code(),
result3.response().errorCode());
+ assertEquals(List.of(), result3.records());
+
+ // The next assignor run is scheduled.
+
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+ }
+
+ @Test
+ public void
testConsumerGroupAsyncTargetAssignmentRescheduledOnAssignorFailure() {
+ String groupId = "fooup";
+ String memberId = Uuid.randomUuid().toString();
+
+ Uuid fooTopicId = Uuid.randomUuid();
+ String fooTopicName = "foo";
+
+ ConsumerGroupPartitionAssignor assignor =
mock(ConsumerGroupPartitionAssignor.class);
+ when(assignor.name()).thenReturn("range");
+ when(assignor.assign(any(), any()))
+ .thenThrow(new PartitionAssignorException("Assignment failed."));
+
+ CoordinatorMetadataImage metadataImage = new MetadataImageBuilder()
+ .addTopic(fooTopicId, fooTopicName, 6)
+ .buildCoordinatorMetadataImage();
+
+ GroupMetadataManagerTestContext context = new
GroupMetadataManagerTestContext.Builder()
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNOR_OFFLOAD_ENABLE_CONFIG,
true)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG,
0)
+
.withConfig(GroupCoordinatorConfig.CONSUMER_GROUP_ASSIGNORS_CONFIG,
List.of(assignor))
+ .withMetadataImage(metadataImage)
+ .build();
+
+ // Member joins the group and gets no assignment yet.
+ context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId)
+ .setMemberEpoch(0)
+ .setRebalanceTimeoutMs(5000)
+ .setServerAssignor("range")
+ .setSubscribedTopicNames(List.of(fooTopicName))
+ .setTopicPartitions(List.of()));
+
+ // Assignor is scheduled on executor.
+
assertTrue(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Assignor fails on executor. No records are written.
+ List<MockCoordinatorExecutor.ExecutorResult<CoordinatorRecord>> tasks
= context.processTasks();
+ assertEquals(
+ List.of(
+ new MockCoordinatorExecutor.ExecutorResult<>(
+
GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId),
+ new CoordinatorResult<>(List.of())
+ )
+ ),
+ tasks
+ );
+
+ // The next assignment is not started automatically.
+
assertFalse(context.executor.isScheduled(GroupMetadataManager.groupTargetAssignmentUpdateKey(groupId)));
+
+ // Member heartbeats again.
+ context.consumerGroupHeartbeat(
+ new ConsumerGroupHeartbeatRequestData()
+ .setGroupId(groupId)
+ .setMemberId(memberId)
+ .setMemberEpoch(1));
Review Comment:
nit: Could we verify the response here? It would show that the member gets a
regular response after the run has failed, while it gets an error when the
assignment is computed in the heartbeat. The result of `processTasks()` in
`testConsumerGroupAsyncTargetAssignmentWithJoiningClassicMember` is not
verified either.
##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4434,11 +4553,73 @@ private UpdateTargetAssignmentResult<Assignment>
maybeUpdateTargetAssignment(
} else {
return new UpdateTargetAssignmentResult<>(groupEpoch,
Assignment.EMPTY);
}
- } catch (PartitionAssignorException ex) {
- String msg = String.format("Failed to compute a new target
assignment for epoch %d: %s",
- groupEpoch, ex.getMessage());
- log.error("[GroupId {}] {}.", group.groupId(), msg, ex);
- throw new UnknownServerException(msg, ex);
+ }
+ }
+
+ /**
+ * Handle the result of the asynchronous task that computes a consumer
group's
+ * target assignment when assignor offloading is enabled.
+ *
+ * @param groupId The group id.
+ * @param targetAssignmentEpoch The assignment epoch.
+ * @param previousStaticMembers The static members at schedule time,
keyed by instance id.
+ * @param result The computed target assignment.
+ * @param exception The exception if the computation failed.
+ * @return A CoordinatorResult containing the records to mutate the group
state.
+ */
+ private CoordinatorResult<Void, CoordinatorRecord>
handleOffloadedConsumerTargetAssignmentResult(
+ String groupId,
+ int targetAssignmentEpoch,
+ Map<String, String> previousStaticMembers,
+ TargetAssignmentBuilder.TargetAssignmentResult result,
+ Throwable exception
+ ) {
+ if (!inflightOffloadedAssignorEpochs.remove(groupId,
targetAssignmentEpoch)) {
+ // The assignment epoch doesn't match the expected in-flight
assignment epoch.
+ // This should never happen since we only allow a single in-flight
assignor run per
+ // group and cancel assignor tasks before removing their epoch
from the in-flight map.
+ log.error("[GroupId {}] Discarding unexpected offloaded target
assignment for epoch {} (expected in-flight epoch was {}).",
+ groupId, targetAssignmentEpoch,
inflightOffloadedAssignorEpochs.get(groupId));
+ return new CoordinatorResult<>(List.of());
+ }
+
+ if (exception != null) {
+ log.error("[GroupId {}] Failed to compute a new target assignment
for epoch {}: {}.",
+ groupId, targetAssignmentEpoch, exception.getMessage(),
exception);
+ return new CoordinatorResult<>(List.of());
+ }
+
+ try {
+ ConsumerGroup consumerGroup = consumerGroup(groupId);
+ if (consumerGroup.groupEpoch() < targetAssignmentEpoch) {
+ // The assignment epoch is greater than the group epoch. This
means that the
+ // assignment was built off a group state that was not
successfully written to the
+ // log and was reverted. Discard the assignment.
+ log.info("[GroupId {}] Discarding stale offloaded target
assignment for epoch {} (current group epoch is {}).",
+ groupId, targetAssignmentEpoch,
consumerGroup.groupEpoch());
+ return new CoordinatorResult<>(List.of());
+ }
+
+ TargetAssignmentRecordsBuilder<Assignment>
assignmentRecordsBuilder =
+ new
TargetAssignmentRecordsBuilder.ConsumerTargetAssignmentRecordsBuilder(log,
groupId)
+
.withTargetAssignmentMetadata(result.targetAssignmentMetadata())
+ .withCurrentMemberIds(consumerGroup.members().keySet())
+ .withChangedStaticMembers(previousStaticMembers,
consumerGroup.staticMembers())
+
.withCurrentTargetAssignment(consumerGroup.targetAssignment())
Review Comment:
No test has a member whose target assignment is left unchanged by the run.
Passing an empty map here is not caught, and we would write a record per member
on every run. Could one of the tests keep the assignment of a member?
--
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]