dajac commented on code in PR #23514:
URL: https://github.com/apache/kafka/pull/23514#discussion_r4641237444


##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -1045,37 +1045,29 @@ ConsumerGroup consumerGroup(
      *                          created if it does not exist.
      *
      * @return A ConsumerGroup.
-     * @throws GroupIdNotFoundException if the group does not exist and 
createIfNotExists is false.
-     * @throws IllegalStateException    if the group does not have the 
expected type.
+     * @throws GroupIdNotFoundException if createIfNotExists is false and the 
group is absent or has another type.
      * Package private for testing.
      */
     ConsumerGroup getOrMaybeCreatePersistedConsumerGroup(
         String groupId,
         boolean createIfNotExists
-    ) throws GroupIdNotFoundException, IllegalStateException {
+    ) throws GroupIdNotFoundException {
         Group group = groups.get(groupId);
-
-        if (group == null && !createIfNotExists) {
-            throw new GroupIdNotFoundException(String.format("Consumer group 
%s not found.", groupId));
+        if (group != null && group.type() != CONSUMER) {
+            // Compaction may have removed the previous group's tombstones.
+            removeGroup(groupId);
+            group = null;
         }

Review Comment:
   This block is the same in the consumer, streams and share accessors and in 
`replay(GroupMetadataKey, GroupMetadataValue)`. It also feels odd in these 
methods: `getOrMaybeCreatePersistedConsumerGroup` reads as a getter that may 
create the group, not as a method that may remove another one. On a tombstone, 
it even removes the group and then throws `GroupIdNotFoundException`. Could we 
move the removal to a helper, call it at the top of every replay method, and 
keep the accessors as they are on trunk without the simple group branches? 
Their `IllegalStateException` would then remain as a guard if a replay method 
misses the call.
   
   The helper would also explain once why removing the group is correct, and 
log. The replay used to throw in this case, and now the group goes away without 
any trace. While loading, this is how we recover when compaction removed the 
tombstones of the previous group. On a write, it could only come from a bug in 
a write path. For instance:
   
   ```java
   /**
    * Removes the group with this id if it has another type than the replayed 
record.
    *
    * The coordinator writes the tombstones of a group before it writes any 
record of a group
    * of another type with the same id. A group of another type was therefore 
deleted, and
    * compaction removed some of its tombstones. This also covers the simple 
classic group that
    * the replay of offset commits creates when no group exists.
    *
    * @param groupId The group id.
    * @param type    The group type of the record being replayed.
    */
   private void maybeRemovePreviousGroup(
       String groupId,
       Group.GroupType type
   ) {
       Group group = groups.get(groupId);
       if (group != null && group.type() != type) {
           log.info("[GroupId {}] Removed the {} group while replaying a record 
of a {} group;"
               + " its tombstones were likely removed by compaction.",
               groupId, group.type(), type);
           removeGroup(groupId);
       }
   }
   ```
   
   And at the top of each replay method, with a short comment:
   
   ```java
   String groupId = key.groupId();
   String memberId = key.memberId();
   // A group of another type with this id was deleted before this record was 
written,
   // and compaction may have removed its tombstones.
   maybeRemovePreviousGroup(groupId, CONSUMER);
   ```
   
   @squah-confluent What do you think?



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java:
##########
@@ -6787,6 +6790,20 @@ public void testReplayGroupMetadataRecords(boolean 
useDefaultRebalanceTimeout) {
         assertEquals(expectedGroup.currentClassicGroupMembers(), 
group.currentClassicGroupMembers());
     }
 
+    @ParameterizedTest
+    @ValueSource(strings = {"consumer", "share", "streams"})
+    public void testReplayGroupMetadataWithOtherGroupType(String 
previousGroupType) {
+        assertReplayWithOtherGroupType(previousGroupType, "classic",
+            groupReplayRecords("classic", 
"new-topic").findFirst().orElseThrow());

Review Comment:
   nit: When the arguments don't fit on one line, could we put one argument per 
line and the closing parenthesis on its own line? Same at 6803, 27167, 27177, 
27182, 27197, 27209 and 27213.



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardCompactionReplayTest.java:
##########
@@ -330,7 +329,6 @@ public void testClassicGroupMigratedToStreamsGroup() throws 
Exception {
      *  Classic group commits an offset
      */
     @Test
-    @Disabled("KAFKA-21117: Consumer group loading can fail with online 
downgrade")
     public void testConsumerGroupDowngradeByLeave() throws Exception {

Review Comment:
   Could we add a streams counterpart to these two tests? Most of the change is 
about the other group types, and the unit tests replay a single record. For 
instance, a classic group upgraded offline to a streams group and downgraded 
back offline fails to load on trunk (`Group classic-streams-classic-group is 
not a streams group.` on a streams tombstone, with a cleaning during the load) 
and loads with this patch:
   
   ```java
   @Test
   public void testClassicGroupOfflineUpgradeToStreamsGroupAndBack() throws 
Exception {
       CompactionReplayTestContext context = newContext();
       String groupId = "classic-streams-classic-group";
   
       JoinGroupResponseData joinResponseA = 
context.joinFirstClassicMember(groupId);
       String classicMemberA = joinResponseA.memberId();
       context.syncClassicMember(groupId, classicMemberA, 
joinResponseA.generationId(), Map.of(
           classicMemberA, List.of(new TopicPartition(FOO_TOPIC_NAME, 0))
       ));
       context.commitOffset(groupId, FOO_TOPIC_NAME, 0, 10L);
       context.leaveClassicMember(groupId, classicMemberA);
   
       String streamsMemberA = Uuid.randomUuid().toString();
       context.prepareStreamsAssignment(Map.of(streamsMemberA, context.tasks(0, 
1, 2, 3, 4, 5)));
       Map<String, StreamsMemberState> members = new LinkedHashMap<>();
       context.joinStreamsMember(groupId, streamsMemberA, "process-a", members);
       context.completeStreamsGroupRebalance(groupId, members);
       assertEquals(GroupType.STREAMS, context.groupType(groupId));
       context.leaveStreamsMember(groupId, streamsMemberA, members);
   
       JoinGroupResponseData joinResponseB = 
context.joinFirstClassicMember(groupId);
       assertEquals(GroupType.CLASSIC, context.groupType(groupId));
       String classicMemberB = joinResponseB.memberId();
       context.syncClassicMember(groupId, classicMemberB, 
joinResponseB.generationId(), Map.of(
           classicMemberB, List.of(new TopicPartition(FOO_TOPIC_NAME, 0))
       ));
       context.commitOffset(groupId, FOO_TOPIC_NAME, 1, 20L);
   
       assertCompactedVariantsLoadCleanly(context);
   }
   ```



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java:
##########
@@ -27143,6 +27160,132 @@ public void testStreamsGroupEvaluatedConfigs() {
             result.response().data().taskOffsetIntervalMs());
     }
 
+    private static Stream<CoordinatorRecord> groupReplayRecords(String 
groupType, String topicName) {
+        String groupId = "group-id";
+        String memberId = "member-id";
+        return switch (groupType) {
+            case "classic" -> 
Stream.of(GroupMetadataManagerTestContext.newGroupMetadataRecord(groupId,
+                new 
GroupMetadataValue().setProtocolType("consumer").setGeneration(1)));
+            case "consumer" -> {
+                ConsumerGroupMember member = new 
ConsumerGroupMember.Builder(memberId)
+                    .setSubscribedTopicNames(List.of(topicName))
+                    .setMemberEpoch(10)
+                    .build();
+                yield Stream.of(
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupMemberSubscriptionRecord(groupId, 
member),
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord(groupId, 10, 0),
+                    CoordinatorRecord.record(new 
ConsumerGroupPartitionMetadataKey().setGroupId(groupId),
+                        new ApiMessageAndVersion(new 
ConsumerGroupPartitionMetadataValue(), (short) 0)),
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord(groupId, 
memberId, Map.of()),
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentMetadataRecord(groupId,
 10, 12345L),
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord(groupId, 
member),
+                    
GroupCoordinatorRecordHelpers.newConsumerGroupRegularExpressionRecord(
+                        groupId, topicName + ".*", new 
ResolvedRegularExpression(Set.of(topicName), 1, 12345L))
+                );
+            }
+            case "share" -> {
+                ShareGroupMember member = new 
ShareGroupMember.Builder(memberId)
+                    .setSubscribedTopicNames(List.of(topicName))
+                    .setMemberEpoch(10)
+                    .build();
+                yield Stream.of(
+                    
GroupCoordinatorRecordHelpers.newShareGroupMemberSubscriptionRecord(groupId, 
member),
+                    
GroupCoordinatorRecordHelpers.newShareGroupEpochRecord(groupId, 10, 0),
+                    
GroupCoordinatorRecordHelpers.newShareGroupTargetAssignmentRecord(groupId, 
memberId, Map.of()),
+                    
GroupCoordinatorRecordHelpers.newShareGroupTargetAssignmentMetadataRecord(groupId,
 10, 12345L),
+                    
GroupCoordinatorRecordHelpers.newShareGroupCurrentAssignmentRecord(groupId, 
member),
+                    
GroupCoordinatorRecordHelpers.newShareGroupStatePartitionMetadataRecord(groupId,
 Map.of(),
+                        Map.of(Uuid.ZERO_UUID, new InitMapValue(topicName, 
Set.of(0), 1)), Map.of())
+                );
+            }
+            case "streams" -> {
+                StreamsGroupMember member = 
GroupMetadataManagerTestContext.streamsGroupMemberBuilderWithDefaults(memberId)
+                    .setMemberEpoch(10)
+                    .setPreviousMemberEpoch(9)
+                    .build();
+                yield Stream.of(
+                    
StreamsCoordinatorRecordHelpers.newStreamsGroupMemberRecord(groupId, member),
+                    
StreamsCoordinatorRecordHelpers.newStreamsGroupMetadataRecord(groupId, 10, 0, 
0, Map.of(), 0, 0),

Review Comment:
   This does not compile on trunk: `newStreamsGroupMetadataRecord` takes an 
`AssignmentConfigs` since #23165.
   
   ```suggestion
                       
StreamsCoordinatorRecordHelpers.newStreamsGroupMetadataRecord(groupId, 10, 0, 
0, AssignmentConfigsImpl.DEFAULT, 0, 0),
   ```



-- 
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]

Reply via email to