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


##########
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:
   This test passes without the new check in `ListGroupsRequest.Builder.build`: 
`prepareUnsupportedVersionResponse` fails the request whatever the version, so 
the v5 `NodeApiVersions` play no role. Could we prepare a regular response 
instead? `MockClient` builds the request at v5, so the test would then fail if 
the filter could be sent to a v5 broker.
   
   ```suggestion
               // The request cannot be built at version 5, so the prepared 
response is never returned.
               
env.kafkaClient().prepareResponse(prepareMetadataResponse(env.cluster(), 
Errors.NONE));
               env.kafkaClient().prepareResponse(new ListGroupsResponse(new 
ListGroupsResponseData()));
   ```



##########
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()
+            );
+
+            ListGroupsResult result = env.adminClient().listGroups(new 
ListGroupsOptions().requireCommittedOffsets(true));
+            TestUtils.assertFutureThrows(UnsupportedVersionException.class, 
result.all());
+            assertEquals(1, result.errors().get().size());
+            assertInstanceOf(UnsupportedVersionException.class, 
result.errors().get().iterator().next());
+            assertTrue(result.valid().get().isEmpty());

Review Comment:
   nit: Could we check `errors()` and `valid()` with one `assertEquals` each? 
Same in the mixed-version test below, where the comment before the assertions 
can go too.
   
   ```suggestion
               assertEquals(
                   List.of(UnsupportedVersionException.class),
                   
result.errors().get().stream().map(Throwable::getClass).collect(Collectors.toList())
               );
               assertEquals(List.of(), new ArrayList<>(result.valid().get()));
   ```



##########
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:
   Could we also add a streams group without committed offsets? As it is, the 
test passes if streams groups are never filtered out.



##########
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"),

Review Comment:
   nit: The two offsets topic configs are already in `@ClusterTestDefaults`.
   
   ```suggestion
       serverProperties = Array(
   ```



##########
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:
   These two return the same groups with or without the filter: `grp-3` is the 
only consumer group and `grp-1` is the only empty group. They still pass if the 
coordinator ignores `requireCommittedOffsets` whenever a types or states filter 
is set. Could we add a consumer group without offsets 
(`joinConsumerGroup("grp-5", useNewProtocol = true)`) and check the states 
filter at the end instead, when `grp-1` is empty without offsets and `grp-4` is 
empty with one?
   
   ```scala
   assertEquals(Set("grp-4"), listGroupIds(requireCommittedOffsets = true, 
statesFilter = List(ClassicGroupState.EMPTY.toString)))
   ```



##########
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);

Review Comment:
   nit: Same here, `ArgumentCaptor.captor()` avoids the `@SuppressWarnings`.
   
   ```suggestion
           ArgumentCaptor<Predicate<String>> groupIdFilterCaptor = 
ArgumentCaptor.captor();
   ```



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -659,13 +659,16 @@ public Group maybeGroup(String groupId, long 
committedOffset) {
      * @param typesFilter       The types of the groups we want to list.
      *                          If empty, all groups are returned with their 
type.
      *                          If invalid, no groups are returned.
+     * @param groupIdFilter     Applied to the ids of the groups that match 
the states and types filters.
+     *                          Only the groups whose id matches are returned.

Review Comment:
   nit: The first line is over 100 characters. How about this?
   
   ```suggestion
        * @param groupIdFilter     The predicate on the ids of the groups we 
want to list.
        *                          It is applied after the states and types 
filters.
   ```



##########
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:
   Could this test read at `context.lastCommittedOffset` instead of 
`Long.MAX_VALUE`, with an offset commit and an offset deletion that are not 
committed yet? Adding a streams group with an offset and a share group would 
also cover the other coordinator cases from the KIP's test plan. Today they are 
only covered by `ListGroupsRequestTest`.



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java:
##########
@@ -1506,9 +1506,13 @@ public void testListGroups() throws ExecutionException, 
InterruptedException, Ti
                 .setGroupType("consumer")
         );
 
+        @SuppressWarnings("unchecked")
+        
ArgumentCaptor<CoordinatorRuntime.CoordinatorReadOperation<GroupCoordinatorShard,
 List<ListGroupsResponseData.ListedGroup>>> readOperationCaptor =
+            
ArgumentCaptor.forClass(CoordinatorRuntime.CoordinatorReadOperation.class);

Review Comment:
   nit: Could we use `ArgumentCaptor.captor()`? It infers the type, so we don't 
need to suppress the unchecked warning.
   
   ```suggestion
           
ArgumentCaptor<CoordinatorRuntime.CoordinatorReadOperation<GroupCoordinatorShard,
 List<ListGroupsResponseData.ListedGroup>>> readOperationCaptor =
               ArgumentCaptor.captor();
   ```



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetMetadataManagerTest.java:
##########
@@ -338,6 +338,13 @@ public boolean cleanupExpiredOffsets(String groupId, 
List<CoordinatorRecord> rec
             return isOffsetsEmptyForGroup;
         }
 
+        public boolean hasCommittedOffsets(String groupId) {
+            // The runtime keeps a snapshot at the last written offset; 
replay() in this
+            // context only snapshots the state before each record, so create 
it here.
+            snapshotRegistry.idempotentCreateSnapshot(lastWrittenOffset);

Review Comment:
   This helper creates a snapshot while it reads, which hides that 
`OffsetMetadataManagerTestContext` does not take snapshots like the runtime. 
The runtime creates a snapshot at 0 when the shard is created and one at the 
new last written offset after each write 
(`SnapshottableCoordinator.updateLastWrittenOffset`), while this context only 
creates one before each record, so after `commit()` there is no snapshot at 
`lastCommittedOffset` until the next write. `GroupMetadataManagerTestContext` 
got the fix when ListGroups first read at the committed offset in #14271: it 
creates the snapshot at `lastWrittenOffset` in the constructor and after 
`lastWrittenOffset++` in `replay`. As this is unrelated to this PR, could we 
fix the context in a separate PR, and drop these lines once it is merged?



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java:
##########
@@ -11639,6 +11639,40 @@ public void testListGroups() {
         assertEquals(expectAllGroupMap, actualAllGroupMap);
     }
 
+    @Test
+    public void testListGroupsAppliesGroupIdFilterAfterStatesAndTypesFilters() 
{
+        GroupMetadataManagerTestContext context = new 
GroupMetadataManagerTestContext.Builder()
+            .withConsumerGroup(new ConsumerGroupBuilder("consumer-group-id", 
10))
+            .build();
+        for (String groupId : List.of("classic-group-1", "classic-group-2")) {
+            
context.replay(GroupMetadataManagerTestContext.newGroupMetadataRecord(
+                groupId,
+                new GroupMetadataValue()
+                    .setMembers(List.of())
+                    .setGeneration(2)
+                    .setLeader(null)
+                    .setProtocolType("classic")
+                    .setProtocol("range")
+                    .setCurrentStateTimestamp(context.time.milliseconds())));
+        }
+        context.commit();
+
+        Set<String> testedGroupIds = new HashSet<>();
+        List<ListGroupsResponseData.ListedGroup> groups = 
context.groupMetadataManager.listGroups(
+            Set.of(),
+            Set.of(Group.GroupType.CLASSIC.toString()),
+            groupId -> {
+                testedGroupIds.add(groupId);
+                return groupId.equals("classic-group-1");
+            },
+            context.lastCommittedOffset
+        );
+
+        assertEquals(List.of("classic-group-1"), 
groups.stream().map(ListGroupsResponseData.ListedGroup::groupId).toList());

Review Comment:
   nit: Could we assert the full `ListedGroup` like `testListGroups` does?
   
   ```suggestion
           assertEquals(List.of(
               new ListGroupsResponseData.ListedGroup()
                   .setGroupId("classic-group-1")
                   .setProtocolType("classic")
                   .setGroupState(EMPTY.toString())
                   .setGroupType(Group.GroupType.CLASSIC.toString())
           ), groups);
   ```



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