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


##########
core/src/test/scala/unit/kafka/server/GroupCoordinatorBaseRequestTest.scala:
##########
@@ -194,6 +209,104 @@ class GroupCoordinatorBaseRequestTest(cluster: 
ClusterInstance) {
     assertEquals(expectedResponse, response.data)
   }
 
+  protected def commitTxnOffset(
+     groupId: String,
+     memberId: String,
+     generationId: Int,
+     producerId: Long,
+     producerEpoch: Short,
+     transactionalId: String,
+     topic: String,
+     partition: Int,
+     offset: Long,
+     expectedError: Errors,
+     version: Short = 
ApiKeys.TXN_OFFSET_COMMIT.latestVersion(isUnstableApiEnabled)
+  ): Unit = {
+    val request = new TxnOffsetCommitRequest.Builder(
+      new TxnOffsetCommitRequestData()
+        .setGroupId(groupId)
+        .setMemberId(memberId)
+        .setGenerationId(generationId)
+        .setProducerId(producerId)
+        .setProducerEpoch(producerEpoch)
+        .setTransactionalId(transactionalId)
+        .setTopics(List(
+          new TxnOffsetCommitRequestData.TxnOffsetCommitRequestTopic()
+            .setName(topic)
+            .setPartitions(List(
+              new TxnOffsetCommitRequestData.TxnOffsetCommitRequestPartition()
+                .setPartitionIndex(partition)
+                .setCommittedOffset(offset)
+            ).asJava)
+        ).asJava)
+    ).build(version)
+
+    val expectedResponse = new TxnOffsetCommitResponseData()
+      .setTopics(List(
+        new TxnOffsetCommitResponseData.TxnOffsetCommitResponseTopic()
+          .setName(topic)
+          .setPartitions(List(
+            new TxnOffsetCommitResponseData.TxnOffsetCommitResponsePartition()
+              .setPartitionIndex(partition)
+              .setErrorCode(expectedError.code)
+            ).asJava)
+        ).asJava)
+
+    val response = connectAndReceive[TxnOffsetCommitResponse](request)
+    assertEquals(expectedResponse, response.data)
+  }
+
+  protected def addOffsetsToTxn(
+    groupId: String,
+    producerId: Long,
+    producerEpoch: Short,
+    transactionalId: String,
+    version: Short = 
ApiKeys.ADD_OFFSETS_TO_TXN.latestVersion(isUnstableApiEnabled)
+  ): Unit = {
+    val request = new AddOffsetsToTxnRequest.Builder(
+      new AddOffsetsToTxnRequestData()
+        .setTransactionalId(transactionalId)
+        .setProducerId(producerId)
+        .setProducerEpoch(producerEpoch)
+        .setGroupId(groupId)
+    ).build(version)
+
+    val response = connectAndReceive[AddOffsetsToTxnResponse](request)
+    assertEquals(new AddOffsetsToTxnResponseData(), response.data)
+  }
+
+  protected def initProducerId(
+    transactionalId: String,
+    transactionTimeoutMs: Int = 60000,
+    producerIdAndEpoch: ProducerIdAndEpoch,
+    expectedError: Errors,
+    version: Short = 
ApiKeys.INIT_PRODUCER_ID.latestVersion(isUnstableApiEnabled)
+  ): ProducerIdAndEpoch = {
+    val request = new InitProducerIdRequest.Builder(
+      new InitProducerIdRequestData()
+        .setTransactionalId(transactionalId)
+        .setTransactionTimeoutMs(transactionTimeoutMs)
+        .setProducerId(producerIdAndEpoch.producerId)
+        .setProducerEpoch(producerIdAndEpoch.epoch))
+      .build(version)
+
+    val response = connectAndReceive[InitProducerIdResponse](request).data()
+    assertEquals(expectedError.code(), response.errorCode())
+    new ProducerIdAndEpoch(response.producerId(), response.producerEpoch())
+  }
+
+  protected def writeTxnMarkers(

Review Comment:
   I am a bit surprised to see this one.



##########
core/src/test/scala/unit/kafka/server/TxnOffsetCommitRequestTest.scala:
##########
@@ -0,0 +1,184 @@
+/**
+ * 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 org.apache.kafka.common.test.api.{ClusterConfigProperty, 
ClusterInstance, ClusterTest, ClusterTestDefaults, ClusterTestExtensions, Type}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.internals.Topic
+import 
org.apache.kafka.common.message.WriteTxnMarkersRequestData.{WritableTxnMarker, 
WritableTxnMarkerTopic}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.common.requests.JoinGroupRequest
+import org.apache.kafka.common.utils.ProducerIdAndEpoch
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig
+import org.apache.kafka.coordinator.transaction.TransactionLogConfig
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue, fail}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.jdk.CollectionConverters.IterableHasAsScala
+
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(types = Array(Type.KRAFT), serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+  )
+)
+class TxnOffsetCommitRequestTest(cluster:ClusterInstance) extends 
GroupCoordinatorBaseRequestTest(cluster) {
+
+  @ClusterTest
+  def testTxnOffsetCommitWithNewConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(true)
+  }
+
+  @ClusterTest
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  @ClusterTest(
+    serverProperties = Array(
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG, value = "false"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, value = 
"classic"),
+    )
+  )
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndOldGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  private def testTxnOffsetCommit(useNewProtocol: Boolean): Unit = {
+    if (useNewProtocol && !isNewGroupCoordinatorEnabled) {
+      fail("Cannot use the new protocol with the old group coordinator.")
+    }
+
+    val topic = "topic"
+    val partition = 0
+    val transactionalId = "txn"
+    val groupId = "group"
+
+    // Creates the __consumer_offsets and __transaction_state topics because 
it won't be created automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+    createTransactionStateTopic()
+
+    // Join the consumer group. Note that we don't heartbeat here so we must 
use
+    // a session long enough for the duration of the test.
+    val (memberId: String, memberEpoch: Int) = joinConsumerGroup(groupId, 
useNewProtocol)
+    assertTrue(memberId != JoinGroupRequest.UNKNOWN_MEMBER_ID)
+    assertTrue(memberEpoch != JoinGroupRequest.UNKNOWN_GENERATION_ID)
+
+    createTopic(topic, 1)
+
+    var producerIdAndEpoch: ProducerIdAndEpoch = null
+    // Wait until ALLOCATE_PRODUCER_ID request finished
+    TestUtils.waitUntilTrue(() =>
+      try {
+        producerIdAndEpoch = initProducerId(
+          transactionalId = transactionalId,
+          producerIdAndEpoch = ProducerIdAndEpoch.NONE,
+          expectedError = Errors.NONE)

Review Comment:
   nit: Let's put the closing parenthesis on a new line to be consistent.



##########
core/src/test/scala/unit/kafka/server/TxnOffsetCommitRequestTest.scala:
##########
@@ -0,0 +1,184 @@
+/**
+ * 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 org.apache.kafka.common.test.api.{ClusterConfigProperty, 
ClusterInstance, ClusterTest, ClusterTestDefaults, ClusterTestExtensions, Type}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.internals.Topic
+import 
org.apache.kafka.common.message.WriteTxnMarkersRequestData.{WritableTxnMarker, 
WritableTxnMarkerTopic}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.common.requests.JoinGroupRequest
+import org.apache.kafka.common.utils.ProducerIdAndEpoch
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig
+import org.apache.kafka.coordinator.transaction.TransactionLogConfig
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue, fail}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.jdk.CollectionConverters.IterableHasAsScala
+
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(types = Array(Type.KRAFT), serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+  )
+)
+class TxnOffsetCommitRequestTest(cluster:ClusterInstance) extends 
GroupCoordinatorBaseRequestTest(cluster) {
+
+  @ClusterTest
+  def testTxnOffsetCommitWithNewConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(true)
+  }
+
+  @ClusterTest
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  @ClusterTest(
+    serverProperties = Array(
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG, value = "false"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, value = 
"classic"),
+    )
+  )
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndOldGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  private def testTxnOffsetCommit(useNewProtocol: Boolean): Unit = {
+    if (useNewProtocol && !isNewGroupCoordinatorEnabled) {
+      fail("Cannot use the new protocol with the old group coordinator.")
+    }
+
+    val topic = "topic"
+    val partition = 0
+    val transactionalId = "txn"
+    val groupId = "group"
+
+    // Creates the __consumer_offsets and __transaction_state topics because 
it won't be created automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+    createTransactionStateTopic()
+
+    // Join the consumer group. Note that we don't heartbeat here so we must 
use
+    // a session long enough for the duration of the test.
+    val (memberId: String, memberEpoch: Int) = joinConsumerGroup(groupId, 
useNewProtocol)
+    assertTrue(memberId != JoinGroupRequest.UNKNOWN_MEMBER_ID)
+    assertTrue(memberEpoch != JoinGroupRequest.UNKNOWN_GENERATION_ID)
+
+    createTopic(topic, 1)
+
+    var producerIdAndEpoch: ProducerIdAndEpoch = null
+    // Wait until ALLOCATE_PRODUCER_ID request finished
+    TestUtils.waitUntilTrue(() =>
+      try {
+        producerIdAndEpoch = initProducerId(
+          transactionalId = transactionalId,
+          producerIdAndEpoch = ProducerIdAndEpoch.NONE,
+          expectedError = Errors.NONE)
+        true
+      } catch {
+        case _: Throwable => false
+      }, "initProducerId request failed"
+    )
+
+    addOffsetsToTxn(
+      groupId = groupId,
+      producerId = producerIdAndEpoch.producerId,
+      producerEpoch = producerIdAndEpoch.epoch,
+      transactionalId = transactionalId
+    )
+
+    def verifyTxnCommitAndFetch(
+      groupId: String,
+      memberId: String,
+      generationId: Int,
+      offset: Long,
+      version: Short
+    ): Unit = {
+      commitTxnOffset(
+        groupId = groupId,
+        memberId = memberId,
+        generationId = generationId,
+        producerId = producerIdAndEpoch.producerId,
+        producerEpoch = producerIdAndEpoch.epoch,
+        transactionalId = transactionalId,
+        topic = topic,
+        partition = partition,
+        offset = offset,
+        expectedError = Errors.NONE,
+        version = version
+      )
+
+      // Send writeTxnMarker to force transaction from pending to completed
+      // hence we can retrieve offsets from OFFSET_FETCH request
+      val writableTxnMarkersResult = writeTxnMarkers(
+        Collections.singletonList(new WritableTxnMarker()
+          .setTopics(Collections.singletonList(new WritableTxnMarkerTopic()
+            .setName(Topic.GROUP_METADATA_TOPIC_NAME)
+            .setPartitionIndexes(Collections.singletonList(0))))
+          .setProducerId(producerIdAndEpoch.producerId)
+          .setProducerEpoch(producerIdAndEpoch.epoch)
+          .setCoordinatorEpoch(0.toShort)
+          .setTransactionResult(true))
+      )
+      assertEquals(1, writableTxnMarkersResult.size())
+      val writableTxnMarkerTopic = 
writableTxnMarkersResult.asScala.head.topics().asScala.head
+      assertEquals(Topic.GROUP_METADATA_TOPIC_NAME, 
writableTxnMarkerTopic.name())
+      assertEquals(1, writableTxnMarkerTopic.partitions().size())
+      assertEquals(Errors.NONE.code(), 
writableTxnMarkerTopic.partitions().asScala.head.errorCode())
+
+      val fetchOffsetsResp = fetchOffsets(
+        groups = Map(groupId -> List(new TopicPartition(topic, partition))),
+        requireStable = true,
+        version = ApiKeys.OFFSET_FETCH.latestVersion()
+      )
+      val groupIdRecord = fetchOffsetsResp.find(_.groupId() == groupId).head
+      val topicRecord = groupIdRecord.topics().asScala.find(_.name() == 
topic).head
+      val partitionRecord = 
topicRecord.partitions().asScala.find(_.partitionIndex() == partition).head
+      assertEquals(offset, partitionRecord.committedOffset())
+    }
+
+    for (version <- 0 to 
ApiKeys.TXN_OFFSET_COMMIT.latestVersion(isUnstableApiEnabled)) {
+      // Verify that the TXN_OFFSET_COMMIT request is processed correctly when 
member id is UNKNOWN_MEMBER_ID
+      // and generation id is UNKNOWN_GENERATION_ID under all api versions
+      verifyTxnCommitAndFetch(
+        groupId = groupId,
+        memberId = JoinGroupRequest.UNKNOWN_MEMBER_ID,
+        generationId = JoinGroupRequest.UNKNOWN_GENERATION_ID,
+        offset = 100 + version,
+        version = version.toShort
+      )
+
+      // Verify that the TXN_OFFSET_COMMIT request is processed correctly when 
the member ID
+      // and generation ID are known. This validation starts from version 3, 
as the member ID
+      // must not be empty from version 3 onwards.
+      if (version >= 3) {
+        verifyTxnCommitAndFetch(
+          groupId = groupId,
+          memberId = memberId,
+          generationId = memberEpoch,
+          offset = 200 + version,
+          version = version.toShort
+        )
+      }

Review Comment:
   Would it be possible to add a negative cases too? We could add them in this 
test or in another one.



##########
core/src/test/scala/unit/kafka/server/TxnOffsetCommitRequestTest.scala:
##########
@@ -0,0 +1,184 @@
+/**
+ * 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 org.apache.kafka.common.test.api.{ClusterConfigProperty, 
ClusterInstance, ClusterTest, ClusterTestDefaults, ClusterTestExtensions, Type}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.internals.Topic
+import 
org.apache.kafka.common.message.WriteTxnMarkersRequestData.{WritableTxnMarker, 
WritableTxnMarkerTopic}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.common.requests.JoinGroupRequest
+import org.apache.kafka.common.utils.ProducerIdAndEpoch
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig
+import org.apache.kafka.coordinator.transaction.TransactionLogConfig
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue, fail}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.jdk.CollectionConverters.IterableHasAsScala
+
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(types = Array(Type.KRAFT), serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+  )
+)
+class TxnOffsetCommitRequestTest(cluster:ClusterInstance) extends 
GroupCoordinatorBaseRequestTest(cluster) {
+
+  @ClusterTest
+  def testTxnOffsetCommitWithNewConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(true)
+  }
+
+  @ClusterTest
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  @ClusterTest(
+    serverProperties = Array(
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG, value = "false"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, value = 
"classic"),
+    )
+  )
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndOldGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  private def testTxnOffsetCommit(useNewProtocol: Boolean): Unit = {
+    if (useNewProtocol && !isNewGroupCoordinatorEnabled) {
+      fail("Cannot use the new protocol with the old group coordinator.")
+    }
+
+    val topic = "topic"
+    val partition = 0
+    val transactionalId = "txn"
+    val groupId = "group"
+
+    // Creates the __consumer_offsets and __transaction_state topics because 
it won't be created automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+    createTransactionStateTopic()
+
+    // Join the consumer group. Note that we don't heartbeat here so we must 
use
+    // a session long enough for the duration of the test.
+    val (memberId: String, memberEpoch: Int) = joinConsumerGroup(groupId, 
useNewProtocol)
+    assertTrue(memberId != JoinGroupRequest.UNKNOWN_MEMBER_ID)
+    assertTrue(memberEpoch != JoinGroupRequest.UNKNOWN_GENERATION_ID)
+
+    createTopic(topic, 1)
+
+    var producerIdAndEpoch: ProducerIdAndEpoch = null
+    // Wait until ALLOCATE_PRODUCER_ID request finished
+    TestUtils.waitUntilTrue(() =>
+      try {
+        producerIdAndEpoch = initProducerId(
+          transactionalId = transactionalId,
+          producerIdAndEpoch = ProducerIdAndEpoch.NONE,
+          expectedError = Errors.NONE)
+        true
+      } catch {
+        case _: Throwable => false
+      }, "initProducerId request failed"
+    )
+
+    addOffsetsToTxn(
+      groupId = groupId,
+      producerId = producerIdAndEpoch.producerId,
+      producerEpoch = producerIdAndEpoch.epoch,
+      transactionalId = transactionalId
+    )
+
+    def verifyTxnCommitAndFetch(
+      groupId: String,
+      memberId: String,
+      generationId: Int,
+      offset: Long,
+      version: Short
+    ): Unit = {
+      commitTxnOffset(
+        groupId = groupId,
+        memberId = memberId,
+        generationId = generationId,
+        producerId = producerIdAndEpoch.producerId,
+        producerEpoch = producerIdAndEpoch.epoch,
+        transactionalId = transactionalId,
+        topic = topic,
+        partition = partition,
+        offset = offset,
+        expectedError = Errors.NONE,
+        version = version
+      )
+
+      // Send writeTxnMarker to force transaction from pending to completed
+      // hence we can retrieve offsets from OFFSET_FETCH request
+      val writableTxnMarkersResult = writeTxnMarkers(
+        Collections.singletonList(new WritableTxnMarker()
+          .setTopics(Collections.singletonList(new WritableTxnMarkerTopic()
+            .setName(Topic.GROUP_METADATA_TOPIC_NAME)
+            .setPartitionIndexes(Collections.singletonList(0))))
+          .setProducerId(producerIdAndEpoch.producerId)
+          .setProducerEpoch(producerIdAndEpoch.epoch)
+          .setCoordinatorEpoch(0.toShort)
+          .setTransactionResult(true))
+      )
+      assertEquals(1, writableTxnMarkersResult.size())
+      val writableTxnMarkerTopic = 
writableTxnMarkersResult.asScala.head.topics().asScala.head
+      assertEquals(Topic.GROUP_METADATA_TOPIC_NAME, 
writableTxnMarkerTopic.name())
+      assertEquals(1, writableTxnMarkerTopic.partitions().size())
+      assertEquals(Errors.NONE.code(), 
writableTxnMarkerTopic.partitions().asScala.head.errorCode())
+
+      val fetchOffsetsResp = fetchOffsets(
+        groups = Map(groupId -> List(new TopicPartition(topic, partition))),
+        requireStable = true,
+        version = ApiKeys.OFFSET_FETCH.latestVersion()
+      )
+      val groupIdRecord = fetchOffsetsResp.find(_.groupId() == groupId).head
+      val topicRecord = groupIdRecord.topics().asScala.find(_.name() == 
topic).head
+      val partitionRecord = 
topicRecord.partitions().asScala.find(_.partitionIndex() == partition).head

Review Comment:
   nit: In Scala, we omit the `()` for getters: 
`topicRecord.partitions.asScala.find(_.partitionIndex == partition).head`. They 
are other cases in this test. Could you please check them?



##########
core/src/test/scala/unit/kafka/server/TxnOffsetCommitRequestTest.scala:
##########
@@ -0,0 +1,184 @@
+/**
+ * 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 org.apache.kafka.common.test.api.{ClusterConfigProperty, 
ClusterInstance, ClusterTest, ClusterTestDefaults, ClusterTestExtensions, Type}
+import kafka.utils.TestUtils
+import org.apache.kafka.common.TopicPartition
+import org.apache.kafka.common.internals.Topic
+import 
org.apache.kafka.common.message.WriteTxnMarkersRequestData.{WritableTxnMarker, 
WritableTxnMarkerTopic}
+import org.apache.kafka.common.protocol.{ApiKeys, Errors}
+import org.apache.kafka.common.requests.JoinGroupRequest
+import org.apache.kafka.common.utils.ProducerIdAndEpoch
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig
+import org.apache.kafka.coordinator.transaction.TransactionLogConfig
+import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue, fail}
+import org.junit.jupiter.api.extension.ExtendWith
+
+import java.util.Collections
+import scala.jdk.CollectionConverters.IterableHasAsScala
+
+@ExtendWith(value = Array(classOf[ClusterTestExtensions]))
+@ClusterTestDefaults(types = Array(Type.KRAFT), serverProperties = Array(
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
GroupCoordinatorConfig.OFFSETS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_PARTITIONS_CONFIG, value = "1"),
+    new ClusterConfigProperty(key = 
TransactionLogConfig.TRANSACTIONS_TOPIC_REPLICATION_FACTOR_CONFIG, value = "1"),
+  )
+)
+class TxnOffsetCommitRequestTest(cluster:ClusterInstance) extends 
GroupCoordinatorBaseRequestTest(cluster) {
+
+  @ClusterTest
+  def testTxnOffsetCommitWithNewConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(true)
+  }
+
+  @ClusterTest
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndNewGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  @ClusterTest(
+    serverProperties = Array(
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG, value = "false"),
+      new ClusterConfigProperty(key = 
GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, value = 
"classic"),
+    )
+  )
+  def testTxnOffsetCommitWithOldConsumerGroupProtocolAndOldGroupCoordinator(): 
Unit = {
+    testTxnOffsetCommit(false)
+  }
+
+  private def testTxnOffsetCommit(useNewProtocol: Boolean): Unit = {
+    if (useNewProtocol && !isNewGroupCoordinatorEnabled) {
+      fail("Cannot use the new protocol with the old group coordinator.")
+    }
+
+    val topic = "topic"
+    val partition = 0
+    val transactionalId = "txn"
+    val groupId = "group"
+
+    // Creates the __consumer_offsets and __transaction_state topics because 
it won't be created automatically
+    // in this test because it does not use FindCoordinator API.
+    createOffsetsTopic()
+    createTransactionStateTopic()
+
+    // Join the consumer group. Note that we don't heartbeat here so we must 
use
+    // a session long enough for the duration of the test.
+    val (memberId: String, memberEpoch: Int) = joinConsumerGroup(groupId, 
useNewProtocol)
+    assertTrue(memberId != JoinGroupRequest.UNKNOWN_MEMBER_ID)
+    assertTrue(memberEpoch != JoinGroupRequest.UNKNOWN_GENERATION_ID)
+
+    createTopic(topic, 1)
+
+    var producerIdAndEpoch: ProducerIdAndEpoch = null
+    // Wait until ALLOCATE_PRODUCER_ID request finished
+    TestUtils.waitUntilTrue(() =>
+      try {
+        producerIdAndEpoch = initProducerId(
+          transactionalId = transactionalId,
+          producerIdAndEpoch = ProducerIdAndEpoch.NONE,
+          expectedError = Errors.NONE)
+        true
+      } catch {
+        case _: Throwable => false
+      }, "initProducerId request failed"
+    )
+
+    addOffsetsToTxn(
+      groupId = groupId,
+      producerId = producerIdAndEpoch.producerId,
+      producerEpoch = producerIdAndEpoch.epoch,
+      transactionalId = transactionalId
+    )
+
+    def verifyTxnCommitAndFetch(
+      groupId: String,
+      memberId: String,
+      generationId: Int,
+      offset: Long,
+      version: Short
+    ): Unit = {
+      commitTxnOffset(
+        groupId = groupId,
+        memberId = memberId,
+        generationId = generationId,
+        producerId = producerIdAndEpoch.producerId,
+        producerEpoch = producerIdAndEpoch.epoch,
+        transactionalId = transactionalId,
+        topic = topic,
+        partition = partition,
+        offset = offset,
+        expectedError = Errors.NONE,
+        version = version
+      )
+
+      // Send writeTxnMarker to force transaction from pending to completed
+      // hence we can retrieve offsets from OFFSET_FETCH request
+      val writableTxnMarkersResult = writeTxnMarkers(
+        Collections.singletonList(new WritableTxnMarker()
+          .setTopics(Collections.singletonList(new WritableTxnMarkerTopic()
+            .setName(Topic.GROUP_METADATA_TOPIC_NAME)
+            .setPartitionIndexes(Collections.singletonList(0))))
+          .setProducerId(producerIdAndEpoch.producerId)
+          .setProducerEpoch(producerIdAndEpoch.epoch)
+          .setCoordinatorEpoch(0.toShort)
+          .setTransactionResult(true))
+      )

Review Comment:
   I wonder if we could rather call the end txn api to use the regular path.



-- 
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-unsubscr...@kafka.apache.org

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

Reply via email to