You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "dongnuo123 (via GitHub)" <gi...@apache.org> on 2023/11/20 01:59:13 UTC

[PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

dongnuo123 opened a new pull request, #14800:
URL: https://github.com/apache/kafka/pull/14800

   This pr is based on https://github.com/apache/kafka/pull/14656,
   Adding integration tests for JoinGroup API and SyncGroup API.
   
   ### JIRA
   https://issues.apache.org/jira/browse/KAFKA-15856
   
   ### Committer Checklist (excluded from commit message)
   - [ ] Verify design and implementation 
   - [ ] Verify test coverage and CI build status
   - [ ] Verify documentation (including upgrade notes)
   


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400986806


##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+
+        // Sync the leader with unmatched protocolType.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolType = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+      }
+
+      // Sync with unknown member id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = "member-id-unknown",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      // Sync with illegal generation id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 2,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.ILLEGAL_GENERATION,
+        version = version.toShort
+      )
+
+      // Sync the leader with empty protocolType and protocolName.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1),
+        version = version.toShort
+      )
+
+      // Sync the leader with matched protocolType and protocolName.

Review Comment:
   Not necessarily, sync with null protocolType or null protocolName also works



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dajac (via GitHub)" <gi...@apache.org>.
dajac merged PR #14800:
URL: https://github.com/apache/kafka/pull/14800


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1398581376


##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -1616,6 +1616,7 @@ public CoordinatorResult<Void, Record> genericGroupJoin(
             responseFuture.complete(new JoinGroupResponseData()
                 .setMemberId(memberId)
                 .setErrorCode(Errors.INVALID_SESSION_TIMEOUT.code())
+                .setProtocolName(null)

Review Comment:
   Changed the default protocolName to comply with the old group coordinator.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dajac (via GitHub)" <gi...@apache.org>.
dajac commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400988059


##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  private def testJoinGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- ApiKeys.JOIN_GROUP.oldestVersion to ApiKeys.JOIN_GROUP.latestVersion(isUnstableApiEnabled)) {
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata,
+        version = version.toShort
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+      if (version >= 4) {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setErrorCode(Errors.MEMBER_ID_REQUIRED.code)
+            .setMemberId(leaderMemberId)
+            .setProtocolName(if (version >= 7) null else ""),
+          joinLeaderResponseData
+        )
+      } else {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setLeader(leaderMemberId)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          joinLeaderResponseData
+        )
+      }
+
+      // Rejoin the group with the member id.
+      if (version >= 4) {
+        val rejoinLeaderResponseData = sendJoinRequest(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setProtocolType(if (version >= 7) "consumer" else null)
+            .setLeader(leaderMemberId)
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          rejoinLeaderResponseData
+        )
+      }
+
+      // Send a SyncGroup request.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Join with an unknown member id.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setMemberId("member-id-unknown")
+          .setErrorCode(Errors.UNKNOWN_MEMBER_ID.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = "member-id-unknown",
+          version = version.toShort
+        )
+      )
+
+      // Join with an inconsistent protocolType.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setErrorCode(Errors.INCONSISTENT_GROUP_PROTOCOL.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          protocolType = "connect",
+          version = version.toShort
+        )
+      )
+
+      // Join a second member.
+      // Non-null group instance id is not supported until JoinGroup version 5,
+      // so only version 4 needs to join a dynamic group (version < 5) and needs an extra join request to get the member id (version > 3).
+      var joinFollowerResponseData: JoinGroupResponseData = null
+      if (version == 4) {
+        joinFollowerResponseData = sendJoinRequest(
+          groupId = "grp",
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      val joinFollowerFuture = Future {
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = if (version != 4) "" else joinFollowerResponseData.memberId,
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      TestUtils.waitUntilTrue(() => {
+        val described = describeGroups(groupIds = List("grp"))
+        GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+      }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+      // The leader rejoins.
+      val rejoinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+
+      val joinFollowerFutureResponseData = Await.result(joinFollowerFuture, Duration.Inf)
+      var followerMemberId = joinFollowerFutureResponseData.memberId
+
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        joinFollowerFutureResponseData
+      )
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(leaderMemberId)
+          .setMembers(List(
+            new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata),
+            new JoinGroupResponseMember()
+              .setMemberId(followerMemberId)
+              .setGroupInstanceId(if (version >= 5) "group-instance-id" else null)
+              .setMetadata(metadata)
+          ).asJava),
+        rejoinLeaderResponseData
+      )
+
+      // Sync the leader.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = rejoinLeaderResponseData.generationId,
+        assignments = List(
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1)),
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(followerMemberId)
+            .setAssignment(Array[Byte](2))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Sync the follower.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = followerMemberId,
+        generationId = joinFollowerFutureResponseData.generationId,
+        expectedAssignment = Array[Byte](2)
+      )
+
+      // The follower rejoin doesn't trigger a rebalance if it's unchanged.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        sendJoinRequest(
+          groupId = "grp",
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          memberId = followerMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+      )
+
+      if (version >= 5) {
+        followerMemberId = testFencedStaticGroup(leaderMemberId, followerMemberId, metadata, version)
+      }
+
+      leaveGroup(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+      leaveGroup(
+        groupId = "grp",
+        memberId = followerMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+
+      deleteGroups(
+        groupIds = List("grp"),
+        expectedErrors = List(Errors.NONE),
+        version = ApiKeys.DELETE_GROUPS.latestVersion(isUnstableApiEnabled)
+      )
+    }
+  }
+
+  private def testFencedStaticGroup(
+    leaderMemberId: String,
+    followerMemberId: String,
+    metadata: Array[Byte],
+    version: Int,
+  ): String = {
+    // The leader rejoins and triggers a rebalance.
+    val rejoinLeaderFuture = Future {
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+    }
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+    // A new follower with duplicated group instance id joins.
+    val joinNewFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.COMPLETING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in COMPLETING_REBALANCE state.")
+
+    // The old follower rejoin request should be fenced.
+    val rejoinFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      memberId = followerMemberId,
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    val rejoinLeaderFutureResponseData = Await.result(rejoinLeaderFuture, Duration.Inf)
+    val newFollowerMemberId = joinNewFollowerResponseData.memberId
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(leaderMemberId)
+        .setMembers(List(
+          new JoinGroupResponseMember()
+            .setMemberId(leaderMemberId)
+            .setMetadata(metadata),
+          new JoinGroupResponseMember()
+            .setMemberId(newFollowerMemberId)
+            .setGroupInstanceId("group-instance-id")
+            .setMetadata(metadata)
+        ).asJava),
+      rejoinLeaderFutureResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(newFollowerMemberId),
+      joinNewFollowerResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setProtocolName(if (version >= 7) null else "")
+        .setMemberId(followerMemberId)
+        .setErrorCode(Errors.FENCED_INSTANCE_ID.code),
+      rejoinFollowerResponseData
+    )
+
+    newFollowerMemberId
+  }
+
+  private def verifyJoinGroupResponseDataEquals(

Review Comment:
   See this [commit](https://github.com/apache/kafka/commit/9e884bcff5a9cac8b49c4d3b783c7eedf60feff1) for an example.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400981634


##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",

Review Comment:
   Yeah, both null protocol type and null protocol name are ignored.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dajac (via GitHub)" <gi...@apache.org>.
dajac commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1401815563


##########
clients/src/main/java/org/apache/kafka/common/requests/JoinGroupResponse.java:
##########
@@ -37,6 +37,12 @@ public JoinGroupResponse(JoinGroupResponseData data, short version) {
         if (version < 7 && data.protocolName() == null) {
             data.setProtocolName("");
         }
+
+        // If nullable string for the protocol name is supported,
+        // we set empty string to be null to ensure compliance.
+        if (version >= 7 && data.protocolName() != null && data.protocolName().isEmpty()) {
+            data.setProtocolName(null);
+        }

Review Comment:
   Should we add a unit test in JoinGroupResponseTest to cover this change?



##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+
+        // Sync the leader with unmatched protocolType.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolType = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+      }
+
+      // Sync with unknown member id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = "member-id-unknown",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      // Sync with illegal generation id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 2,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.ILLEGAL_GENERATION,
+        version = version.toShort
+      )
+
+      // Sync the leader with empty protocolType and protocolName.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1),
+        version = version.toShort
+      )
+
+      // Sync the leader with matched protocolType and protocolName.

Review Comment:
   So how is it different from L158? 



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dajac (via GitHub)" <gi...@apache.org>.
dajac commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400987513


##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  private def testJoinGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- ApiKeys.JOIN_GROUP.oldestVersion to ApiKeys.JOIN_GROUP.latestVersion(isUnstableApiEnabled)) {
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata,
+        version = version.toShort
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+      if (version >= 4) {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setErrorCode(Errors.MEMBER_ID_REQUIRED.code)
+            .setMemberId(leaderMemberId)
+            .setProtocolName(if (version >= 7) null else ""),
+          joinLeaderResponseData
+        )
+      } else {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setLeader(leaderMemberId)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          joinLeaderResponseData
+        )
+      }
+
+      // Rejoin the group with the member id.
+      if (version >= 4) {
+        val rejoinLeaderResponseData = sendJoinRequest(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setProtocolType(if (version >= 7) "consumer" else null)
+            .setLeader(leaderMemberId)
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          rejoinLeaderResponseData
+        )
+      }
+
+      // Send a SyncGroup request.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Join with an unknown member id.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setMemberId("member-id-unknown")
+          .setErrorCode(Errors.UNKNOWN_MEMBER_ID.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = "member-id-unknown",
+          version = version.toShort
+        )
+      )
+
+      // Join with an inconsistent protocolType.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setErrorCode(Errors.INCONSISTENT_GROUP_PROTOCOL.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          protocolType = "connect",
+          version = version.toShort
+        )
+      )
+
+      // Join a second member.
+      // Non-null group instance id is not supported until JoinGroup version 5,
+      // so only version 4 needs to join a dynamic group (version < 5) and needs an extra join request to get the member id (version > 3).
+      var joinFollowerResponseData: JoinGroupResponseData = null
+      if (version == 4) {
+        joinFollowerResponseData = sendJoinRequest(
+          groupId = "grp",
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      val joinFollowerFuture = Future {
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = if (version != 4) "" else joinFollowerResponseData.memberId,
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      TestUtils.waitUntilTrue(() => {
+        val described = describeGroups(groupIds = List("grp"))
+        GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+      }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+      // The leader rejoins.
+      val rejoinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+
+      val joinFollowerFutureResponseData = Await.result(joinFollowerFuture, Duration.Inf)
+      var followerMemberId = joinFollowerFutureResponseData.memberId
+
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        joinFollowerFutureResponseData
+      )
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(leaderMemberId)
+          .setMembers(List(
+            new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata),
+            new JoinGroupResponseMember()
+              .setMemberId(followerMemberId)
+              .setGroupInstanceId(if (version >= 5) "group-instance-id" else null)
+              .setMetadata(metadata)
+          ).asJava),
+        rejoinLeaderResponseData
+      )
+
+      // Sync the leader.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = rejoinLeaderResponseData.generationId,
+        assignments = List(
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1)),
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(followerMemberId)
+            .setAssignment(Array[Byte](2))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Sync the follower.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = followerMemberId,
+        generationId = joinFollowerFutureResponseData.generationId,
+        expectedAssignment = Array[Byte](2)
+      )
+
+      // The follower rejoin doesn't trigger a rebalance if it's unchanged.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        sendJoinRequest(
+          groupId = "grp",
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          memberId = followerMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+      )
+
+      if (version >= 5) {
+        followerMemberId = testFencedStaticGroup(leaderMemberId, followerMemberId, metadata, version)
+      }
+
+      leaveGroup(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+      leaveGroup(
+        groupId = "grp",
+        memberId = followerMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+
+      deleteGroups(
+        groupIds = List("grp"),
+        expectedErrors = List(Errors.NONE),
+        version = ApiKeys.DELETE_GROUPS.latestVersion(isUnstableApiEnabled)
+      )
+    }
+  }
+
+  private def testFencedStaticGroup(
+    leaderMemberId: String,
+    followerMemberId: String,
+    metadata: Array[Byte],
+    version: Int,
+  ): String = {
+    // The leader rejoins and triggers a rebalance.
+    val rejoinLeaderFuture = Future {
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+    }
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+    // A new follower with duplicated group instance id joins.
+    val joinNewFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.COMPLETING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in COMPLETING_REBALANCE state.")
+
+    // The old follower rejoin request should be fenced.
+    val rejoinFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      memberId = followerMemberId,
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    val rejoinLeaderFutureResponseData = Await.result(rejoinLeaderFuture, Duration.Inf)
+    val newFollowerMemberId = joinNewFollowerResponseData.memberId
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(leaderMemberId)
+        .setMembers(List(
+          new JoinGroupResponseMember()
+            .setMemberId(leaderMemberId)
+            .setMetadata(metadata),
+          new JoinGroupResponseMember()
+            .setMemberId(newFollowerMemberId)
+            .setGroupInstanceId("group-instance-id")
+            .setMetadata(metadata)
+        ).asJava),
+      rejoinLeaderFutureResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(newFollowerMemberId),
+      joinNewFollowerResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setProtocolName(if (version >= 7) null else "")
+        .setMemberId(followerMemberId)
+        .setErrorCode(Errors.FENCED_INSTANCE_ID.code),
+      rejoinFollowerResponseData
+    )
+
+    newFollowerMemberId
+  }
+
+  private def verifyJoinGroupResponseDataEquals(

Review Comment:
   In this case, it would be better to duplicate the structure with `duplicate()` and to sort in place the field(s) with unstable orders. This is a little more robust because we don't have to modify it to support new fields in the future.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400981634


##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",

Review Comment:
   Both null protocol type and null protocol name are ignored. Only when the non-null sync request protocol name/type is not equal to group protocol name/type that an error occurs.



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dajac (via GitHub)" <gi...@apache.org>.
dajac commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400798929


##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),

Review Comment:
   nit: not needed.



##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  private def testJoinGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- ApiKeys.JOIN_GROUP.oldestVersion to ApiKeys.JOIN_GROUP.latestVersion(isUnstableApiEnabled)) {
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata,
+        version = version.toShort
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+      if (version >= 4) {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setErrorCode(Errors.MEMBER_ID_REQUIRED.code)
+            .setMemberId(leaderMemberId)
+            .setProtocolName(if (version >= 7) null else ""),
+          joinLeaderResponseData
+        )
+      } else {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setLeader(leaderMemberId)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          joinLeaderResponseData
+        )
+      }
+
+      // Rejoin the group with the member id.
+      if (version >= 4) {
+        val rejoinLeaderResponseData = sendJoinRequest(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setProtocolType(if (version >= 7) "consumer" else null)
+            .setLeader(leaderMemberId)
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          rejoinLeaderResponseData
+        )
+      }
+
+      // Send a SyncGroup request.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Join with an unknown member id.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setMemberId("member-id-unknown")
+          .setErrorCode(Errors.UNKNOWN_MEMBER_ID.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = "member-id-unknown",
+          version = version.toShort
+        )
+      )
+
+      // Join with an inconsistent protocolType.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setErrorCode(Errors.INCONSISTENT_GROUP_PROTOCOL.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          protocolType = "connect",
+          version = version.toShort
+        )
+      )
+
+      // Join a second member.
+      // Non-null group instance id is not supported until JoinGroup version 5,
+      // so only version 4 needs to join a dynamic group (version < 5) and needs an extra join request to get the member id (version > 3).
+      var joinFollowerResponseData: JoinGroupResponseData = null
+      if (version == 4) {
+        joinFollowerResponseData = sendJoinRequest(
+          groupId = "grp",
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      val joinFollowerFuture = Future {
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = if (version != 4) "" else joinFollowerResponseData.memberId,
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      TestUtils.waitUntilTrue(() => {
+        val described = describeGroups(groupIds = List("grp"))
+        GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+      }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+      // The leader rejoins.
+      val rejoinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+
+      val joinFollowerFutureResponseData = Await.result(joinFollowerFuture, Duration.Inf)
+      var followerMemberId = joinFollowerFutureResponseData.memberId
+
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        joinFollowerFutureResponseData
+      )
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(leaderMemberId)
+          .setMembers(List(
+            new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata),
+            new JoinGroupResponseMember()
+              .setMemberId(followerMemberId)
+              .setGroupInstanceId(if (version >= 5) "group-instance-id" else null)
+              .setMetadata(metadata)
+          ).asJava),
+        rejoinLeaderResponseData
+      )
+
+      // Sync the leader.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = rejoinLeaderResponseData.generationId,
+        assignments = List(
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1)),
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(followerMemberId)
+            .setAssignment(Array[Byte](2))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Sync the follower.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = followerMemberId,
+        generationId = joinFollowerFutureResponseData.generationId,
+        expectedAssignment = Array[Byte](2)
+      )
+
+      // The follower rejoin doesn't trigger a rebalance if it's unchanged.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        sendJoinRequest(
+          groupId = "grp",
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          memberId = followerMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+      )
+
+      if (version >= 5) {
+        followerMemberId = testFencedStaticGroup(leaderMemberId, followerMemberId, metadata, version)
+      }
+
+      leaveGroup(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+      leaveGroup(
+        groupId = "grp",
+        memberId = followerMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+
+      deleteGroups(
+        groupIds = List("grp"),
+        expectedErrors = List(Errors.NONE),
+        version = ApiKeys.DELETE_GROUPS.latestVersion(isUnstableApiEnabled)
+      )
+    }
+  }
+
+  private def testFencedStaticGroup(
+    leaderMemberId: String,
+    followerMemberId: String,
+    metadata: Array[Byte],
+    version: Int,
+  ): String = {
+    // The leader rejoins and triggers a rebalance.
+    val rejoinLeaderFuture = Future {
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+    }
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+    // A new follower with duplicated group instance id joins.
+    val joinNewFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.COMPLETING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in COMPLETING_REBALANCE state.")
+
+    // The old follower rejoin request should be fenced.
+    val rejoinFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      memberId = followerMemberId,
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    val rejoinLeaderFutureResponseData = Await.result(rejoinLeaderFuture, Duration.Inf)
+    val newFollowerMemberId = joinNewFollowerResponseData.memberId
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(leaderMemberId)
+        .setMembers(List(
+          new JoinGroupResponseMember()
+            .setMemberId(leaderMemberId)
+            .setMetadata(metadata),
+          new JoinGroupResponseMember()
+            .setMemberId(newFollowerMemberId)
+            .setGroupInstanceId("group-instance-id")
+            .setMetadata(metadata)
+        ).asJava),
+      rejoinLeaderFutureResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(newFollowerMemberId),
+      joinNewFollowerResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setProtocolName(if (version >= 7) null else "")
+        .setMemberId(followerMemberId)
+        .setErrorCode(Errors.FENCED_INSTANCE_ID.code),
+      rejoinFollowerResponseData
+    )
+
+    newFollowerMemberId
+  }
+
+  private def verifyJoinGroupResponseDataEquals(

Review Comment:
   Why do we need this? Couldn't we assertEquals(expected, actual)?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -1616,6 +1616,7 @@ public CoordinatorResult<Void, Record> genericGroupJoin(
             responseFuture.complete(new JoinGroupResponseData()
                 .setMemberId(memberId)
                 .setErrorCode(Errors.INVALID_SESSION_TIMEOUT.code())
+                .setProtocolName(null)

Review Comment:
   This change is a tad annoying. I wonder if we could handle this in the `JoinGroupResponse` class. We already have logic to handle the `null` case. What do you think?



##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),

Review Comment:
   ditto.



##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",

Review Comment:
   I suppose that a null protocol type is simply ignored. Is it correct?



##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),

Review Comment:
   nit: We can remove this one.



##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),

Review Comment:
   ditto.



##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+
+        // Sync the leader with unmatched protocolType.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolType = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+      }
+
+      // Sync with unknown member id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = "member-id-unknown",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      // Sync with illegal generation id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 2,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.ILLEGAL_GENERATION,
+        version = version.toShort
+      )
+
+      // Sync the leader with empty protocolType and protocolName.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1),
+        version = version.toShort
+      )
+
+      // Sync the leader with matched protocolType and protocolName.

Review Comment:
   Hum.. Should we set those?



##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+
+        // Sync the leader with unmatched protocolType.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolType = "unmatched",

Review Comment:
   Same question here but for protocol name



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1400973546


##########
core/src/test/scala/unit/kafka/server/JoinGroupRequestTest.scala:
##########
@@ -0,0 +1,402 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
+import org.apache.kafka.common.message.{JoinGroupResponseData, SyncGroupRequestData}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.jdk.CollectionConverters._
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class JoinGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testJoinGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testJoinGroup()
+  }
+
+  private def testJoinGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- ApiKeys.JOIN_GROUP.oldestVersion to ApiKeys.JOIN_GROUP.latestVersion(isUnstableApiEnabled)) {
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata,
+        version = version.toShort
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+      if (version >= 4) {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setErrorCode(Errors.MEMBER_ID_REQUIRED.code)
+            .setMemberId(leaderMemberId)
+            .setProtocolName(if (version >= 7) null else ""),
+          joinLeaderResponseData
+        )
+      } else {
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setLeader(leaderMemberId)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          joinLeaderResponseData
+        )
+      }
+
+      // Rejoin the group with the member id.
+      if (version >= 4) {
+        val rejoinLeaderResponseData = sendJoinRequest(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+        verifyJoinGroupResponseDataEquals(
+          new JoinGroupResponseData()
+            .setGenerationId(1)
+            .setMemberId(leaderMemberId)
+            .setProtocolName("consumer-range")
+            .setProtocolType(if (version >= 7) "consumer" else null)
+            .setLeader(leaderMemberId)
+            .setMembers(List(new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata)
+            ).asJava),
+          rejoinLeaderResponseData
+        )
+      }
+
+      // Send a SyncGroup request.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Join with an unknown member id.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setMemberId("member-id-unknown")
+          .setErrorCode(Errors.UNKNOWN_MEMBER_ID.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = "member-id-unknown",
+          version = version.toShort
+        )
+      )
+
+      // Join with an inconsistent protocolType.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setErrorCode(Errors.INCONSISTENT_GROUP_PROTOCOL.code)
+          .setProtocolName(if (version >= 7) null else ""),
+        sendJoinRequest(
+          groupId = "grp",
+          protocolType = "connect",
+          version = version.toShort
+        )
+      )
+
+      // Join a second member.
+      // Non-null group instance id is not supported until JoinGroup version 5,
+      // so only version 4 needs to join a dynamic group (version < 5) and needs an extra join request to get the member id (version > 3).
+      var joinFollowerResponseData: JoinGroupResponseData = null
+      if (version == 4) {
+        joinFollowerResponseData = sendJoinRequest(
+          groupId = "grp",
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      val joinFollowerFuture = Future {
+        sendJoinRequest(
+          groupId = "grp",
+          memberId = if (version != 4) "" else joinFollowerResponseData.memberId,
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          metadata = metadata,
+          version = version.toShort
+        )
+      }
+
+      TestUtils.waitUntilTrue(() => {
+        val described = describeGroups(groupIds = List("grp"))
+        GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+      }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+      // The leader rejoins.
+      val rejoinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+
+      val joinFollowerFutureResponseData = Await.result(joinFollowerFuture, Duration.Inf)
+      var followerMemberId = joinFollowerFutureResponseData.memberId
+
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        joinFollowerFutureResponseData
+      )
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(leaderMemberId)
+          .setMembers(List(
+            new JoinGroupResponseMember()
+              .setMemberId(leaderMemberId)
+              .setMetadata(metadata),
+            new JoinGroupResponseMember()
+              .setMemberId(followerMemberId)
+              .setGroupInstanceId(if (version >= 5) "group-instance-id" else null)
+              .setMetadata(metadata)
+          ).asJava),
+        rejoinLeaderResponseData
+      )
+
+      // Sync the leader.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = rejoinLeaderResponseData.generationId,
+        assignments = List(
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1)),
+          new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(followerMemberId)
+            .setAssignment(Array[Byte](2))
+        ),
+        expectedAssignment = Array[Byte](1)
+      )
+
+      // Sync the follower.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = followerMemberId,
+        generationId = joinFollowerFutureResponseData.generationId,
+        expectedAssignment = Array[Byte](2)
+      )
+
+      // The follower rejoin doesn't trigger a rebalance if it's unchanged.
+      verifyJoinGroupResponseDataEquals(
+        new JoinGroupResponseData()
+          .setGenerationId(2)
+          .setProtocolType(if (version >= 7) "consumer" else null)
+          .setProtocolName("consumer-range")
+          .setLeader(leaderMemberId)
+          .setMemberId(followerMemberId),
+        sendJoinRequest(
+          groupId = "grp",
+          groupInstanceId = if (version >= 5) "group-instance-id" else null,
+          memberId = followerMemberId,
+          metadata = metadata,
+          version = version.toShort
+        )
+      )
+
+      if (version >= 5) {
+        followerMemberId = testFencedStaticGroup(leaderMemberId, followerMemberId, metadata, version)
+      }
+
+      leaveGroup(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+      leaveGroup(
+        groupId = "grp",
+        memberId = followerMemberId,
+        useNewProtocol = false,
+        version = ApiKeys.LEAVE_GROUP.latestVersion(isUnstableApiEnabled)
+      )
+
+      deleteGroups(
+        groupIds = List("grp"),
+        expectedErrors = List(Errors.NONE),
+        version = ApiKeys.DELETE_GROUPS.latestVersion(isUnstableApiEnabled)
+      )
+    }
+  }
+
+  private def testFencedStaticGroup(
+    leaderMemberId: String,
+    followerMemberId: String,
+    metadata: Array[Byte],
+    version: Int,
+  ): String = {
+    // The leader rejoins and triggers a rebalance.
+    val rejoinLeaderFuture = Future {
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata,
+        version = version.toShort
+      )
+    }
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.PREPARING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in PREPARING_REBALANCE state.")
+
+    // A new follower with duplicated group instance id joins.
+    val joinNewFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    TestUtils.waitUntilTrue(() => {
+      val described = describeGroups(groupIds = List("grp"))
+      GenericGroupState.COMPLETING_REBALANCE.toString == described.head.groupState
+    }, msg = s"The group is not in COMPLETING_REBALANCE state.")
+
+    // The old follower rejoin request should be fenced.
+    val rejoinFollowerResponseData = sendJoinRequest(
+      groupId = "grp",
+      memberId = followerMemberId,
+      groupInstanceId = "group-instance-id",
+      metadata = metadata,
+      version = version.toShort
+    )
+
+    val rejoinLeaderFutureResponseData = Await.result(rejoinLeaderFuture, Duration.Inf)
+    val newFollowerMemberId = joinNewFollowerResponseData.memberId
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(leaderMemberId)
+        .setMembers(List(
+          new JoinGroupResponseMember()
+            .setMemberId(leaderMemberId)
+            .setMetadata(metadata),
+          new JoinGroupResponseMember()
+            .setMemberId(newFollowerMemberId)
+            .setGroupInstanceId("group-instance-id")
+            .setMetadata(metadata)
+        ).asJava),
+      rejoinLeaderFutureResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setGenerationId(3)
+        .setProtocolType(if (version >= 7) "consumer" else null)
+        .setProtocolName("consumer-range")
+        .setLeader(leaderMemberId)
+        .setMemberId(newFollowerMemberId),
+      joinNewFollowerResponseData
+    )
+
+    verifyJoinGroupResponseDataEquals(
+      new JoinGroupResponseData()
+        .setProtocolName(if (version >= 7) null else "")
+        .setMemberId(followerMemberId)
+        .setErrorCode(Errors.FENCED_INSTANCE_ID.code),
+      rejoinFollowerResponseData
+    )
+
+    newFollowerMemberId
+  }
+
+  private def verifyJoinGroupResponseDataEquals(

Review Comment:
   The elements in the list of JoinGroupResponseMember doesn't have a determined order. It would be better if I can directly change the `equals` method in JoinGroupResponseData, but I'm worried that it can cause bugs in other places



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] KAFKA-15856: Add integration tests for JoinGroup API and SyncGroup API [kafka]

Posted by "dongnuo123 (via GitHub)" <gi...@apache.org>.
dongnuo123 commented on code in PR #14800:
URL: https://github.com/apache/kafka/pull/14800#discussion_r1402122588


##########
core/src/test/scala/unit/kafka/server/SyncGroupRequestTest.scala:
##########
@@ -0,0 +1,283 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package kafka.server
+
+import kafka.test.ClusterInstance
+import kafka.test.annotation.{ClusterConfigProperty, ClusterTest, ClusterTestDefaults, Type}
+import kafka.test.junit.ClusterTestExtensions
+import kafka.utils.TestUtils
+import org.apache.kafka.clients.consumer.ConsumerPartitionAssignor
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol
+import org.apache.kafka.common.message.SyncGroupRequestData
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.coordinator.group.generic.GenericGroupState
+import org.junit.jupiter.api.{Tag, Timeout}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+@Timeout(120)
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(clusterType = Type.KRAFT, brokers = 1)
+@Tag("integration")
+class SyncGroupRequestTest(cluster: ClusterInstance) extends GroupCoordinatorBaseRequestTest(cluster) {
+  @ClusterTest(serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "true"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndNewGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  @ClusterTest(clusterType = Type.ALL, serverProperties = Array(
+    new ClusterConfigProperty(key = "unstable.api.versions.enable", value = "false"),
+    new ClusterConfigProperty(key = "group.coordinator.new.enable", value = "false"),
+    new ClusterConfigProperty(key = "offsets.topic.num.partitions", value = "1"),
+    new ClusterConfigProperty(key = "offsets.topic.replication.factor", value = "1")
+  ))
+  def testSyncGroupWithOldConsumerGroupProtocolAndOldGroupCoordinator(): Unit = {
+    testSyncGroup()
+  }
+
+  private def testSyncGroup(): 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.
+    createTopic(
+      topic = "foo",
+      numPartitions = 3
+    )
+
+    for (version <- 0 to ApiKeys.SYNC_GROUP.latestVersion(isUnstableApiEnabled)) {
+      // Sync with unknown group id.
+      syncGroupWithOldProtocol(
+        groupId = "grp-unknown",
+        memberId = "member-id",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      val metadata = ConsumerProtocol.serializeSubscription(
+        new ConsumerPartitionAssignor.Subscription(Collections.singletonList("foo"))
+      ).array
+
+      // Join a dynamic member without member id.
+      // Prior to JoinGroup version 4, a new member is immediately added if it sends a join group request with UNKNOWN_MEMBER_ID.
+      val joinLeaderResponseData = sendJoinRequest(
+        groupId = "grp",
+        metadata = metadata
+      )
+      val leaderMemberId = joinLeaderResponseData.memberId
+
+      // Rejoin the group with the member id.
+      sendJoinRequest(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        metadata = metadata
+      )
+
+      if (version >= 5) {
+        // Sync the leader with unmatched protocolName.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolName = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+
+        // Sync the leader with unmatched protocolType.
+        syncGroupWithOldProtocol(
+          groupId = "grp",
+          memberId = leaderMemberId,
+          generationId = 1,
+          protocolType = "unmatched",
+          assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+            .setMemberId(leaderMemberId)
+            .setAssignment(Array[Byte](1))
+          ),
+          expectedProtocolType = null,
+          expectedProtocolName = null,
+          expectedError = Errors.INCONSISTENT_GROUP_PROTOCOL,
+          version = version.toShort
+        )
+      }
+
+      // Sync with unknown member id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = "member-id-unknown",
+        generationId = -1,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.UNKNOWN_MEMBER_ID,
+        version = version.toShort
+      )
+
+      // Sync with illegal generation id.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 2,
+        expectedProtocolType = null,
+        expectedProtocolName = null,
+        expectedError = Errors.ILLEGAL_GENERATION,
+        version = version.toShort
+      )
+
+      // Sync the leader with empty protocolType and protocolName.
+      syncGroupWithOldProtocol(
+        groupId = "grp",
+        memberId = leaderMemberId,
+        generationId = 1,
+        assignments = List(new SyncGroupRequestData.SyncGroupRequestAssignment()
+          .setMemberId(leaderMemberId)
+          .setAssignment(Array[Byte](1))
+        ),
+        expectedAssignment = Array[Byte](1),
+        version = version.toShort
+      )
+
+      // Sync the leader with matched protocolType and protocolName.

Review Comment:
   Ah! I didn't realize I missed setting null protocolName and protocolType



-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org