NicoleYWDu commented on code in PR #24071:
URL: https://github.com/apache/kafka/pull/24071#discussion_r4617990480


##########
clients/src/test/java/org/apache/kafka/clients/admin/KafkaAdminClientConsumerGroupTest.java:
##########
@@ -447,6 +447,67 @@ public void testListGroupsWithTypesOlderBrokerVersion() 
throws Exception {
         }
     }
 
+    @Test
+    public void testListGroupsWithRequireCommittedOffsetsOlderBrokerVersion() 
throws Exception {
+        ApiVersion listGroupV5 = new ApiVersion()
+            .setApiKey(ApiKeys.LIST_GROUPS.id)
+            .setMinVersion((short) 0)
+            .setMaxVersion((short) 5);
+        try (AdminClientUnitTestEnv env = new 
AdminClientUnitTestEnv(mockCluster(1, 0))) {
+            
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create(List.of(listGroupV5)));
+
+            // The committed-offsets filter cannot be used with an older 
broker.
+            
env.kafkaClient().prepareResponse(prepareMetadataResponse(env.cluster(), 
Errors.NONE));
+            env.kafkaClient().prepareUnsupportedVersionResponse(request ->
+                request instanceof ListGroupsRequest && ((ListGroupsRequest) 
request).data().requireCommittedOffsets()
+            );

Review Comment:
   Done. I also confirmed the test now fails if the check in 
`ListGroupsRequest.Builder.build` is removed.



##########
core/src/test/scala/unit/kafka/server/ListGroupsRequestTest.scala:
##########
@@ -45,6 +47,169 @@ class ListGroupsRequestTest(cluster: ClusterInstance) 
extends GroupCoordinatorBa
     testListGroups(false)
   }
 
+  // grp-3's member never heartbeats again, so keep its session alive for the 
states filter assertion.
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.CONSUMER_GROUP_SESSION_TIMEOUT_MS_CONFIG, value = 
"600000"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.CONSUMER_GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG, value = 
"600000")
+  ))
+  def testListGroupsWithRequireCommittedOffsets(): Unit = {
+    // Creates the __consumer_offsets topics because it won't be created 
automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+
+    // Create the topic.
+    val topicId = createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    // grp-1 is a classic group with a committed offset.
+    val (memberId1, generationId1) = 
joinDynamicConsumerGroupWithOldProtocol(groupId = "grp-1")
+    commitOffset(
+      groupId = "grp-1",
+      memberId = memberId1,
+      memberEpoch = generationId1,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+
+    // grp-2 is a classic group without offsets.
+    joinDynamicConsumerGroupWithOldProtocol(groupId = "grp-2")
+
+    // grp-3 is a consumer group with a committed offset.
+    val (memberId3, memberEpoch3) = joinConsumerGroup("grp-3", useNewProtocol 
= true)
+    commitOffset(
+      groupId = "grp-3",
+      memberId = memberId3,
+      memberEpoch = memberEpoch3,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+
+    // Without the filter, all groups are returned.
+    assertEquals(Set("grp-1", "grp-2", "grp-3"), 
listGroupIds(requireCommittedOffsets = false))
+
+    // With the filter, only groups with committed offsets are returned.
+    assertEquals(Set("grp-1", "grp-3"), listGroupIds(requireCommittedOffsets = 
true))
+
+    // The filter is combined with the types filter.
+    assertEquals(Set("grp-3"), listGroupIds(requireCommittedOffsets = true, 
typesFilter = List(Group.GroupType.CONSUMER.toString)))
+
+    // Delete the only offset of grp-1. The classic group must be empty first.
+    leaveGroup(
+      groupId = "grp-1",
+      memberId = memberId1,
+      useNewProtocol = false,
+      version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+    )
+
+    // The filter is combined with the states filter.
+    assertEquals(Set("grp-1"), listGroupIds(requireCommittedOffsets = true, 
statesFilter = List(ClassicGroupState.EMPTY.toString)))

Review Comment:
   Done. grp-5 is a consumer group without offsets, so the types filter check 
now has a consumer group on each side. The states filter check moved to the 
end, where grp-1 is empty without offsets and grp-4 is empty with one.



##########
core/src/test/scala/unit/kafka/server/ListGroupsRequestTest.scala:
##########
@@ -45,6 +47,169 @@ class ListGroupsRequestTest(cluster: ClusterInstance) 
extends GroupCoordinatorBa
     testListGroups(false)
   }
 
+  // grp-3's member never heartbeats again, so keep its session alive for the 
states filter assertion.
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.CONSUMER_GROUP_SESSION_TIMEOUT_MS_CONFIG, value = 
"600000"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.CONSUMER_GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG, value = 
"600000")
+  ))
+  def testListGroupsWithRequireCommittedOffsets(): Unit = {
+    // Creates the __consumer_offsets topics because it won't be created 
automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+
+    // Create the topic.
+    val topicId = createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    // grp-1 is a classic group with a committed offset.
+    val (memberId1, generationId1) = 
joinDynamicConsumerGroupWithOldProtocol(groupId = "grp-1")
+    commitOffset(
+      groupId = "grp-1",
+      memberId = memberId1,
+      memberEpoch = generationId1,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+
+    // grp-2 is a classic group without offsets.
+    joinDynamicConsumerGroupWithOldProtocol(groupId = "grp-2")
+
+    // grp-3 is a consumer group with a committed offset.
+    val (memberId3, memberEpoch3) = joinConsumerGroup("grp-3", useNewProtocol 
= true)
+    commitOffset(
+      groupId = "grp-3",
+      memberId = memberId3,
+      memberEpoch = memberEpoch3,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+
+    // Without the filter, all groups are returned.
+    assertEquals(Set("grp-1", "grp-2", "grp-3"), 
listGroupIds(requireCommittedOffsets = false))
+
+    // With the filter, only groups with committed offsets are returned.
+    assertEquals(Set("grp-1", "grp-3"), listGroupIds(requireCommittedOffsets = 
true))
+
+    // The filter is combined with the types filter.
+    assertEquals(Set("grp-3"), listGroupIds(requireCommittedOffsets = true, 
typesFilter = List(Group.GroupType.CONSUMER.toString)))
+
+    // Delete the only offset of grp-1. The classic group must be empty first.
+    leaveGroup(
+      groupId = "grp-1",
+      memberId = memberId1,
+      useNewProtocol = false,
+      version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+    )
+
+    // The filter is combined with the states filter.
+    assertEquals(Set("grp-1"), listGroupIds(requireCommittedOffsets = true, 
statesFilter = List(ClassicGroupState.EMPTY.toString)))
+
+    deleteOffset(
+      groupId = "grp-1",
+      topic = "foo",
+      partition = 0,
+      version = ApiKeys.OFFSET_DELETE.latestVersion(isUnstableApiEnabled)
+    )
+
+    assertEquals(Set("grp-3"), listGroupIds(requireCommittedOffsets = true))
+    assertEquals(Set("grp-1", "grp-2", "grp-3"), 
listGroupIds(requireCommittedOffsets = false))
+
+    // grp-4 is created by an offset commit without group membership.
+    commitOffset(
+      groupId = "grp-4",
+      memberId = "",
+      memberEpoch = -1,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+    assertEquals(Set("grp-3", "grp-4"), listGroupIds(requireCommittedOffsets = 
true))
+  }
+
+  @ClusterTest(
+    serverProperties = Array(
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.STREAMS_GROUP_INITIAL_REBALANCE_DELAY_MS_CONFIG, value = 
"0"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.STREAMS_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG, value = 
"0"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.SHARE_GROUP_ASSIGNMENT_INTERVAL_MS_CONFIG, value = "0"),
+      new ClusterConfigProperty(key = "group.share.persister.class.name", 
value = "")
+    )
+  )
+  def testListGroupsWithRequireCommittedOffsetsForStreamsAndShareGroups(): 
Unit = {
+    // Creates the __consumer_offsets topics because it won't be created 
automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+
+    // Create the topic.
+    val topicId = createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    // streams-grp is a streams group with a committed offset.
+    val topology = new StreamsGroupHeartbeatRequestData.Topology()
+      .setEpoch(1)
+      .setSubtopologies(List(
+        new StreamsGroupHeartbeatRequestData.Subtopology()
+          .setSubtopologyId("subtopology-1")
+          .setSourceTopics(List("foo").asJava)
+          .setRepartitionSinkTopics(List.empty.asJava)
+          .setRepartitionSourceTopics(List.empty.asJava)
+      ).asJava)
+    val streamsMember = streamsGroupHeartbeat(
+      groupId = "streams-grp",
+      memberId = "streams-member",
+      rebalanceTimeoutMs = 1000,
+      activeTasks = List.empty,
+      standbyTasks = List.empty,
+      warmupTasks = List.empty,
+      topology = topology
+    )
+    commitOffset(
+      groupId = "streams-grp",
+      memberId = streamsMember.memberId,
+      memberEpoch = streamsMember.memberEpoch,
+      topic = "foo",
+      topicId = topicId,
+      partition = 0,
+      offset = 10L,
+      expectedError = Errors.NONE
+    )
+
+    // share-grp is a share group. Share groups never have committed offsets.
+    shareGroupHeartbeat(
+      groupId = "share-grp",
+      subscribedTopicNames = List("foo")
+    )
+
+    assertEquals(Set("streams-grp", "share-grp"), 
listGroupIds(requireCommittedOffsets = false))
+    assertEquals(Set("streams-grp"), listGroupIds(requireCommittedOffsets = 
true))

Review Comment:
   Done. Added streams-grp-2 without offsets, plus a check with the STREAMS 
types filter.



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java:
##########
@@ -2823,4 +2828,72 @@ public void testFetchOffsets(boolean fetchAllOffsets) {
 
         assertEquals(result, coordinator.fetchOffsets(request, 
Long.MAX_VALUE));
     }
+
+    @Test
+    public void testListGroupsWithRequireCommittedOffsets() {
+        GroupMetadataManager groupMetadataManager = 
mock(GroupMetadataManager.class);
+        OffsetMetadataManager offsetMetadataManager = 
mock(OffsetMetadataManager.class);
+        GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
+            new LogContext(),
+            groupMetadataManager,
+            offsetMetadataManager,
+            Time.SYSTEM,
+            new MockCoordinatorTimer<>(Time.SYSTEM),
+            mock(GroupCoordinatorConfig.class),
+            mock(CoordinatorMetrics.class),
+            mock(CoordinatorMetricsShard.class)
+        );
+
+        @SuppressWarnings("unchecked")
+        ArgumentCaptor<Predicate<String>> groupIdFilterCaptor = 
ArgumentCaptor.forClass(Predicate.class);
+        List<ListGroupsResponseData.ListedGroup> groups = List.of(new 
ListGroupsResponseData.ListedGroup().setGroupId("with-offsets"));
+        when(groupMetadataManager.listGroups(eq(Set.of()), eq(Set.of()), 
groupIdFilterCaptor.capture(), eq(100L))).thenReturn(groups);
+
+        // Without the filter, every group matches and the offsets are not 
read.
+        assertEquals(groups, coordinator.listGroups(List.of(), List.of(), 
false, 100L));
+        assertTrue(groupIdFilterCaptor.getValue().test("with-offsets"));
+        assertTrue(groupIdFilterCaptor.getValue().test("without-offsets"));
+        verifyNoInteractions(offsetMetadataManager);
+
+        // With the filter, the offsets are read at the same committed offset 
as the groups.
+        when(offsetMetadataManager.hasCommittedOffsets("with-offsets", 
100L)).thenReturn(true);
+        when(offsetMetadataManager.hasCommittedOffsets("without-offsets", 
100L)).thenReturn(false);
+        assertEquals(groups, coordinator.listGroups(List.of(), List.of(), 
true, 100L));
+        assertTrue(groupIdFilterCaptor.getValue().test("with-offsets"));
+        assertFalse(groupIdFilterCaptor.getValue().test("without-offsets"));
+    }
+
+    @Test
+    public void 
testListGroupsWithRequireCommittedOffsetsAndStatesAndTypesFilters() {
+        OffsetMetadataManagerTest.OffsetMetadataManagerTestContext context =
+            new 
OffsetMetadataManagerTest.OffsetMetadataManagerTestContext.Builder().build();
+        GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
+            new LogContext(),
+            context.groupMetadataManager,
+            context.offsetMetadataManager,
+            context.time,
+            context.timer,
+            mock(GroupCoordinatorConfig.class),
+            mock(CoordinatorMetrics.class),
+            mock(CoordinatorMetricsShard.class)
+        );
+
+        // All four groups are empty. Committing an offset to an unknown group 
creates a simple classic group.
+        context.commitOffset("classic-with-offsets", "foo", 0, 100L, 1);
+        context.getOrMaybeCreateGroup(Group.GroupType.CLASSIC, 
"classic-without-offsets");
+        context.getOrMaybeCreateGroup(Group.GroupType.CONSUMER, 
"consumer-with-offsets");
+        context.commitOffset("consumer-with-offsets", "foo", 0, 100L, 1);
+        context.getOrMaybeCreateGroup(Group.GroupType.CONSUMER, 
"consumer-without-offsets");
+
+        BiFunction<List<String>, List<String>, Set<String>> listGroupIds = 
(statesFilter, typesFilter) ->
+            coordinator.listGroups(statesFilter, typesFilter, true, 
Long.MAX_VALUE).stream()

Review Comment:
   Will do once #24301 is merged, since reading at 
`context.lastCommittedOffset` needs the snapshot fix in the test context. I 
will add the uncommitted commit and deletion, a streams group with an offset, 
and a share group in the same change.



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