You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by ca...@apache.org on 2024/11/28 16:58:39 UTC

(kafka) branch kip1071 updated (881541b8d7a -> 744679541e1)

This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a change to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git


    omit 881541b8d7a Remove superfluous record version
    omit c9507cff82e KIP1071 trunk rebase 11_25 add streams membership manager stream thread integration (#17968)
    omit 790311027d8 Fixes from rebase
    omit 9b995426eab Correctness updates from rebase
    omit ae8b81b2d9b Resolve conflicts from 11/15 trunk rebase - Initialize topologies as part of heartbeat (#17695)
    omit 13478962f35 Introduce the streams membership manager (#17564)
    omit 6069ba983b1 Resolve conflicts from 11/25 trunk rebase - Internal topic auto creation (#17433)
    omit 072e979dd33 Resolve conflicts from trunk rebase - Port tools for topic configuration (#17371)
    omit 5b4bebc0d3e Resolve conflicts from 11/25 trunk rebase - MINOR: Rebase dev branch on current trunk
    omit 86fbb0c8a1a Complete topic metadata for automatic topic creation (#17391)
    omit 662db9e0304 MINOR: Fix unit tests (#17374)
    omit 584ff178d23 MINOR: Use subtopologyId and spelling consistently (#17370)
    omit 854624c25ee KAFKA-17125: finalize TaskId (#17300)
    omit 64bcba7b99b Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-09-25
    omit 00bd56cbd63 Add broker configs for streams group
    omit 6c0b266039b Resolve conflict from 11/25 trunk rebase - Streams reconciliation logic
    omit 58c2b74b611 Improve the Streams group initialization handler
    omit bbd9708bbb7 Rename streamsHeartbeatX and streamsInitializeX to streamsGroupX
    omit ff472e36156 StickyTaskAssignor
    omit eb8ecfdca98 Minor: Revert test changes
    omit b97a8d02779 Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-08-15
    omit eddb74f24e1 Resolve conflicts from 11/25 trunk rebase - Implement DescribeStreamsGroup RPC handling
    omit 072c1fe9747 Resovle conflicts from 11/25 trunk rebase - Update RPCs
    omit 7490fda1fea Resolve conflicts for 11/25 trunk rebase - Rebased on AK trunk 2024-07-16
    omit 9cfcf1a33db Resolve conflicts from 11/25 rebase - Get SmokeTestDriverIntegrationTest working
    omit 89a2b27394a Reslove confict from 11/25 trunk rebase - Replay all streams-related records
    omit e218779e42d Reslove conflicts from 11/25 rebase - Create assignment-related classes for streams groups
    omit 08d78f802f0 Define the assignor interface for streams and implement a simple assignor
    omit 63eef9d740e Add streams group member
    omit 8ccd17c0d39 Resolve conflict from 11/25 rebase Basic heartbeat RPC handler
    omit 460d0b777e8 Minor: Rename TaskId to TaskIds
    omit 9af3f93669f Add Assignment class in group coordinator for Streams
    omit a5ab91ccbf6 Resolve merge conflict from 11/25 trunk rebase Implement InitStreamsApp RPC in the group coordinator
    omit 97c53d1c0b5 Define initial record types for the consumer offset topic
    omit 53169a3a68a Minor: Test fixes
    omit 548283e93c7 Resolve conflict from 11/25 trunk rebase - Create and inject StreamsHeartbeatRequestManager
    omit 8c26aae0f92 Implement StreamsInitialize request manager
    omit 528e3cb307b Resolve merge conflict from 11/25 rebase - Specify AsyncKafkaConsumer interface with Streams for the Rebalance PoC
    omit 9c8c30e67d8 Resolve merge conflict from 11/25 trunk rebase - Define RPCs to perform client-side assignment
    omit 16be1c4253a Reslove merge conflict from 11/25 trunk rebase - StreamsInitialize RPC and some errors
    omit 02dca3ef6dc Very initial (compiling) streams RPCs.
     add 3268435fd66 KAFKA-18013: Add AutoOffsetResetStrategy internal class (#17858)
     add 54843e6e1ed KAFKA-18077 Remove deprecated JmxReporter(String) (#17923)
     add d17a1492054 KAFKA-17956 Remove Admin.listShareGroups (#17912)
     add 7908a4838b4 Fix long running RangeQueryIntegrationTest. (#17933)
     add 0f33b16fdf7 KAFKA-18085: Abort inflight requests on existing connections while rebootstrapping (#17939)
     add 13d9a199f25 KAFKA-18011 Remove ZooKeeper sections from the docs (#17813)
     add 95947d2f581 KAFKA-17299: add unit tests for previous fix (#17919)
     add 7f8a592ad19 KAFKA-17869: Adding tests to ensure KIP-1076 doesn't interfere producer metrics[2/3] (#17783)
     add 4fc9e442c30 KAFKA-17898: Refine Epoch Bumping Logic (#17849)
     add 918a67ece83 MINOR: Improve Docker examples readme (#17894)
     add 5480d54d185 KAFKA-17544: Add log message for early access use of KafkaShareConsumer (#17940)
     add 48d60efe980 KAFKA-17990: Deflake testShareAutoOffsetResetDefaultValue (#17916)
     add cebec91470c KAFKA-18080 Replace DelayedItem by Long type (#17927)
     add 58bf20d6753 MINOR: add </script> back to security.html (#17944)
     add 0b081fc3100 KAFKA-15561 [2/N]: Background event and subscription state changes for RE2J pattern (#17918)
     add 55577e73b2a KAFKA-18083 ClusterInstance custom controllerListener not work (#17932)
     add 866d66229da KAFKA-18056: Fixed bug in handling commitAsync responses (#17909)
     add 056a76e2b91 KAFKA-17811 Separate modules to use different JDKs (#17522)
     add 0e4d8b3e868 KAFKA-17569 Rewrite TestLinearWriteSpeed by Java (#17736)
     add 11ce41fb1d5 KAFKA-18092: Mark testBumpTransactionalEpochWithTV2Enabled as flaky (#17945)
     add 24dd11d6936 KAFKA-17593; [8/N] Resolve regular expressions (#17864)
     add b42efc7dc26 KAFKA-18049: Upgrade the caffeine version to 3.1.1 (#17879)
     add 98d47f47ef2 KAFKA-18028 the effective kraft version of --no-initial-controllers should be 1 rather than 0 (#17836)
     add f5d712396bd MINOR: fix warnings in Kafka Streams state store tests (#17855)
     add 2b2b3cd355c KAFKA-18062: use feature version to enable ELR (#17867)
     add 3f834781a43 KAFKA-12844: clean up TaskId (#17904)
     add 3710add2a7f KAFKA-18012: Update the Scram configuration section for KRaft (#17844)
     add 434fe7c26e3 KAFKA-18081 Remove isKRaftTest from the kraft-only tests (#17934)
     add c32a49549df MINOR: Remove duplicate valid value in document (#17947)
     add 37b4d9b01d5 KAFKA-15561 [3/N]: Client support for SubscriptionPattern in HB (#17951)
     add aae42ef656a KAFKA-17593; [9/N] Mark ConsumerGroupHeartbeat API v1 as stable (#17961)
     add 486f65e8c60 KAFKA-18100 `Using` block suppresses all errors (#17954)
     add a39c984d216 KAFKA-15561 [4/N]: MockConsumer support for SubscriptionPattern (#17962)
     add c446e799be3 KAFKA-17010 Remove `DescribeLogDirsResponse#LogDirInfo`, `DescribeLogDirsResponse#ReplicaInfo`, and `DescribeLogDirsResult#all` (#17953)
     add cdf3aab661f MINOR: remove zk from several tests (#17949)
     add d334f60944f MINOR: KStreamRepartitionIntegrationTest  bug  (#17963)
     add b08b64c2d85 KAFKA-18098 add kraft support to testReplicaPlacementAllServers and testReplicaPlacementPartialServers (#17955)
     add 8be99f44dc1 KAFKA-18097 Upgrade readme to include min JDK changes (#17948)
     add 5243fb9a7d7 KAFKA-18026: migrate KTableSource to use ProcesserSupplier#stores (#17903)
     add e1ba01d2144 KAFKA-18109 Fix failed SaslClientsWithInvalidCredentialsTest in tools module (#17971)
     new 5eb61c087ca Very initial (compiling) streams RPCs.
     new f8ecdc9a716 Reslove merge conflict from 11/25 trunk rebase - StreamsInitialize RPC and some errors
     new 7cd85abe2db Resolve merge conflict from 11/25 trunk rebase - Define RPCs to perform client-side assignment
     new 9e3ba3e0f5a Resolve merge conflict from 11/25 rebase - Specify AsyncKafkaConsumer interface with Streams for the Rebalance PoC
     new a19bc7d97b7 Implement StreamsInitialize request manager
     new b2e6b80df6e Resolve conflict from 11/25 trunk rebase - Create and inject StreamsHeartbeatRequestManager
     new 8f22f7a6181 Minor: Test fixes
     new 286314d72ae Define initial record types for the consumer offset topic
     new c1a597b211e Resolve merge conflict from 11/25 trunk rebase Implement InitStreamsApp RPC in the group coordinator
     new 60f6773fa63 Add Assignment class in group coordinator for Streams
     new 41669d978ec Minor: Rename TaskId to TaskIds
     new 4c64b358d62 Resolve conflict from 11/25 rebase Basic heartbeat RPC handler
     new 9b448029274 Add streams group member
     new d06afbd4a96 Define the assignor interface for streams and implement a simple assignor
     new 049aece0aa3 Reslove conflicts from 11/25 rebase - Create assignment-related classes for streams groups
     new cc4985e5972 Reslove confict from 11/25 trunk rebase - Replay all streams-related records
     new 7d73d52e8b6 Resolve conflicts from 11/25 rebase - Get SmokeTestDriverIntegrationTest working
     new 6c36a43fe9d Resolve conflicts for 11/25 trunk rebase - Rebased on AK trunk 2024-07-16
     new 2dd10b7147e Resovle conflicts from 11/25 trunk rebase - Update RPCs
     new 6a4aa0cf1d4 Resolve conflicts from 11/25 trunk rebase - Implement DescribeStreamsGroup RPC handling
     new dc5b2ef7ecd Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-08-15
     new a002fe9c241 Minor: Revert test changes
     new eeea1ca9205 StickyTaskAssignor
     new 93b72dba05c Rename streamsHeartbeatX and streamsInitializeX to streamsGroupX
     new 7a9105b93fc Improve the Streams group initialization handler
     new 133a442e66b Resolve conflict from 11/25 trunk rebase - Streams reconciliation logic
     new 51155f993e6 Add broker configs for streams group
     new d1794f477ba Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-09-25
     new deb38899cc9 KAFKA-17125: finalize TaskId (#17300)
     new 8b6094c4e32 MINOR: Use subtopologyId and spelling consistently (#17370)
     new 0953df59d7b MINOR: Fix unit tests (#17374)
     new b18625b86ff Complete topic metadata for automatic topic creation (#17391)
     new 16c51af4e20 Resolve conflicts from 11/25 trunk rebase - MINOR: Rebase dev branch on current trunk
     new f5f901771ce Resolve conflicts from trunk rebase - Port tools for topic configuration (#17371)
     new 4686728d883 Resolve conflicts from 11/25 trunk rebase - Internal topic auto creation (#17433)
     new dcb0c923ff7 Introduce the streams membership manager (#17564)
     new 6b98ec67ee3 Resolve conflicts from 11/15 trunk rebase - Initialize topologies as part of heartbeat (#17695)
     new e19b7e08737 Correctness updates from rebase
     new 1e8284b71d2 Fixes from rebase
     new b3eeed7a093 KIP1071 trunk rebase 11_25 add streams membership manager stream thread integration (#17968)
     new c7deec0e70c Remove superfluous record version
     new 744679541e1 Remove unused import

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (881541b8d7a)
            \
             N -- N -- N   refs/heads/kip1071 (744679541e1)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 42 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .github/workflows/build.yml                        |   2 +-
 .github/workflows/ci-complete.yml                  |   2 +-
 LICENSE-binary                                     |   2 +-
 README.md                                          |   6 +-
 build.gradle                                       |  36 +-
 checkstyle/import-control-jmh-benchmarks.xml       |   1 +
 .../apache/kafka/clients/CommonClientConfigs.java  |   3 +-
 .../java/org/apache/kafka/clients/KafkaClient.java |   6 -
 .../org/apache/kafka/clients/MetadataUpdater.java  |  17 +
 .../org/apache/kafka/clients/NetworkClient.java    |  53 +-
 .../java/org/apache/kafka/clients/admin/Admin.java |  20 -
 .../kafka/clients/admin/DescribeLogDirsResult.java |  46 --
 .../kafka/clients/admin/ForwardingAdmin.java       |   5 -
 .../kafka/clients/admin/KafkaAdminClient.java      | 142 +---
 .../clients/admin/ListShareGroupsOptions.java      |  51 --
 .../kafka/clients/admin/ListShareGroupsResult.java |  84 ---
 .../kafka/clients/admin/ShareGroupListing.java     |  91 ---
 .../admin/internals/AdminMetadataManager.java      |  11 +-
 .../kafka/clients/consumer/ConsumerConfig.java     |   5 +-
 .../kafka/clients/consumer/MockConsumer.java       |  43 +-
 .../kafka/clients/consumer/MockShareConsumer.java  |   3 +-
 .../clients/consumer/OffsetResetStrategy.java      |   4 +
 .../internals/AbstractHeartbeatRequestManager.java |   6 +
 .../consumer/internals/AsyncKafkaConsumer.java     |  35 +-
 .../internals/AutoOffsetResetStrategy.java         | 105 +++
 .../consumer/internals/ClassicKafkaConsumer.java   |   5 +-
 .../internals/ConsumerHeartbeatRequestManager.java |  15 +-
 .../clients/consumer/internals/ConsumerUtils.java  |   5 +-
 .../consumer/internals/OffsetFetcherUtils.java     |  15 +-
 .../internals/ShareConsumeRequestManager.java      |   5 +-
 .../internals/ShareConsumerDelegateCreator.java    |   7 +
 .../consumer/internals/SubscriptionState.java      |  74 +-
 .../internals/events/ApplicationEvent.java         |   5 +-
 .../events/ApplicationEventProcessor.java          |  26 +
 .../internals/events/ResetOffsetEvent.java         |   8 +-
 ...> TopicRe2JPatternSubscriptionChangeEvent.java} |  23 +-
 .../kafka/clients/producer/KafkaProducer.java      |  14 +-
 .../producer/internals/TransactionManager.java     | 133 +++-
 .../apache/kafka/common/config/TopicConfig.java    |   2 +-
 .../apache/kafka/common/metrics/JmxReporter.java   |  13 +-
 .../common/requests/DescribeLogDirsResponse.java   |  66 --
 .../message/ConsumerGroupHeartbeatRequest.json     |   1 -
 .../java/org/apache/kafka/clients/MockClient.java  |   5 -
 .../apache/kafka/clients/NetworkClientTest.java    |  54 +-
 .../kafka/clients/admin/KafkaAdminClientTest.java  | 118 +--
 .../kafka/clients/admin/MockAdminClient.java       |   5 -
 .../kafka/clients/consumer/KafkaConsumerTest.java  |  15 +-
 .../consumer/KafkaShareConsumerMetricsTest.java    |   3 +-
 .../kafka/clients/consumer/MockConsumerTest.java   |  19 +-
 .../internals/AbstractCoordinatorTest.java         |   3 +-
 .../consumer/internals/AsyncKafkaConsumerTest.java |  46 +-
 .../internals/AutoOffsetResetStrategyTest.java     |  77 ++
 .../internals/CommitRequestManagerTest.java        |   3 +-
 .../consumer/internals/CompletedFetchTest.java     |   3 +-
 .../internals/ConsumerCoordinatorTest.java         |   7 +-
 .../ConsumerHeartbeatRequestManagerTest.java       |  56 ++
 .../consumer/internals/ConsumerMetadataTest.java   |   3 +-
 .../internals/FetchRequestManagerTest.java         |  57 +-
 .../clients/consumer/internals/FetcherTest.java    |  61 +-
 .../consumer/internals/OffsetFetcherTest.java      |  81 +-
 .../internals/OffsetForLeaderEpochClientTest.java  |   5 +-
 .../internals/OffsetsRequestManagerTest.java       |   7 +-
 .../internals/ShareConsumeRequestManagerTest.java  |  70 +-
 .../consumer/internals/ShareConsumerImplTest.java  |  21 +-
 .../consumer/internals/SubscriptionStateTest.java  |  52 +-
 .../internals/TopicMetadataFetcherTest.java        |   3 +-
 .../events/ApplicationEventProcessorTest.java      |  43 +-
 .../kafka/clients/producer/KafkaProducerTest.java  | 116 +++
 .../producer/internals/TransactionManagerTest.java |  60 +-
 .../kafka/common/metrics/JmxReporterTest.java      |  19 -
 .../kafka/connect/runtime/WorkerSinkTaskTest.java  |   4 +-
 .../runtime/isolation/SynchronizationTest.java     |   1 +
 .../storage/ConnectorOffsetBackingStoreTest.java   |   4 +-
 .../kafka/connect/util/KafkaBasedLogTest.java      |   4 +-
 .../common/runtime/MockCoordinatorExecutor.java    | 127 ++++
 .../scala/kafka/server/AbstractFetcherThread.scala |  19 +-
 .../main/scala/kafka/server/ControllerServer.scala |   3 +-
 core/src/main/scala/kafka/server/KafkaConfig.scala |   2 -
 core/src/main/scala/kafka/tools/StorageTool.scala  |  14 +-
 core/src/main/scala/kafka/utils/DelayedItem.scala  |  44 --
 .../java/kafka/test/api/ShareConsumerTest.java     |  47 +-
 .../kafka/admin/RemoteTopicCrudTest.scala          |  45 +-
 ...merWithLegacyMessageFormatIntegrationTest.scala |  34 +-
 ...onTokenEndToEndAuthorizationWithOwnerTest.scala |   6 +-
 .../kafka/api/PlaintextAdminIntegrationTest.scala  |  27 +-
 .../SaslClientsWithInvalidCredentialsTest.scala    |   5 +-
 .../scala/integration/kafka/api/SaslSetup.scala    |   2 +-
 .../integration/kafka/api/TransactionsTest.scala   |   1 +
 .../server/DynamicBrokerReconfigurationTest.scala  |  43 +-
 .../kafka/server/GssapiAuthenticationTest.scala    |   2 +-
 .../kafka/server/QuorumTestHarness.scala           |   8 +-
 .../kafka/server/RaftClusterSnapshotTest.scala     |   4 +-
 .../scala/kafka/raft/KafkaMetadataLogTest.scala    | 146 ++--
 .../src/test/scala/kafka/utils/TestInfoUtils.scala |   8 +
 .../scala/other/kafka/TestLinearWriteSpeed.scala   | 254 -------
 .../scala/unit/kafka/admin/AddPartitionsTest.scala |  61 +-
 .../group/CoordinatorLoaderImplTest.scala          |  27 +-
 .../kafka/integration/KafkaServerTestHarness.scala |   6 +-
 .../kafka/log/remote/RemoteIndexCacheTest.scala    |   4 +-
 .../scala/unit/kafka/metrics/MetricsTest.scala     |   2 +-
 .../server/AbstractApiVersionsRequestTest.scala    |   9 +-
 .../server/AbstractCreateTopicsRequestTest.scala   |   4 -
 .../kafka/server/AbstractMetadataRequestTest.scala |  14 +-
 .../server/ConsumerGroupHeartbeatRequestTest.scala |  91 ++-
 .../kafka/server/ControllerMutationQuotaTest.scala |  15 +-
 .../server/CreateTopicsRequestWithPolicyTest.scala |  18 +-
 .../kafka/server/DeleteTopicsRequestTest.scala     |  93 +--
 ...leteTopicsRequestWithDeletionDisabledTest.scala |   2 +-
 .../kafka/server/DescribeClusterRequestTest.scala  |  11 +-
 .../kafka/server/DynamicConfigChangeTest.scala     | 102 ++-
 .../server/GroupCoordinatorBaseRequestTest.scala   |   3 +-
 .../scala/unit/kafka/server/KafkaApisTest.scala    |   8 +-
 .../kafka/server/KafkaMetricsReporterTest.scala    |   9 +-
 .../server/ReplicaAlterLogDirsThreadTest.scala     |   8 +-
 .../unit/kafka/server/ReplicationQuotasTest.scala  |   4 +-
 .../scala/unit/kafka/server/RequestQuotaTest.scala |   4 +-
 .../unit/kafka/server/ServerShutdownTest.scala     |  12 +-
 .../server/epoch/LeaderEpochIntegrationTest.scala  |   8 +-
 .../unit/kafka/tools/DumpLogSegmentsTest.scala     |   2 +-
 .../scala/unit/kafka/tools/StorageToolTest.scala   |  38 +-
 docker/examples/README.md                          | 131 ++--
 docs/configuration.html                            |  44 +-
 docs/design.html                                   |  23 +-
 docs/implementation.html                           |  39 -
 docs/migration.html                                |  34 -
 docs/ops.html                                      | 482 +-----------
 docs/quickstart.html                               |  31 +-
 docs/security.html                                 | 257 +------
 docs/streams/quickstart.html                       |  28 +-
 docs/toc.html                                      |  37 +-
 docs/upgrade.html                                  |  11 +-
 gradle/dependencies.gradle                         |   5 +-
 .../coordinator/group/GroupCoordinatorConfig.java  |   2 +
 .../coordinator/group/GroupCoordinatorShard.java   |   1 +
 .../coordinator/group/GroupMetadataManager.java    | 382 +++++++++-
 .../group/modern/consumer/ConsumerGroup.java       |  48 +-
 .../modern/consumer/ResolvedRegularExpression.java |   2 +
 .../group/GroupMetadataManagerTest.java            | 525 ++++++++++++-
 .../group/GroupMetadataManagerTestContext.java     |  19 +-
 .../coordinator/group/MetadataImageBuilder.java    |  16 +-
 .../group/OffsetMetadataManagerTest.java           |   3 +
 .../group/modern/consumer/ConsumerGroupTest.java   |  17 +
 .../jmh/consumer/SubscriptionStateBenchmark.java   |   4 +-
 .../jmh/coordinator/RegexResolutionBenchmark.java  | 128 ++++
 .../apache/kafka/jmh/log/TestLinearWriteSpeed.java | 342 +++++++++
 .../kafka/controller/FeatureControlManager.java    |   9 +
 .../apache/kafka/controller/QuorumController.java  |  20 +-
 .../controller/ReplicationControlManager.java      |  18 +-
 .../apache/kafka/metadata/storage/Formatter.java   |  12 +-
 .../QuorumControllerIntegrationTestUtils.java      |  30 +-
 .../kafka/controller/QuorumControllerTest.java     |  21 +-
 .../kafka/controller/QuorumControllerTestEnv.java  |  12 +-
 .../controller/ReplicationControlManagerTest.java  |  14 +-
 .../kafka/metadata/storage/FormatterTest.java      |  68 +-
 ...ion.java => EligibleLeaderReplicasVersion.java} |  26 +-
 .../org/apache/kafka/server/common/Features.java   |   3 +-
 .../kafka/server/config/ServerLogConfigs.java      |   2 +-
 .../apache/kafka/server/config/KRaftConfigs.java   |   4 -
 .../kafka/server/config/ReplicationConfigs.java    |   7 +-
 .../apache/kafka/server/BrokerFeaturesTest.java    |   2 +
 .../log/remote/storage/RemoteLogManagerConfig.java |   4 +-
 .../remote/metadata/storage/ConsumerTaskTest.java  |   4 +-
 .../KStreamRepartitionIntegrationTest.java         |  58 +-
 .../integration/RangeQueryIntegrationTest.java     |  10 +-
 .../TestingMetricsInterceptingAdminClient.java     |   7 -
 .../org/apache/kafka/streams/StreamsBuilder.java   |   8 +-
 .../java/org/apache/kafka/streams/Topology.java    |   8 +-
 .../kstream/internals/InternalStreamsBuilder.java  |   9 +-
 .../streams/kstream/internals/KStreamImpl.java     |   7 +-
 .../streams/kstream/internals/KStreamImplJoin.java |   2 +-
 .../streams/kstream/internals/KTableImpl.java      |   7 +-
 .../streams/kstream/internals/KTableSource.java    |  24 +-
 .../kstream/internals/MaterializedInternal.java    |  11 +-
 .../kstream/internals/graph/GlobalStoreNode.java   |  12 +-
 .../kstream/internals/graph/TableSourceNode.java   |  34 +-
 .../org/apache/kafka/streams/processor/TaskId.java |  24 +-
 .../internals/InternalTopologyBuilder.java         |  54 +-
 .../processor/internals/PartitionGroup.java        |   3 +-
 .../processor/internals/StoreBuilderWrapper.java   |  10 +-
 .../StoreDelegatingProcessorSupplier.java}         |  32 +-
 .../streams/processor/internals/StoreFactory.java  |  76 ++
 .../streams/processor/internals/StreamThread.java  |  37 +-
 .../processor/internals/TopologyMetadata.java      |   4 +-
 .../apache/kafka/streams/StreamsBuilderTest.java   |  79 +-
 .../apache/kafka/streams/StreamsConfigTest.java    |   6 +-
 .../org/apache/kafka/streams/TopologyTest.java     |  13 +-
 ...StreamsThreadMetricsDelegatingReporterTest.java |   4 +-
 .../internals/InternalStreamsBuilderTest.java      |  18 +-
 .../internals/SessionWindowedKStreamImplTest.java  |   6 +-
 .../internals/SlidingWindowedKStreamImplTest.java  |  16 +-
 .../internals/TimeWindowedKStreamImplTest.java     |  12 +-
 .../internals/graph/TableSourceNodeTest.java       |  17 +-
 .../internals/GlobalStateManagerImplTest.java      |  30 +-
 .../internals/GlobalStreamThreadTest.java          |  13 +-
 .../internals/InternalTopologyBuilderTest.java     | 115 +--
 .../processor/internals/PartitionGroupTest.java    |  82 ++
 .../processor/internals/StateConsumerTest.java     |   4 +-
 .../internals/StoreChangelogReaderTest.java        |  14 +-
 .../processor/internals/StreamTaskTest.java        | 106 ++-
 .../processor/internals/StreamThreadTest.java      |  10 +-
 ...ctDualSchemaRocksDBSegmentedBytesStoreTest.java | 833 ++++++++++-----------
 .../state/internals/AbstractKeyValueStoreTest.java |  66 +-
 .../AbstractRocksDBSegmentedBytesStoreTest.java    | 124 +--
 .../internals/AbstractRocksDBWindowStoreTest.java  | 153 ++--
 .../internals/AbstractSessionBytesStoreTest.java   |  58 +-
 .../internals/AbstractWindowBytesStoreTest.java    | 313 ++++----
 .../internals/CachingInMemorySessionStoreTest.java |   8 +-
 .../CachingPersistentSessionStoreTest.java         |   8 +-
 .../CachingPersistentWindowStoreTest.java          |  18 +-
 .../CompositeReadOnlyKeyValueStoreTest.java        |  20 +-
 .../CompositeReadOnlySessionStoreTest.java         |  16 +-
 .../CompositeReadOnlyWindowStoreTest.java          |  40 +-
 .../state/internals/FilteredCacheIteratorTest.java |   6 +-
 .../state/internals/InMemorySessionStoreTest.java  |   6 +-
 .../state/internals/ListValueStoreTest.java        |  10 +-
 .../StreamThreadStateStoreProviderTest.java        |   6 +-
 ...imeOrderedCachingPersistentWindowStoreTest.java |  26 +-
 .../internals/TimeOrderedWindowStoreTest.java      |  26 +-
 .../state/internals/WindowKeySchemaTest.java       |   4 +-
 .../org/apache/kafka/streams/utils/TestUtils.java  |  16 +-
 .../org/apache/kafka/test/MockClientSupplier.java  |   6 +-
 .../kafka/test/MockKeyValueStoreBuilder.java       |   2 +-
 .../org/apache/kafka/test/MockRestoreConsumer.java |   4 +-
 .../org/apache/kafka/test/StreamsTestUtils.java    |  32 +-
 .../apache/kafka/streams/TopologyTestDriver.java   |   6 +-
 .../kafka/common/test/KafkaClusterTestKit.java     |  11 +-
 .../common/test/api/ClusterTestExtensionsTest.java |   8 +
 .../tools/consumer/group/ShareGroupCommand.java    |  18 +-
 .../org/apache/kafka/tools/FeatureCommandTest.java |  23 +-
 .../apache/kafka/tools/StreamsResetterTest.java    |  10 +-
 .../kafka/tools/consumer/ConsoleConsumerTest.java  |   4 +-
 .../SaslClientsWithInvalidCredentialsTest.java     |  38 +-
 232 files changed, 5054 insertions(+), 4331 deletions(-)
 delete mode 100644 clients/src/main/java/org/apache/kafka/clients/admin/ListShareGroupsOptions.java
 delete mode 100644 clients/src/main/java/org/apache/kafka/clients/admin/ListShareGroupsResult.java
 delete mode 100644 clients/src/main/java/org/apache/kafka/clients/admin/ShareGroupListing.java
 create mode 100644 clients/src/main/java/org/apache/kafka/clients/consumer/internals/AutoOffsetResetStrategy.java
 copy clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/{TopicPatternSubscriptionChangeEvent.java => TopicRe2JPatternSubscriptionChangeEvent.java} (53%)
 create mode 100644 clients/src/test/java/org/apache/kafka/clients/consumer/internals/AutoOffsetResetStrategyTest.java
 create mode 100644 coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/MockCoordinatorExecutor.java
 delete mode 100644 core/src/main/scala/kafka/utils/DelayedItem.scala
 delete mode 100755 core/src/test/scala/other/kafka/TestLinearWriteSpeed.scala
 delete mode 100644 docs/migration.html
 create mode 100644 jmh-benchmarks/src/main/java/org/apache/kafka/jmh/coordinator/RegexResolutionBenchmark.java
 create mode 100644 jmh-benchmarks/src/main/java/org/apache/kafka/jmh/log/TestLinearWriteSpeed.java
 copy server-common/src/main/java/org/apache/kafka/server/common/{GroupVersion.java => EligibleLeaderReplicasVersion.java} (69%)
 copy streams/src/main/java/org/apache/kafka/streams/{kstream/internals/PassThrough.java => processor/internals/StoreDelegatingProcessorSupplier.java} (55%)


(kafka) 40/42: KIP1071 trunk rebase 11_25 add streams membership manager stream thread integration (#17968)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit b3eeed7a093e252b4057804dd1e4f25ed516a44d
Author: Bill Bejeck <bb...@apache.org>
AuthorDate: Thu Nov 28 07:39:16 2024 -0500

    KIP1071 trunk rebase 11_25 add streams membership manager stream thread integration (#17968)
    
    Rebase on trunk
---
 .../consumer/internals/AsyncKafkaConsumer.java     |  11 +-
 .../consumer/internals/CommitRequestManager.java   |   2 +-
 .../internals/ConsumerDelegateCreator.java         |   3 +-
 .../consumer/internals/RequestManagers.java        |  70 ++-
 .../internals/StreamsAssignmentInterface.java      | 179 +++++++-
 .../StreamsGroupHeartbeatRequestManager.java       | 103 +----
 .../internals/StreamsMembershipManager.java        | 238 +++++++---
 .../internals/events/ApplicationEvent.java         |   4 +-
 .../events/ApplicationEventProcessor.java          |  76 +++-
 .../consumer/internals/events/BackgroundEvent.java |   3 +-
 ...reamsOnAllTasksLostCallbackCompletedEvent.java} |   8 +-
 ... StreamsOnAllTasksLostCallbackNeededEvent.java} |  21 +-
 ...eamsOnTasksAssignedCallbackCompletedEvent.java} |   8 +-
 ...StreamsOnTasksAssignedCallbackNeededEvent.java} |   6 +-
 ...reamsOnTasksRevokedCallbackCompletedEvent.java} |   8 +-
 ... StreamsOnTasksRevokedCallbackNeededEvent.java} |  18 +-
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  61 ++-
 .../internals/StreamsMembershipManagerTest.java    | 501 ++++++++++++---------
 .../events/ApplicationEventProcessorTest.java      |  85 ++++
 .../coordinator/group/GroupCoordinatorShard.java   |  21 +-
 .../streams/CoordinatorStreamsRecordHelpers.java   |  28 +-
 .../message/ConsumerGroupRegularExpressionKey.json |   4 +-
 .../StreamsGroupCurrentMemberAssignmentKey.json    |   6 +-
 .../message/StreamsGroupMemberMetadataKey.json     |   6 +-
 .../common/message/StreamsGroupMetadataKey.json    |   4 +-
 .../message/StreamsGroupPartitionMetadataKey.json  |   4 +-
 .../StreamsGroupTargetAssignmentMemberKey.json     |   6 +-
 .../StreamsGroupTargetAssignmentMetadataKey.json   |   4 +-
 .../common/message/StreamsGroupTopologyKey.json    |   4 +-
 .../CoordinatorStreamsRecordHelpersTest.java       |   2 +-
 .../streams/processor/internals/StreamThread.java  |  70 ++-
 .../internals/StreamsRebalanceListener.java        |   2 -
 32 files changed, 1014 insertions(+), 552 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
index 459d26c6010..b74dcce64fe 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
@@ -387,7 +387,9 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                     applicationEventProcessorSupplier,
                     networkClientDelegateSupplier,
                     requestManagersSupplier);
-
+            streamsAssignmentInterface.ifPresent(
+                sai -> sai.setApplicationEventHandler(applicationEventHandler)
+            );
             this.rebalanceListenerInvoker = new ConsumerRebalanceListenerInvoker(
                     logContext,
                     subscriptions,
@@ -477,8 +479,7 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                        Deserializer<V> valueDeserializer,
                        KafkaClient client,
                        SubscriptionState subscriptions,
-                       ConsumerMetadata metadata,
-                       Optional<StreamsAssignmentInterface> streamsInstanceMetadata) {
+                       ConsumerMetadata metadata) {
         this.log = logContext.logger(getClass());
         this.subscriptions = subscriptions;
         this.clientId = config.getString(ConsumerConfig.CLIENT_ID_CONFIG);
@@ -546,8 +547,8 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
             clientTelemetryReporter,
             metrics,
             offsetCommitCallbackInvoker,
-            memberStateListener,
-            streamsInstanceMetadata
+            this::updateGroupMetadata,
+            Optional.empty()
         );
         Supplier<ApplicationEventProcessor> applicationEventProcessorSupplier = ApplicationEventProcessor.supplier(
                 logContext,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
index 41522889768..c6e08ad377c 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/CommitRequestManager.java
@@ -96,7 +96,7 @@ public class CommitRequestManager implements RequestManager, MemberStateListener
     private Optional<Integer> lastEpochSentOnCommit;
 
     /**
-     *  The member ID and latest member epoch received via the {@link MemberStateListener#onMemberEpochUpdated(Optional, String)},
+     *  The member ID and latest member epoch received via the {@link MemberStateListener#onMemberEpochUpdated(Optional, Optional)},
      *  to be included in the OffsetFetch and OffsetCommit requests. This will have
      *  the latest memberEpoch received from the broker.
      */
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
index 3f5926080fc..d4ded4377b2 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
@@ -92,8 +92,7 @@ public class ConsumerDelegateCreator {
                     valueDeserializer,
                     client,
                     subscriptions,
-                    metadata,
-                    Optional.empty()
+                    metadata
                 );
             else
                 return new ClassicKafkaConsumer<>(
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 4058bd72725..919615774cc 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -54,6 +54,7 @@ public class RequestManagers implements Closeable {
     public final Optional<ShareHeartbeatRequestManager> shareHeartbeatRequestManager;
     public final Optional<ConsumerMembershipManager> consumerMembershipManager;
     public final Optional<ShareMembershipManager> shareMembershipManager;
+    public final Optional<StreamsMembershipManager> streamsMembershipManager;
     public final OffsetsRequestManager offsetsRequestManager;
     public final TopicMetadataRequestManager topicMetadataRequestManager;
     public final FetchRequestManager fetchRequestManager;
@@ -70,7 +71,8 @@ public class RequestManagers implements Closeable {
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
                            Optional<ConsumerMembershipManager> membershipManager,
-                           Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager) {
+                           Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager,
+                           Optional<StreamsMembershipManager> streamsMembershipManager) {
         this.log = logContext.logger(RequestManagers.class);
         this.offsetsRequestManager = requireNonNull(offsetsRequestManager, "OffsetsRequestManager cannot be null");
         this.coordinatorRequestManager = coordinatorRequestManager;
@@ -83,6 +85,7 @@ public class RequestManagers implements Closeable {
         this.consumerMembershipManager = membershipManager;
         this.shareMembershipManager = Optional.empty();
         this.streamsGroupHeartbeatRequestManager = streamsGroupHeartbeatRequestManager;
+        this.streamsMembershipManager = streamsMembershipManager;
 
         List<Optional<? extends RequestManager>> list = new ArrayList<>();
         list.add(coordinatorRequestManager);
@@ -93,6 +96,7 @@ public class RequestManagers implements Closeable {
         list.add(Optional.of(topicMetadataRequestManager));
         list.add(Optional.of(fetchRequestManager));
         list.add(streamsGroupHeartbeatRequestManager);
+        list.add(streamsMembershipManager);
         entries = Collections.unmodifiableList(list);
     }
 
@@ -110,6 +114,7 @@ public class RequestManagers implements Closeable {
         this.consumerMembershipManager = Optional.empty();
         this.shareMembershipManager = shareMembershipManager;
         this.streamsGroupHeartbeatRequestManager = Optional.empty();
+        this.streamsMembershipManager = Optional.empty();
         this.offsetsRequestManager = null;
         this.topicMetadataRequestManager = null;
         this.fetchRequestManager = null;
@@ -194,6 +199,7 @@ public class RequestManagers implements Closeable {
                 CoordinatorRequestManager coordinator = null;
                 CommitRequestManager commitRequestManager = null;
                 StreamsGroupHeartbeatRequestManager streamsGroupHeartbeatRequestManager = null;
+                StreamsMembershipManager streamsMembershipManager = null;
 
                 if (groupRebalanceConfig != null && groupRebalanceConfig.groupId != null) {
                     Optional<String> serverAssignor = Optional.ofNullable(config.getString(ConsumerConfig.GROUP_REMOTE_ASSIGNOR_CONFIG));
@@ -214,43 +220,57 @@ public class RequestManagers implements Closeable {
                             groupRebalanceConfig.groupInstanceId,
                             metrics,
                             metadata);
-                    membershipManager = new ConsumerMembershipManager(
+
+                    if (streamsInstanceMetadata.isPresent()) {
+                        streamsMembershipManager = new StreamsMembershipManager(
                             groupRebalanceConfig.groupId,
-                            groupRebalanceConfig.groupInstanceId,
-                            groupRebalanceConfig.rebalanceTimeoutMs,
-                            serverAssignor,
+                            streamsInstanceMetadata.get(),
                             subscriptions,
-                            commitRequestManager,
-                            metadata,
                             logContext,
-                            backgroundEventHandler,
                             time,
                             metrics);
+                        streamsMembershipManager.registerStateListener(commitRequestManager);
+                        streamsMembershipManager.registerStateListener(applicationThreadMemberStateListener);
 
-                    // Update the group member ID label in the client telemetry reporter.
-                    // According to KIP-1082, the consumer will generate the member ID as the incarnation ID of the process.
-                    // Therefore, we can update the group member ID during initialization.
-                    if (clientTelemetryReporter.isPresent()) {
-                        clientTelemetryReporter.get()
-                            .updateMetricsLabels(Map.of(ClientTelemetryProvider.GROUP_MEMBER_ID, membershipManager.memberId()));
-                    }
-
-                    membershipManager.registerStateListener(commitRequestManager);
-                    membershipManager.registerStateListener(applicationThreadMemberStateListener);
+                        if (clientTelemetryReporter.isPresent()) {
+                            clientTelemetryReporter.get()
+                                .updateMetricsLabels(Map.of(ClientTelemetryProvider.GROUP_MEMBER_ID, streamsMembershipManager.memberId()));
+                        }
 
-                    if (streamsInstanceMetadata.isPresent()) {
                         streamsGroupHeartbeatRequestManager = new StreamsGroupHeartbeatRequestManager(
                             logContext,
                             time,
                             config,
                             coordinator,
-                            membershipManager,
+                            streamsMembershipManager,
                             backgroundEventHandler,
                             metrics,
-                            streamsInstanceMetadata.get(),
-                            metadata
-                            );
+                            streamsInstanceMetadata.get()
+                        );
                     } else {
+                        membershipManager = new ConsumerMembershipManager(
+                            groupRebalanceConfig.groupId,
+                            groupRebalanceConfig.groupInstanceId,
+                            groupRebalanceConfig.rebalanceTimeoutMs,
+                            serverAssignor,
+                            subscriptions,
+                            commitRequestManager,
+                            metadata,
+                            logContext,
+                            backgroundEventHandler,
+                            time,
+                            metrics);
+
+                        // Update the group member ID label in the client telemetry reporter.
+                        // According to KIP-1082, the consumer will generate the member ID as the incarnation ID of the process.
+                        // Therefore, we can update the group member ID during initialization.
+                        if (clientTelemetryReporter.isPresent()) {
+                            clientTelemetryReporter.get()
+                                .updateMetricsLabels(Map.of(ClientTelemetryProvider.GROUP_MEMBER_ID, membershipManager.memberId()));
+                        }
+
+                        membershipManager.registerStateListener(commitRequestManager);
+                        membershipManager.registerStateListener(applicationThreadMemberStateListener);
                         heartbeatRequestManager = new ConsumerHeartbeatRequestManager(
                             logContext,
                             time,
@@ -260,6 +280,7 @@ public class RequestManagers implements Closeable {
                             membershipManager,
                             backgroundEventHandler,
                             metrics);
+
                     }
                 }
 
@@ -284,7 +305,8 @@ public class RequestManagers implements Closeable {
                         Optional.ofNullable(commitRequestManager),
                         Optional.ofNullable(heartbeatRequestManager),
                         Optional.ofNullable(membershipManager),
-                        Optional.ofNullable(streamsGroupHeartbeatRequestManager)
+                        Optional.ofNullable(streamsGroupHeartbeatRequestManager),
+                        Optional.ofNullable(streamsMembershipManager)
                 );
             }
         };
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index de6cb9e2098..8bafa619627 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -16,20 +16,37 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
+import org.apache.kafka.clients.consumer.internals.events.ApplicationEventHandler;
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEvent;
+import org.apache.kafka.clients.consumer.internals.events.ErrorEvent;
+import org.apache.kafka.clients.consumer.internals.events.EventProcessor;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAllTasksLostCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAllTasksLostCallbackNeededEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksAssignedCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksAssignedCallbackNeededEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksRevokedCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksRevokedCallbackNeededEvent;
+import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.TopicPartition;
 
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.function.Supplier;
 
 /**
  * Defines a self-contained object to exchange assignment-related metadata with the Kafka Streams instance.
@@ -128,6 +145,8 @@ public class StreamsAssignmentInterface {
 
     public static class Assignment {
 
+        public static final Assignment EMPTY = new Assignment();
+
         public final Set<TaskId> activeTasks = new HashSet<>();
 
         public final Set<TaskId> standbyTasks = new HashSet<>();
@@ -281,17 +300,173 @@ public class StreamsAssignmentInterface {
         }
     }
 
+    private final BlockingQueue<BackgroundEvent> onCallbackRequests = new LinkedBlockingQueue<>();
+
+    private ApplicationEventHandler applicationEventHandler = null;
+
+    private Optional<Function<Set<StreamsAssignmentInterface.TaskId>, Optional<Exception>>> onTasksRevokedCallback = null;
+    private Optional<Function<Assignment, Optional<Exception>>> onTasksAssignedCallback = null;
+    private Optional<Supplier<Optional<Exception>>> onAllTasksLostCallback = null;
+
+    private final StreamsRebalanceEventProcessor streamsRebalanceEventProcessor;
+
+    private class StreamsRebalanceEventProcessor implements EventProcessor<BackgroundEvent> {
+
+        @Override
+        public void process(final BackgroundEvent event) {
+            switch (event.type()) {
+                case ERROR:
+                    process((ErrorEvent) event);
+                    break;
+
+                case STREAMS_ON_TASKS_REVOKED_CALLBACK_NEEDED:
+                    process((StreamsOnTasksRevokedCallbackNeededEvent) event);
+                    break;
+
+                case STREAMS_ON_TASKS_ASSIGNED_CALLBACK_NEEDED:
+                    process((StreamsOnTasksAssignedCallbackNeededEvent) event);
+                    break;
+
+                case STREAMS_ON_ALL_TASKS_LOST_CALLBACK_NEEDED:
+                    process((StreamsOnAllTasksLostCallbackNeededEvent) event);
+                    break;
+
+                default:
+                    throw new IllegalArgumentException("Background event type " + event.type() + " was not expected");
+
+            }
+        }
+
+        private void process(final ErrorEvent event) {
+            throw event.error();
+        }
+
+        private void process(final StreamsOnTasksRevokedCallbackNeededEvent event) {
+            StreamsOnTasksRevokedCallbackCompletedEvent invokedEvent = invokeOnTasksRevokedCallback(event.activeTasksToRevoke(), event.future());
+            applicationEventHandler.add(invokedEvent);
+            if (invokedEvent.error().isPresent()) {
+                throw invokedEvent.error().get();
+            }
+        }
+
+        private void process(final StreamsOnTasksAssignedCallbackNeededEvent event) {
+            StreamsOnTasksAssignedCallbackCompletedEvent invokedEvent = invokeOnTasksAssignedCallback(event.assignment(), event.future());
+            applicationEventHandler.add(invokedEvent);
+            if (invokedEvent.error().isPresent()) {
+                throw invokedEvent.error().get();
+            }
+        }
+
+        private void process(final StreamsOnAllTasksLostCallbackNeededEvent event) {
+            StreamsOnAllTasksLostCallbackCompletedEvent invokedEvent = invokeOnAllTasksLostCallback(event.future());
+            applicationEventHandler.add(invokedEvent);
+            if (invokedEvent.error().isPresent()) {
+                throw invokedEvent.error().get();
+            }
+        }
+
+        private StreamsOnTasksRevokedCallbackCompletedEvent invokeOnTasksRevokedCallback(final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke,
+                                                                                          final CompletableFuture<Void> future) {
+            final Optional<Exception> exceptionFromCallback = onTasksRevokedCallback
+                .orElseThrow(() -> new IllegalStateException("No tasks assignment callback set!")).apply(activeTasksToRevoke);
+
+            return exceptionFromCallback
+                .map(exception ->
+                    new StreamsOnTasksRevokedCallbackCompletedEvent(
+                        future,
+                        Optional.of(ConsumerUtils.maybeWrapAsKafkaException(exception, "Task revocation callback throws an error"))
+                    ))
+                .orElseGet(() -> new StreamsOnTasksRevokedCallbackCompletedEvent(future, Optional.empty()));
+        }
+
+        private StreamsOnTasksAssignedCallbackCompletedEvent invokeOnTasksAssignedCallback(final StreamsAssignmentInterface.Assignment assignment,
+                                                                                           final CompletableFuture<Void> future) {
+            Optional<KafkaException> error = Optional.empty();
+            // ToDo: Can we avoid the following check?
+            if (!assignment.equals(reconciledAssignment.get())) {
+
+                final Optional<Exception> exceptionFromCallback = onTasksAssignedCallback
+                    .orElseThrow(() -> new IllegalStateException("No tasks assignment callback set!")).apply(assignment);
+
+                if (exceptionFromCallback.isPresent()) {
+                    error = Optional.of(ConsumerUtils.maybeWrapAsKafkaException(exceptionFromCallback.get(), "Task assignment callback throws an error"));
+                } else {
+                    reconciledAssignment.set(assignment);
+                }
+            }
+            return new StreamsOnTasksAssignedCallbackCompletedEvent(future, error);
+        }
+
+        private StreamsOnAllTasksLostCallbackCompletedEvent invokeOnAllTasksLostCallback(final CompletableFuture<Void> future) {
+            final Optional<Exception> exceptionFromCallback = onAllTasksLostCallback
+                .orElseThrow(() -> new IllegalStateException("No tasks assignment callback set!")).get();
+
+            final Optional<KafkaException> error;
+
+            if (exceptionFromCallback.isPresent()) {
+                error = Optional.of(ConsumerUtils.maybeWrapAsKafkaException(exceptionFromCallback.get(), "Task assignment callback throws an error"));
+            } else {
+                error = Optional.empty();
+                reconciledAssignment.set(Assignment.EMPTY);
+            }
+
+            return new StreamsOnAllTasksLostCallbackCompletedEvent(future, error);
+        }
+    }
+
     public StreamsAssignmentInterface(UUID processId,
                                       Optional<HostInfo> endpoint,
                                       Map<String, Subtopology> subtopologyMap,
-                                      Map<String, String> clientTags
-    ) {
+                                      Map<String, String> clientTags) {
         this.processId = processId;
         this.endpoint = endpoint;
         this.subtopologyMap = subtopologyMap;
         this.taskLags = new HashMap<>();
         this.shutdownRequested = new AtomicBoolean(false);
         this.clientTags = clientTags;
+        this.streamsRebalanceEventProcessor = new StreamsRebalanceEventProcessor();
+    }
+
+    public void setOnTasksRevokedCallback(final Function<Set<StreamsAssignmentInterface.TaskId>, Optional<Exception>> onTasksRevokedCallback) {
+        this.onTasksRevokedCallback = Optional.ofNullable(onTasksRevokedCallback);
+    }
+
+    public void setOnTasksAssignedCallback(final Function<Assignment, Optional<Exception>> onTasksAssignedCallback) {
+        this.onTasksAssignedCallback = Optional.ofNullable(onTasksAssignedCallback);
+    }
+
+    public void setOnAllTasksLostCallback(final Supplier<Optional<Exception>> onAllTasksLostCallback) {
+        this.onAllTasksLostCallback = Optional.ofNullable(onAllTasksLostCallback);
+    }
+
+    public void setApplicationEventHandler(final ApplicationEventHandler applicationEventHandler) {
+        this.applicationEventHandler = applicationEventHandler;
+    }
+
+    public CompletableFuture<Void> requestOnTasksAssignedCallbackInvocation(final Assignment assignment) {
+        final StreamsOnTasksAssignedCallbackNeededEvent onTasksAssignedCallbackNeededEvent = new StreamsOnTasksAssignedCallbackNeededEvent(assignment);
+        onCallbackRequests.add(onTasksAssignedCallbackNeededEvent);
+        return onTasksAssignedCallbackNeededEvent.future();
+    }
+
+    public CompletableFuture<Void> requestOnTasksRevokedCallbackInvocation(final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke) {
+        final StreamsOnTasksRevokedCallbackNeededEvent onTasksRevokedCallbackNeededEvent = new StreamsOnTasksRevokedCallbackNeededEvent(activeTasksToRevoke);
+        onCallbackRequests.add(onTasksRevokedCallbackNeededEvent);
+        return onTasksRevokedCallbackNeededEvent.future();
+    }
+
+    public CompletableFuture<Void> requestOnAllTasksLostCallbackInvocation() {
+        final StreamsOnAllTasksLostCallbackNeededEvent onAllTasksLostCallbackNeededEvent = new StreamsOnAllTasksLostCallbackNeededEvent();
+        onCallbackRequests.add(onAllTasksLostCallbackNeededEvent);
+        return onAllTasksLostCallbackNeededEvent.future();
+    }
+
+    public void processStreamsRebalanceEvents() {
+        LinkedList<BackgroundEvent> events = new LinkedList<>();
+        onCallbackRequests.drainTo(events);
+        for (BackgroundEvent event : events) {
+            streamsRebalanceEventProcessor.process(event);
+        }
     }
 
     @Override
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 7506a497939..f435b1cd21b 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -23,11 +23,8 @@ import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler
 import org.apache.kafka.clients.consumer.internals.events.ErrorEvent;
 import org.apache.kafka.clients.consumer.internals.metrics.HeartbeatMetricsManager;
 import org.apache.kafka.common.TopicPartition;
-import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.GroupAuthorizationException;
 import org.apache.kafka.common.errors.RetriableException;
-import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.CopartitionGroup;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskIds;
@@ -35,7 +32,6 @@ import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData.Endpoint;
 import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.common.requests.ConsumerGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.utils.LogContext;
@@ -51,11 +47,9 @@ import java.util.Comparator;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
-import java.util.stream.Stream;
 
 public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
@@ -69,7 +63,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final StreamsGroupHeartbeatRequestManager.HeartbeatState heartbeatState;
 
-    private final ConsumerMembershipManager membershipManager;
+    private final StreamsMembershipManager membershipManager;
 
     private final BackgroundEventHandler backgroundEventHandler;
 
@@ -79,20 +73,15 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private StreamsAssignmentInterface streamsInterface;
 
-    private final Map<String, Uuid> assignedTopicIdCache;
-
-    private final ConsumerMetadata metadata;
-
     public StreamsGroupHeartbeatRequestManager(
         final LogContext logContext,
         final Time time,
         final ConsumerConfig config,
         final CoordinatorRequestManager coordinatorRequestManager,
-        final ConsumerMembershipManager membershipManager,
+        final StreamsMembershipManager membershipManager,
         final BackgroundEventHandler backgroundEventHandler,
         final Metrics metrics,
-        final StreamsAssignmentInterface streamsAssignmentInterface,
-        final ConsumerMetadata metadata
+        final StreamsAssignmentInterface streamsAssignmentInterface
     ) {
         this.coordinatorRequestManager = coordinatorRequestManager;
         this.logger = logContext.logger(getClass());
@@ -108,14 +97,12 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         this.pollTimer = time.timer(maxPollIntervalMs);
         this.metricsManager = new HeartbeatMetricsManager(metrics);
         this.streamsInterface = streamsAssignmentInterface;
-        this.assignedTopicIdCache = new HashMap<>();
-        this.metadata = metadata;
     }
 
     @Override
     public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
         if (!coordinatorRequestManager.coordinator().isPresent() || membershipManager.shouldSkipHeartbeat()) {
-            membershipManager.onHeartbeatRequestSkipped();
+            membershipManager.transitionToUnsubscribeIfLeaving();
             return NetworkClientDelegate.PollResult.EMPTY;
         }
         pollTimer.update(currentTimeMs);
@@ -126,7 +113,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 "messages. You can address this either by increasing max.poll.interval.ms or by " +
                 "reducing the maximum size of batches returned in poll() with max.poll.records.");
 
-            membershipManager.transitionToSendingLeaveGroup(true);
+            membershipManager.onPollTimerExpired();
             NetworkClientDelegate.UnsentRequest leaveHeartbeat = makeHeartbeatRequest(currentTimeMs, true);
 
             // We can ignore the leave response because we can join before or after receiving the response.
@@ -145,7 +132,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         return new NetworkClientDelegate.PollResult(heartbeatRequestState.heartbeatIntervalMs, Collections.singletonList(request));
     }
 
-    public ConsumerMembershipManager membershipManager() {
+    public StreamsMembershipManager membershipManager() {
         return membershipManager;
     }
 
@@ -252,14 +239,6 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             streamsInterface.partitionsByHost.set(convertHostInfoMap(data));
         }
 
-        ConsumerGroupHeartbeatResponseData cgData = new ConsumerGroupHeartbeatResponseData();
-        cgData.setMemberId(data.memberId());
-        cgData.setMemberEpoch(data.memberEpoch());
-        cgData.setErrorCode(data.errorCode());
-        cgData.setErrorMessage(data.errorMessage());
-        cgData.setThrottleTimeMs(data.throttleTimeMs());
-        cgData.setHeartbeatIntervalMs(data.heartbeatIntervalMs());
-
         List<StreamsGroupHeartbeatResponseData.Status> statuses = data.status();
 
         if (statuses != null && !statuses.isEmpty()) {
@@ -269,54 +248,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             logger.warn("Membership is in the following statuses: {}.", statusDetails);
         }
 
-        if (data.activeTasks() != null && data.standbyTasks() != null && data.warmupTasks() != null) {
-
-            setTargetAssignment(data);
-            setTargetAssignmentForConsumerGroup(data, cgData);
-
-        } else {
-            if (data.activeTasks() != null || data.standbyTasks() != null || data.warmupTasks() != null) {
-                throw new IllegalStateException("Invalid response data, task collections must be all null or all non-null: " + data);
-            }
-        }
-
-        membershipManager.onHeartbeatSuccess(new ConsumerGroupHeartbeatResponse(cgData));
-    }
-
-    private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data,
-                                                     final ConsumerGroupHeartbeatResponseData cgData) {
-        Map<String, TopicPartitions> tps = new HashMap<>();
-        data.activeTasks().forEach(taskId -> Stream.concat(
-                streamsInterface.subtopologyMap().get(taskId.subtopologyId()).sourceTopics.stream(),
-                streamsInterface.subtopologyMap().get(taskId.subtopologyId()).repartitionSourceTopics.keySet().stream()
-            )
-            .forEach(topic -> {
-                final TopicPartitions toInsert = tps.computeIfAbsent(topic, k -> {
-                    final Optional<Uuid> uuid = findTopicIdInGlobalOrLocalCache(topic);
-                    if (uuid.isPresent()) {
-                        TopicPartitions t =
-                            new TopicPartitions();
-                        t.setTopicId(uuid.get());
-                        return t;
-                    } else {
-                        return null;
-                    }
-                });
-                if (toInsert != null) {
-                    toInsert.partitions().addAll(taskId.partitions());
-                }
-            }));
-        ConsumerGroupHeartbeatResponseData.Assignment cgAssignment = new ConsumerGroupHeartbeatResponseData.Assignment();
-        cgAssignment.setTopicPartitions(new ArrayList<>(tps.values()));
-        cgData.setAssignment(cgAssignment);
-    }
-
-    private void setTargetAssignment(final StreamsGroupHeartbeatResponseData data) {
-        Assignment targetAssignment = new Assignment();
-        updateTaskIdCollection(data.activeTasks(), targetAssignment.activeTasks);
-        updateTaskIdCollection(data.standbyTasks(), targetAssignment.standbyTasks);
-        updateTaskIdCollection(data.warmupTasks(), targetAssignment.warmupTasks);
-        streamsInterface.targetAssignment.set(targetAssignment);
+        membershipManager.onHeartbeatSuccess(response);
     }
 
     private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(
@@ -410,7 +342,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 message = String.format("StreamsGroupHeartbeatRequest failed for member %s because epoch %s is fenced.",
                     membershipManager.memberId(), membershipManager.memberEpoch());
                 logInfo(message, response, currentTimeMs);
-                membershipManager.transitionToFenced();
+                membershipManager.onFenced();
                 // Skip backoff so that a next HB to rejoin is sent as soon as the fenced member releases its assignment
                 heartbeatRequestState.reset();
                 break;
@@ -419,7 +351,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 message = String.format("StreamsGroupHeartbeatRequest failed because member %s is unknown.",
                     membershipManager.memberId());
                 logInfo(message, response, currentTimeMs);
-                membershipManager.transitionToFenced();
+                membershipManager.onFenced();
                 // Skip backoff so that a next HB to rejoin is sent as soon as the fenced member releases its assignment
                 heartbeatRequestState.reset();
                 break;
@@ -507,22 +439,9 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         }
     }
 
-    private Optional<Uuid> findTopicIdInGlobalOrLocalCache(String topicName) {
-        Uuid idFromMetadataCache = metadata.topicIds().getOrDefault(topicName, null);
-        if (idFromMetadataCache != null) {
-            // Add topic name to local cache, so it can be reused if included in a next target
-            // assignment if metadata cache not available.
-            assignedTopicIdCache.put(topicName, idFromMetadataCache);
-            return Optional.of(idFromMetadataCache);
-        } else {
-            Uuid idFromLocalCache = assignedTopicIdCache.getOrDefault(topicName, null);
-            return Optional.ofNullable(idFromLocalCache);
-        }
-    }
-
     static class HeartbeatState {
 
-        private final ConsumerMembershipManager membershipManager;
+        private final StreamsMembershipManager membershipManager;
         private final int rebalanceTimeoutMs;
         private final StreamsGroupHeartbeatRequestManager.HeartbeatState.SentFields sentFields;
 
@@ -533,7 +452,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
         public HeartbeatState(
             final StreamsAssignmentInterface streamsInterface,
-            final ConsumerMembershipManager membershipManager,
+            final StreamsMembershipManager membershipManager,
             final int rebalanceTimeoutMs) {
 
             this.membershipManager = membershipManager;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
index fb34f50847b..a3f55c92d3a 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
@@ -16,9 +16,9 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
-import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
-import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackCompletedEvent;
-import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackNeededEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAllTasksLostCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksAssignedCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksRevokedCallbackCompletedEvent;
 import org.apache.kafka.clients.consumer.internals.metrics.ConsumerRebalanceMetricsManager;
 import org.apache.kafka.clients.consumer.internals.metrics.RebalanceMetricsManager;
 import org.apache.kafka.common.KafkaException;
@@ -28,13 +28,12 @@ import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
-import org.apache.kafka.common.telemetry.internals.ClientTelemetryProvider;
-import org.apache.kafka.common.telemetry.internals.ClientTelemetryReporter;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
 
 import org.slf4j.Logger;
 
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -145,8 +144,6 @@ public class StreamsMembershipManager implements RequestManager {
 
     private final SubscriptionState subscriptionState;
 
-    private final BackgroundEventHandler backgroundEventHandler;
-
     private MemberState state;
 
     private final String groupId;
@@ -165,7 +162,7 @@ public class StreamsMembershipManager implements RequestManager {
 
     private boolean rejoinedWhileReconciliationInProgress;
 
-    private final Optional<ClientTelemetryReporter> clientTelemetryReporter;
+    private final List<MemberStateListener> stateUpdatesListeners = new ArrayList<>();
 
     private LocalAssignment targetAssignment = LocalAssignment.NONE;
 
@@ -183,8 +180,6 @@ public class StreamsMembershipManager implements RequestManager {
                                     final StreamsAssignmentInterface streamsAssignmentInterface,
                                     final SubscriptionState subscriptionState,
                                     final LogContext logContext,
-                                    final Optional<ClientTelemetryReporter> clientTelemetryReporter,
-                                    final BackgroundEventHandler backgroundEventHandler,
                                     final Time time,
                                     final Metrics metrics) {
         log = logContext.logger(StreamsMembershipManager.class);
@@ -192,8 +187,6 @@ public class StreamsMembershipManager implements RequestManager {
         this.groupId = groupId;
         this.streamsAssignmentInterface = streamsAssignmentInterface;
         this.subscriptionState = subscriptionState;
-        this.clientTelemetryReporter = clientTelemetryReporter;
-        this.backgroundEventHandler = backgroundEventHandler;
         metricsManager = new ConsumerRebalanceMetricsManager(metrics);
         this.time = time;
     }
@@ -231,6 +224,14 @@ public class StreamsMembershipManager implements RequestManager {
             state == MemberState.STALE;
     }
 
+    public void registerStateListener(MemberStateListener listener) {
+        stateUpdatesListeners.add(Objects.requireNonNull(listener, "State updates listener cannot be null"));
+    }
+
+    void notifyEpochChange(Optional<Integer> epoch) {
+        stateUpdatesListeners.forEach(stateListener -> stateListener.onMemberEpochUpdated(epoch, memberId));
+    }
+
     private void transitionToJoining() {
         if (state == MemberState.FATAL) {
             log.warn("No action taken to join the group with the updated subscription because " +
@@ -276,8 +277,9 @@ public class StreamsMembershipManager implements RequestManager {
     private void transitionToStale() {
         transitionTo(MemberState.STALE);
 
-        CompletableFuture<Void> onAllTasksRevokedDone = invokeRevokingAllTasksCallback();
-        staleMemberAssignmentRelease = onAllTasksRevokedDone.whenComplete((result, error) -> {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecution =
+            streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation();
+        staleMemberAssignmentRelease = onAllTasksLostCallbackExecution.whenComplete((result, error) -> {
             if (error != null) {
                 log.error("Task revocation callback invocation failed " +
                     "after member left group due to expired poll timer.", error);
@@ -293,6 +295,7 @@ public class StreamsMembershipManager implements RequestManager {
         MemberState previousState = state;
         transitionTo(MemberState.FATAL);
         log.error("Member {} with epoch {} transitioned to fatal state", memberIdInfoForLog(), memberEpoch);
+        notifyEpochChange(Optional.empty());
 
         if (previousState == MemberState.UNSUBSCRIBED) {
             log.debug("Member {} with epoch {} got fatal error from the broker but it already " +
@@ -308,8 +311,8 @@ public class StreamsMembershipManager implements RequestManager {
             return;
         }
 
-        CompletableFuture<Void> callbackResult = invokeRevokingAllTasksCallback();
-        callbackResult.whenComplete((result, error) -> {
+        CompletableFuture<Void> onAllTasksLostCallbackExecuted = streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation();
+        onAllTasksLostCallbackExecuted.whenComplete((result, error) -> {
             if (error != null) {
                 log.error("onTaskAssignment callback invocation failed while releasing assignment" +
                     "after member failed with fatal error.", error);
@@ -359,7 +362,15 @@ public class StreamsMembershipManager implements RequestManager {
     }
 
     private void updateMemberEpoch(int newEpoch) {
-        memberEpoch = newEpoch;
+        boolean newEpochReceived = this.memberEpoch != newEpoch;
+        this.memberEpoch = newEpoch;
+        if (newEpochReceived) {
+            if (memberEpoch > 0) {
+                notifyEpochChange(Optional.of(memberEpoch));
+            } else {
+                notifyEpochChange(Optional.empty());
+            }
+        }
     }
 
     private void clearPendingTaskAssignment() {
@@ -434,15 +445,6 @@ public class StreamsMembershipManager implements RequestManager {
             return;
         }
 
-        // Update the group member id label in the client telemetry reporter if the member id has
-        // changed. Initially the member id is empty, and it is updated when the member joins the
-        // group. This is done here to avoid updating the label on every heartbeat response. Also
-        // check if the member id is null, as the schema defines it as nullable.
-        if (responseData.memberId() != null && !responseData.memberId().equals(memberId)) {
-            clientTelemetryReporter.ifPresent(reporter -> reporter.updateMetricsLabels(
-                Collections.singletonMap(ClientTelemetryProvider.GROUP_MEMBER_ID, responseData.memberId())));
-        }
-
         memberId = responseData.memberId();
         updateMemberEpoch(responseData.memberEpoch());
 
@@ -519,17 +521,17 @@ public class StreamsMembershipManager implements RequestManager {
         log.debug("Member {} with epoch {} transitioned to {} state. It will release its " +
             "assignment and rejoin the group.", memberIdInfoForLog(), memberEpoch, MemberState.FENCED);
 
-        CompletableFuture<Void> callbackResult = invokeRevokingAllTasksCallback();
+        CompletableFuture<Void> callbackResult = streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation();
         callbackResult.whenComplete((result, error) -> {
             if (error != null) {
-                log.error("onTaskAssignment callback invocation failed while releasing assignment" +
+                log.error("onAllTasksLost callback invocation failed while releasing assignment" +
                     " after member got fenced. Member will rejoin the group anyways.", error);
             }
             clearTaskAndPartitionAssignment();
             if (state == MemberState.FENCED) {
                 transitionToJoining();
             } else {
-                log.debug("Fenced member onTaskAssignment callback completed but the state has " +
+                log.debug("Fenced member onAllTasksLost callback completed but the state has " +
                     "already changed to {}, so the member won't rejoin the group", state);
             }
         });
@@ -615,15 +617,19 @@ public class StreamsMembershipManager implements RequestManager {
 
         CompletableFuture<Void> onGroupLeft = new CompletableFuture<>();
         leaveGroupInProgress = Optional.of(onGroupLeft);
-        CompletableFuture<Void> onAllTasksRevokedDone = prepareLeaving();
-        onAllTasksRevokedDone.whenComplete((__, callbackError) -> leaving(callbackError));
+        CompletableFuture<Void> onAllTasksRevokedCallbackExecuted = prepareLeaving();
+        onAllTasksRevokedCallbackExecuted.whenComplete((__, callbackError) -> leaving(callbackError));
 
         return onGroupLeft;
     }
 
     private CompletableFuture<Void> prepareLeaving() {
         transitionTo(MemberState.PREPARE_LEAVING);
-        return invokeRevokingAllTasksCallback();
+        if (memberEpoch > 0) {
+            return revokeActiveTasks(toTaskIdSet(currentAssignment.activeTasks));
+        } else {
+            return releaseLostActiveTasks();
+        }
     }
 
     private void leaving(Throwable callbackError) {
@@ -636,8 +642,8 @@ public class StreamsMembershipManager implements RequestManager {
                     "to clear its assignment and send a leave group heartbeat",
                 memberIdInfoForLog());
         }
-        subscriptionState.unsubscribe();
         clearTaskAndPartitionAssignment();
+        subscriptionState.unsubscribe();
         transitionToSendingLeaveGroup(false);
     }
 
@@ -709,41 +715,54 @@ public class StreamsMembershipManager implements RequestManager {
 
         // ToDo: add standby and warmup tasks
         SortedSet<StreamsAssignmentInterface.TaskId> assignedActiveTasks = toTaskIdSet(targetAssignment.activeTasks);
+        SortedSet<StreamsAssignmentInterface.TaskId> ownedActiveTasks = toTaskIdSet(currentAssignment.activeTasks);
+        SortedSet<StreamsAssignmentInterface.TaskId> activeTasksToRevoke = new TreeSet<>(ownedActiveTasks);
+        activeTasksToRevoke.removeAll(assignedActiveTasks);
 
         log.info("Assigned tasks with local epoch {}\n" +
                 "\tMember:                        {}\n" +
-                "\tActive tasks:                  {}\n",
+                "\tAssigned active tasks:         {}\n" +
+                "\tOwned active tasks:            {}\n" +
+                "\tActive tasks to revoke:        {}\n",
             targetAssignment.localEpoch,
             memberIdInfoForLog(),
-            assignedActiveTasks
+            assignedActiveTasks,
+            ownedActiveTasks,
+            activeTasksToRevoke
         );
 
-        SortedSet<TopicPartition> ownedTopicPartitions = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
-        ownedTopicPartitions.addAll(subscriptionState.assignedPartitions());
+        SortedSet<TopicPartition> ownedTopicPartitionsFromSubscriptionState = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
+        ownedTopicPartitionsFromSubscriptionState.addAll(subscriptionState.assignedPartitions());
+        SortedSet<TopicPartition> ownedTopicPartitionsFromAssignedTasks =
+            topicPartitionsForActiveTasks(currentAssignment.activeTasks);
+        if (!ownedTopicPartitionsFromAssignedTasks.equals(ownedTopicPartitionsFromSubscriptionState)) {
+            throw new IllegalStateException("Owned partitions from subscription state and owned partitions from " +
+                "assigned active tasks are not equal. " +
+                "Owned partitions from subscription state: " + ownedTopicPartitionsFromSubscriptionState + ", " +
+                "Owned partitions from assigned active tasks: " + ownedTopicPartitionsFromAssignedTasks);
+        }
         SortedSet<TopicPartition> assignedTopicPartitions = topicPartitionsForActiveTasks(targetAssignment.activeTasks);
         SortedSet<TopicPartition> assignedTopicPartitionsNotPreviouslyOwned =
-            assignedTopicPartitionsNotPreviouslyOwned(assignedTopicPartitions, ownedTopicPartitions);
+            partitionsToAssignNotPreviouslyOwned(assignedTopicPartitions, ownedTopicPartitionsFromSubscriptionState);
+        SortedSet<TopicPartition> partitionsToRevoke = new TreeSet<>(ownedTopicPartitionsFromSubscriptionState);
+        partitionsToRevoke.removeAll(assignedTopicPartitions);
 
-        subscriptionState.assignFromSubscribedAwaitingCallback(
-            assignedTopicPartitions,
-            assignedTopicPartitionsNotPreviouslyOwned
-        );
+        final CompletableFuture<Void> onTasksRevokedCallbackExecuted = revokeActiveTasks(activeTasksToRevoke);
+
+        final CompletableFuture<Void> onTasksRevokedAndAssignedCallbacksExecuted = onTasksRevokedCallbackExecuted.thenCompose(__ -> {
+            if (!maybeAbortReconciliation()) {
+                return assignActiveTasks(assignedActiveTasks, ownedActiveTasks);
+            }
+            return CompletableFuture.completedFuture(null);
+        });
 
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            new StreamsOnAssignmentCallbackNeededEvent(new StreamsAssignmentInterface.Assignment(
-                assignedActiveTasks,
-                Collections.emptySet(),
-                Collections.emptySet()
-            ));
-        CompletableFuture<Void> onTasksAssignmentDone = onAssignmentCallbackNeededEvent.future();
-        backgroundEventHandler.add(onAssignmentCallbackNeededEvent);
         // The current target assignment is captured to ensure that acknowledging the current assignment is done with
         // the same target assignment that was used when this reconciliation was initiated.
         LocalAssignment currentTargetAssignment = targetAssignment;
-        onTasksAssignmentDone.whenComplete((__, callbackError) -> {
+        onTasksRevokedAndAssignedCallbacksExecuted.whenComplete((__, callbackError) -> {
             if (callbackError != null) {
-                log.error("Reconciliation failed: onTasksAssignment callback invocation failed for tasks {}",
-                    targetAssignment, callbackError);
+                log.error("Reconciliation failed: callback invocation failed for tasks {}",
+                    currentTargetAssignment, callbackError);
                 markReconciliationCompleted();
             } else {
                 if (reconciliationInProgress && !maybeAbortReconciliation()) {
@@ -756,8 +775,61 @@ public class StreamsMembershipManager implements RequestManager {
         });
     }
 
-    private SortedSet<TopicPartition> assignedTopicPartitionsNotPreviouslyOwned(final SortedSet<TopicPartition> assignedTopicPartitions,
-                                                                                final SortedSet<TopicPartition> ownedTopicPartitions) {
+    private CompletableFuture<Void> revokeActiveTasks(final SortedSet<StreamsAssignmentInterface.TaskId> activeTasksToRevoke) {
+        if (activeTasksToRevoke.isEmpty()) {
+            return CompletableFuture.completedFuture(null);
+        }
+
+        log.info("Revoking previously assigned active tasks {}", activeTasksToRevoke.stream()
+            .map(StreamsAssignmentInterface.TaskId::toString)
+            .collect(Collectors.joining(", ")));
+
+        final SortedSet<TopicPartition> partitionsToRevoke = topicPartitionsForActiveTasks(activeTasksToRevoke);
+        log.debug("Marking partitions pending for revocation: {}", partitionsToRevoke);
+        subscriptionState.markPendingRevocation(partitionsToRevoke);
+
+        return streamsAssignmentInterface.requestOnTasksRevokedCallbackInvocation(activeTasksToRevoke);
+    }
+
+    private CompletableFuture<Void> assignActiveTasks(final SortedSet<StreamsAssignmentInterface.TaskId> activeTasksToAssign,
+                                                      final SortedSet<StreamsAssignmentInterface.TaskId> ownedActiveTasks) {
+        log.info("Assigning active tasks {}", activeTasksToAssign.stream()
+            .map(StreamsAssignmentInterface.TaskId::toString)
+            .collect(Collectors.joining(", ")));
+
+        final SortedSet<TopicPartition> partitionsToAssign = topicPartitionsForActiveTasks(activeTasksToAssign);
+        final SortedSet<TopicPartition> partitionsToAssigneNotPreviouslyOwned =
+            partitionsToAssignNotPreviouslyOwned(partitionsToAssign, topicPartitionsForActiveTasks(ownedActiveTasks));
+
+        subscriptionState.assignFromSubscribedAwaitingCallback(
+            partitionsToAssign,
+            partitionsToAssigneNotPreviouslyOwned
+        );
+
+        return streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(
+            new StreamsAssignmentInterface.Assignment(
+                activeTasksToAssign,
+                Collections.emptySet(),
+                Collections.emptySet()
+            )
+        );
+    }
+
+    private CompletableFuture<Void> releaseLostActiveTasks() {
+        final SortedSet<StreamsAssignmentInterface.TaskId> activeTasksToRelease = toTaskIdSet(currentAssignment.activeTasks);
+        log.info("Revoking previously assigned and now lost active tasks {}", activeTasksToRelease.stream()
+            .map(StreamsAssignmentInterface.TaskId::toString)
+            .collect(Collectors.joining(", ")));
+
+        final SortedSet<TopicPartition> partitionsToRelease = topicPartitionsForActiveTasks(activeTasksToRelease);
+        log.debug("Marking lost partitions pending for revocation: {}", partitionsToRelease);
+        subscriptionState.markPendingRevocation(partitionsToRelease);
+
+        return streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation();
+    }
+
+    private SortedSet<TopicPartition> partitionsToAssignNotPreviouslyOwned(final SortedSet<TopicPartition> assignedTopicPartitions,
+                                                                           final SortedSet<TopicPartition> ownedTopicPartitions) {
         SortedSet<TopicPartition> assignedPartitionsNotPreviouslyOwned = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
         assignedPartitionsNotPreviouslyOwned.addAll(assignedTopicPartitions);
         assignedPartitionsNotPreviouslyOwned.removeAll(ownedTopicPartitions);
@@ -779,6 +851,19 @@ public class StreamsMembershipManager implements RequestManager {
         return topicPartitions;
     }
 
+    private SortedSet<TopicPartition> topicPartitionsForActiveTasks(final SortedSet<StreamsAssignmentInterface.TaskId> activeTasks) {
+        final SortedSet<TopicPartition> topicPartitions = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
+        activeTasks.forEach(task ->
+            Stream.concat(
+                streamsAssignmentInterface.subtopologyMap().get(task.subtopologyId()).sourceTopics.stream(),
+                streamsAssignmentInterface.subtopologyMap().get(task.subtopologyId()).repartitionSourceTopics.keySet().stream()
+            ).forEach(topic -> {
+                topicPartitions.add(new TopicPartition(topic, task.partitionId()));
+            })
+        );
+        return topicPartitions;
+    }
+
     private void markReconciliationCompleted() {
         reconciliationInProgress = false;
         rejoinedWhileReconciliationInProgress = false;
@@ -801,28 +886,47 @@ public class StreamsMembershipManager implements RequestManager {
         rejoinedWhileReconciliationInProgress = false;
     }
 
-    private CompletableFuture<Void> invokeRevokingAllTasksCallback() {
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            new StreamsOnAssignmentCallbackNeededEvent(new StreamsAssignmentInterface.Assignment(
-                Collections.emptySet(),
-                Collections.emptySet(),
-                Collections.emptySet()
-            ));
-        backgroundEventHandler.add(onAssignmentCallbackNeededEvent);
-        return onAssignmentCallbackNeededEvent.future();
+    public void onTasksRevokedCallbackCompleted(final StreamsOnTasksRevokedCallbackCompletedEvent event) {
+        Optional<KafkaException> error = event.error();
+        CompletableFuture<Void> future = event.future();
+
+        if (error.isPresent()) {
+            Exception e = error.get();
+            log.warn("The onTasksRevoked callback completed with an error ({}); " +
+                "signaling to continue to the next phase of rebalance", e.getMessage());
+            future.completeExceptionally(e);
+        } else {
+            log.debug("The onTasksRevoked callback completed successfully; signaling to continue to the next phase of rebalance");
+            future.complete(null);
+        }
+    }
+
+    public void onTasksAssignedCallbackCompleted(final StreamsOnTasksAssignedCallbackCompletedEvent event) {
+        Optional<KafkaException> error = event.error();
+        CompletableFuture<Void> future = event.future();
+
+        if (error.isPresent()) {
+            Exception e = error.get();
+            log.warn("The onTasksAssigned callback completed with an error ({}); " +
+                "signaling to continue to the next phase of rebalance", e.getMessage());
+            future.completeExceptionally(e);
+        } else {
+            log.debug("The onTasksAssigned callback completed successfully; signaling to continue to the next phase of rebalance");
+            future.complete(null);
+        }
     }
 
-    public void onTaskAssignmentCallbackCompleted(StreamsOnAssignmentCallbackCompletedEvent event) {
+    public void onAllTasksLostCallbackCompleted(final StreamsOnAllTasksLostCallbackCompletedEvent event) {
         Optional<KafkaException> error = event.error();
         CompletableFuture<Void> future = event.future();
 
         if (error.isPresent()) {
             Exception e = error.get();
-            log.warn("The onTaskAssignment callback completed with an error ({}); " +
+            log.warn("The onAllTasksLost callback completed with an error ({}); " +
                 "signaling to continue to the next phase of rebalance", e.getMessage());
             future.completeExceptionally(e);
         } else {
-            log.debug("The onTaskAssignment callback completed successfully; signaling to continue to the next phase of rebalance");
+            log.debug("The onAllTasksLost callback completed successfully; signaling to continue to the next phase of rebalance");
             future.complete(null);
         }
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
index dc0c393e279..b23584b053c 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
@@ -40,7 +40,9 @@ public abstract class ApplicationEvent {
         SHARE_ACKNOWLEDGE_ON_CLOSE,
         SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK_REGISTRATION,
         SEEK_UNVALIDATED,
-        STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED,
+        STREAMS_ON_TASKS_ASSIGNED_CALLBACK_COMPLETED,
+        STREAMS_ON_TASKS_REVOKED_CALLBACK_COMPLETED,
+        STREAMS_ON_ALL_TASKS_LOST_CALLBACK_COMPLETED,
     }
 
     private final Type type;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
index 135857a06b6..f36852c091a 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
@@ -180,6 +180,18 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
                 process((SeekUnvalidatedEvent) event);
                 return;
 
+            case STREAMS_ON_TASKS_REVOKED_CALLBACK_COMPLETED:
+                process((StreamsOnTasksRevokedCallbackCompletedEvent) event);
+                return;
+
+            case STREAMS_ON_TASKS_ASSIGNED_CALLBACK_COMPLETED:
+                process((StreamsOnTasksAssignedCallbackCompletedEvent) event);
+                return;
+
+            case STREAMS_ON_ALL_TASKS_LOST_CALLBACK_COMPLETED:
+                process((StreamsOnAllTasksLostCallbackCompletedEvent) event);
+                return;
+
             default:
                 log.warn("Application event type {} was not expected", event.type());
         }
@@ -289,21 +301,29 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
      * it is already a member on the next poll.
      */
     private void process(final TopicSubscriptionChangeEvent event) {
-        if (requestManagers.consumerHeartbeatRequestManager.isEmpty()) {
+        if (requestManagers.consumerMembershipManager.isPresent()) {
+            try {
+                if (subscriptions.subscribe(event.topics(), event.listener())) {
+                    this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
+                }
+                requestManagers.consumerMembershipManager.get().onSubscriptionUpdated();
+                event.future().complete(null);
+            } catch (Exception e) {
+                event.future().completeExceptionally(e);
+            }
+        } else if (requestManagers.streamsMembershipManager.isPresent()) {
+            try {
+                if (subscriptions.subscribe(event.topics(), event.listener())) {
+                    this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
+                }
+                requestManagers.streamsMembershipManager.get().onSubscriptionUpdated();
+                event.future().complete(null);
+            } catch (Exception e) {
+                event.future().completeExceptionally(e);
+            }
+        } else {
             log.warn("Group membership manager not present when processing a subscribe event");
             event.future().complete(null);
-            return;
-        }
-
-        try {
-            if (subscriptions.subscribe(event.topics(), event.listener()))
-                this.metadataVersionSnapshot = metadata.requestUpdateForNewTopics();
-
-            // Join the group if not already part of it, or just send the new subscription to the broker on the next poll.
-            requestManagers.consumerHeartbeatRequestManager.get().membershipManager().onSubscriptionUpdated();
-            event.future().complete(null);
-        } catch (Exception e) {
-            event.future().completeExceptionally(e);
         }
     }
 
@@ -374,6 +394,9 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
         if (requestManagers.consumerMembershipManager.isPresent()) {
             CompletableFuture<Void> future = requestManagers.consumerMembershipManager.get().leaveGroup();
             future.whenComplete(complete(event.future()));
+        } else if (requestManagers.streamsMembershipManager.isPresent()) {
+            CompletableFuture<Void> future = requestManagers.streamsMembershipManager.get().leaveGroup();
+            future.whenComplete(complete(event.future()));
         } else {
             // If the consumer is not using the group management capabilities, we still need to clear all assignments it may have.
             subscriptions.unsubscribe();
@@ -548,6 +571,33 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
         manager.setAcknowledgementCommitCallbackRegistered(event.isCallbackRegistered());
     }
 
+    private void process(final StreamsOnTasksRevokedCallbackCompletedEvent event) {
+        if (!requestManagers.streamsMembershipManager.isPresent()) {
+            log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
+                "of the onTasksRevoked callback execution could not be sent");
+            return;
+        }
+        requestManagers.streamsMembershipManager.get().onTasksRevokedCallbackCompleted(event);
+    }
+
+    private void process(final StreamsOnTasksAssignedCallbackCompletedEvent event) {
+        if (!requestManagers.streamsMembershipManager.isPresent()) {
+            log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
+                "of the onTasksAssigned callback execution could not be sent");
+            return;
+        }
+        requestManagers.streamsMembershipManager.get().onTasksAssignedCallbackCompleted(event);
+    }
+
+    private void process(final StreamsOnAllTasksLostCallbackCompletedEvent event) {
+        if (!requestManagers.streamsMembershipManager.isPresent()) {
+            log.warn("An internal error occurred; the Streams membership manager was not present, so the notification " +
+                "of the onAllTasksLost callback execution could not be sent");
+            return;
+        }
+        requestManagers.streamsMembershipManager.get().onAllTasksLostCallbackCompleted(event);
+    }
+
     private <T> BiConsumer<? super T, ? super Throwable> complete(final CompletableFuture<T> b) {
         return (value, exception) -> {
             if (exception != null)
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
index cffcca42f48..b18611895f9 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
@@ -28,7 +28,8 @@ public abstract class BackgroundEvent {
 
     public enum Type {
         ERROR, CONSUMER_REBALANCE_LISTENER_CALLBACK_NEEDED, SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK,
-        STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED
+        STREAMS_ON_TASKS_ASSIGNED_CALLBACK_NEEDED, STREAMS_ON_TASKS_REVOKED_CALLBACK_NEEDED,
+        STREAMS_ON_ALL_TASKS_LOST_CALLBACK_NEEDED
     }
 
     private final Type type;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackCompletedEvent.java
similarity index 82%
copy from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
copy to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackCompletedEvent.java
index 5b702efb62c..b84e9d0c138 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackCompletedEvent.java
@@ -22,14 +22,14 @@ import java.util.Objects;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 
-public class StreamsOnAssignmentCallbackCompletedEvent extends ApplicationEvent {
+public class StreamsOnAllTasksLostCallbackCompletedEvent extends ApplicationEvent {
 
     private final CompletableFuture<Void> future;
     private final Optional<KafkaException> error;
 
-    public StreamsOnAssignmentCallbackCompletedEvent(final CompletableFuture<Void> future,
-                                                     final Optional<KafkaException> error) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED);
+    public StreamsOnAllTasksLostCallbackCompletedEvent(final CompletableFuture<Void> future,
+                                                       final Optional<KafkaException> error) {
+        super(Type.STREAMS_ON_ALL_TASKS_LOST_CALLBACK_COMPLETED);
         this.future = Objects.requireNonNull(future);
         this.error = Objects.requireNonNull(error);
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackNeededEvent.java
similarity index 57%
copy from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
copy to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackNeededEvent.java
index 5ef6cd9c462..294cf3e2fde 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAllTasksLostCallbackNeededEvent.java
@@ -16,26 +16,15 @@
  */
 package org.apache.kafka.clients.consumer.internals.events;
 
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
+public class StreamsOnAllTasksLostCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
 
-import java.util.Objects;
-
-public class StreamsOnAssignmentCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
-
-    private final StreamsAssignmentInterface.Assignment assignment;
-
-    public StreamsOnAssignmentCallbackNeededEvent(StreamsAssignmentInterface.Assignment assignment) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED, Long.MAX_VALUE);
-        this.assignment = Objects.requireNonNull(assignment);
-    }
-
-    public StreamsAssignmentInterface.Assignment assignment() {
-        return assignment;
+    public StreamsOnAllTasksLostCallbackNeededEvent() {
+        super(Type.STREAMS_ON_ALL_TASKS_LOST_CALLBACK_NEEDED, Long.MAX_VALUE);
     }
 
     @Override
     protected String toStringBase() {
-        return super.toStringBase() +
-            ", assignment=" + assignment;
+        return super.toStringBase();
     }
 }
+
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackCompletedEvent.java
similarity index 81%
copy from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
copy to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackCompletedEvent.java
index 5b702efb62c..96c2519bb2d 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackCompletedEvent.java
@@ -22,14 +22,14 @@ import java.util.Objects;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 
-public class StreamsOnAssignmentCallbackCompletedEvent extends ApplicationEvent {
+public class StreamsOnTasksAssignedCallbackCompletedEvent extends ApplicationEvent {
 
     private final CompletableFuture<Void> future;
     private final Optional<KafkaException> error;
 
-    public StreamsOnAssignmentCallbackCompletedEvent(final CompletableFuture<Void> future,
-                                                     final Optional<KafkaException> error) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED);
+    public StreamsOnTasksAssignedCallbackCompletedEvent(final CompletableFuture<Void> future,
+                                                        final Optional<KafkaException> error) {
+        super(Type.STREAMS_ON_TASKS_ASSIGNED_CALLBACK_COMPLETED);
         this.future = Objects.requireNonNull(future);
         this.error = Objects.requireNonNull(error);
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackNeededEvent.java
similarity index 82%
copy from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
copy to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackNeededEvent.java
index 5ef6cd9c462..276eba3ca4a 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksAssignedCallbackNeededEvent.java
@@ -20,12 +20,12 @@ import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 
 import java.util.Objects;
 
-public class StreamsOnAssignmentCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
+public class StreamsOnTasksAssignedCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
 
     private final StreamsAssignmentInterface.Assignment assignment;
 
-    public StreamsOnAssignmentCallbackNeededEvent(StreamsAssignmentInterface.Assignment assignment) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED, Long.MAX_VALUE);
+    public StreamsOnTasksAssignedCallbackNeededEvent(StreamsAssignmentInterface.Assignment assignment) {
+        super(Type.STREAMS_ON_TASKS_ASSIGNED_CALLBACK_NEEDED, Long.MAX_VALUE);
         this.assignment = Objects.requireNonNull(assignment);
     }
 
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackCompletedEvent.java
similarity index 82%
rename from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
rename to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackCompletedEvent.java
index 5b702efb62c..5717012ac45 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackCompletedEvent.java
@@ -22,14 +22,14 @@ import java.util.Objects;
 import java.util.Optional;
 import java.util.concurrent.CompletableFuture;
 
-public class StreamsOnAssignmentCallbackCompletedEvent extends ApplicationEvent {
+public class StreamsOnTasksRevokedCallbackCompletedEvent extends ApplicationEvent {
 
     private final CompletableFuture<Void> future;
     private final Optional<KafkaException> error;
 
-    public StreamsOnAssignmentCallbackCompletedEvent(final CompletableFuture<Void> future,
-                                                     final Optional<KafkaException> error) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED);
+    public StreamsOnTasksRevokedCallbackCompletedEvent(final CompletableFuture<Void> future,
+                                                       final Optional<KafkaException> error) {
+        super(Type.STREAMS_ON_TASKS_REVOKED_CALLBACK_COMPLETED);
         this.future = Objects.requireNonNull(future);
         this.error = Objects.requireNonNull(error);
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackNeededEvent.java
similarity index 62%
rename from clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
rename to clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackNeededEvent.java
index 5ef6cd9c462..be7ae13b446 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnTasksRevokedCallbackNeededEvent.java
@@ -19,23 +19,25 @@ package org.apache.kafka.clients.consumer.internals.events;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 
 import java.util.Objects;
+import java.util.Set;
 
-public class StreamsOnAssignmentCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
+public class StreamsOnTasksRevokedCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
 
-    private final StreamsAssignmentInterface.Assignment assignment;
+    private final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke;
 
-    public StreamsOnAssignmentCallbackNeededEvent(StreamsAssignmentInterface.Assignment assignment) {
-        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED, Long.MAX_VALUE);
-        this.assignment = Objects.requireNonNull(assignment);
+    public StreamsOnTasksRevokedCallbackNeededEvent(final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke) {
+        super(Type.STREAMS_ON_TASKS_REVOKED_CALLBACK_NEEDED, Long.MAX_VALUE);
+        this.activeTasksToRevoke = Objects.requireNonNull(activeTasksToRevoke);
     }
 
-    public StreamsAssignmentInterface.Assignment assignment() {
-        return assignment;
+    public Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke() {
+        return activeTasksToRevoke;
     }
 
     @Override
     protected String toStringBase() {
         return super.toStringBase() +
-            ", assignment=" + assignment;
+            ", active tasks to revoke=" + activeTasksToRevoke;
     }
 }
+
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index 9e88e2c7569..a9e34cf2067 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -19,22 +19,17 @@ package org.apache.kafka.clients.consumer.internals;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest;
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TaskId;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TopicInfo;
 import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
 import org.apache.kafka.common.Node;
 import org.apache.kafka.common.Uuid;
-import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.metrics.Sensor;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.common.requests.ConsumerGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.RequestHeader;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
@@ -59,7 +54,6 @@ import java.util.Optional;
 import java.util.Properties;
 import java.util.Set;
 import java.util.UUID;
-import java.util.stream.Collectors;
 
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
@@ -93,7 +87,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
     private CoordinatorRequestManager coordinatorRequestManager;
 
     @Mock
-    private ConsumerMembershipManager membershipManager;
+    private StreamsMembershipManager membershipManager;
 
     @Mock
     private BackgroundEventHandler backgroundEventHandler;
@@ -141,8 +135,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
             membershipManager,
             backgroundEventHandler,
             metrics,
-            streamsAssignmentInterface,
-            metadata
+            streamsAssignmentInterface
         );
 
         when(membershipManager.groupId()).thenReturn(TEST_GROUP_ID);
@@ -160,7 +153,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
 
         assertEquals(0, result.unsentRequests.size());
-        verify(membershipManager).onHeartbeatRequestSkipped();
+        verify(membershipManager).transitionToUnsubscribeIfLeaving();
     }
 
     @Test
@@ -171,7 +164,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
 
         assertEquals(0, result.unsentRequests.size());
-        verify(membershipManager).onHeartbeatRequestSkipped();
+        verify(membershipManager).transitionToUnsubscribeIfLeaving();
     }
 
     @Test
@@ -347,35 +340,35 @@ class StreamsGroupHeartbeatRequestManagerTest {
 
         mockResponse(data);
 
-        ArgumentCaptor<ConsumerGroupHeartbeatResponse> captor = ArgumentCaptor.forClass(ConsumerGroupHeartbeatResponse.class);
+        ArgumentCaptor<StreamsGroupHeartbeatResponse> captor = ArgumentCaptor.forClass(StreamsGroupHeartbeatResponse.class);
         verify(membershipManager, times(1)).onHeartbeatSuccess(captor.capture());
-        ConsumerGroupHeartbeatResponseData response = captor.getValue().data();
+        StreamsGroupHeartbeatResponseData response = captor.getValue().data();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertEquals(TEST_MEMBER_ID, response.memberId());
         assertEquals(TEST_MEMBER_EPOCH, response.memberEpoch());
         assertEquals(TEST_THROTTLE_TIME_MS, response.throttleTimeMs());
         assertEquals(1000, response.heartbeatIntervalMs());
-        final List<TopicPartitions> tps = response.assignment().topicPartitions();
-        assertEquals(2, tps.size());
-        assertEquals(Set.of(uuid0, uuid1), tps.stream().map(TopicPartitions::topicId).collect(Collectors.toSet()));
-        assertEquals(Collections.singletonList(0), tps.get(0).partitions());
-        assertEquals(Collections.singletonList(0), tps.get(1).partitions());
-
-        final Assignment targetAssignment = streamsAssignmentInterface.targetAssignment.get();
-        assertEquals(1, targetAssignment.activeTasks.size());
-        final TaskId activeTaskId = targetAssignment.activeTasks.stream().findFirst().get();
-        assertEquals(activeTaskId.subtopologyId(), "0");
-        assertEquals(activeTaskId.partitionId(), 0);
-
-        assertEquals(1, targetAssignment.standbyTasks.size());
-        final TaskId standbyTaskId = targetAssignment.standbyTasks.stream().findFirst().get();
-        assertEquals(standbyTaskId.subtopologyId(), "1");
-        assertEquals(standbyTaskId.partitionId(), 1);
-
-        assertEquals(1, targetAssignment.warmupTasks.size());
-        final TaskId warmupTaskId = targetAssignment.warmupTasks.stream().findFirst().get();
-        assertEquals(warmupTaskId.subtopologyId(), "2");
-        assertEquals(warmupTaskId.partitionId(), 2);
+//        final List<TopicPartitions> tps = response.assign.topicPartitions();
+//        assertEquals(2, tps.size());
+//        assertEquals(Set.of(uuid0, uuid1), tps.stream().map(TopicPartitions::topicId).collect(Collectors.toSet()));
+//        assertEquals(Collections.singletonList(0), tps.get(0).partitions());
+//        assertEquals(Collections.singletonList(0), tps.get(1).partitions());
+
+//        final Assignment targetAssignment = streamsAssignmentInterface.targetAssignment.get();
+//        assertEquals(1, targetAssignment.activeTasks.size());
+//        final TaskId activeTaskId = targetAssignment.activeTasks.stream().findFirst().get();
+//        assertEquals(activeTaskId.subtopologyId(), "0");
+//        assertEquals(activeTaskId.partitionId(), 0);
+//
+//        assertEquals(1, targetAssignment.standbyTasks.size());
+//        final TaskId standbyTaskId = targetAssignment.standbyTasks.stream().findFirst().get();
+//        assertEquals(standbyTaskId.subtopologyId(), "1");
+//        assertEquals(standbyTaskId.partitionId(), 1);
+//
+//        assertEquals(1, targetAssignment.warmupTasks.size());
+//        final TaskId warmupTaskId = targetAssignment.warmupTasks.stream().findFirst().get();
+//        assertEquals(warmupTaskId.subtopologyId(), "2");
+//        assertEquals(warmupTaskId.partitionId(), 2);
 
     }
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
index 7d954477da9..1ee0975a8cb 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
@@ -18,8 +18,9 @@ package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.clients.consumer.internals.events.BackgroundEvent;
 import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
-import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackCompletedEvent;
-import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackNeededEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAllTasksLostCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksAssignedCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnTasksAssignedCallbackNeededEvent;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
@@ -34,6 +35,8 @@ import org.apache.kafka.common.utils.Time;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
 import org.mockito.Mock;
 import org.mockito.junit.jupiter.MockitoExtension;
 
@@ -54,6 +57,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -85,6 +89,9 @@ public class StreamsMembershipManagerTest {
     @Mock
     private StreamsAssignmentInterface streamsAssignmentInterface;
 
+    @Captor
+    private ArgumentCaptor<StreamsOnTasksAssignedCallbackNeededEvent> onAssignmentCallbackNeededEventCaptor;
+
     private Queue<BackgroundEvent> backgroundEventQueue = new LinkedList<>();
     private BackgroundEventHandler backgroundEventHandler = new BackgroundEventHandler(backgroundEventQueue);
 
@@ -95,8 +102,6 @@ public class StreamsMembershipManagerTest {
             streamsAssignmentInterface,
             subscriptionState,
             new LogContext("test"),
-            Optional.empty(),
-            backgroundEventHandler,
             time,
             metrics
         );
@@ -151,62 +156,87 @@ public class StreamsMembershipManagerTest {
     @Test
     public void testReconcilingEmptyToSingleActiveTask() {
         setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         joining();
 
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
 
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
-            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
-        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        final Collection<TopicPartition> expectedPartitionsToAssign = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedPartitionsToAssign);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        onTasksAssignedCallbackExecuted.complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateAcknowledging(membershipManager);
+        verify(streamsAssignmentInterface, never()).requestOnTasksRevokedCallbackInvocation(any());
     }
 
     @Test
     public void testReconcilingActiveTaskToDifferentActiveTask() {
         setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        final CompletableFuture<Void> onTasksRevokedCallbackExecuted = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        when(streamsAssignmentInterface.requestOnTasksRevokedCallbackInvocation(activeTasksSetup))
+            .thenReturn(onTasksRevokedCallbackExecuted);
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         when(subscriptionState.assignedPartitions())
             .thenReturn(Collections.emptySet())
             .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0)));
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
 
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
-        );
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        final Set<TopicPartition> expectedPartitionsToRevoke = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
+        final Collection<TopicPartition> expectedPartitionsToAssign = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
+        verify(subscriptionState).markPendingRevocation(expectedPartitionsToRevoke);
+        verify(subscriptionState, never()).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedPartitionsToAssign);
+        onTasksRevokedCallbackExecuted.complete(null);
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedPartitionsToAssign);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        onTasksAssignedCallbackExecuted.complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateAcknowledging(membershipManager);
     }
 
     @Test
     public void testReconcilingSingleActiveTaskToAdditionalActiveTask() {
         setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         when(subscriptionState.assignedPartitions())
             .thenReturn(Collections.emptySet())
             .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0)));
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0, PARTITION_1)));
 
@@ -214,57 +244,58 @@ public class StreamsMembershipManagerTest {
             new TopicPartition(TOPIC_0, PARTITION_0),
             new TopicPartition(TOPIC_0, PARTITION_1)
         );
-        final Collection<TopicPartition> expectedAdditionalPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(
-            expectedPartitionAssignment,
-            expectedAdditionalPartitionAssignment
-        );
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
-        );
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        final Collection<TopicPartition> expectedAdditionalPartitionsToAssign = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedAdditionalPartitionsToAssign);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        onTasksAssignedCallbackExecuted.complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionsToAssign);
         verifyInStateAcknowledging(membershipManager);
+        verify(streamsAssignmentInterface, never()).requestOnTasksRevokedCallbackInvocation(any());
     }
 
     @Test
     public void testReconcilingMultipleActiveTaskToSingleActiveTask() {
         setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final CompletableFuture<Void> onTasksRevokedCallbackExecuted = new CompletableFuture<>();
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        when(streamsAssignmentInterface.requestOnTasksRevokedCallbackInvocation(activeTasksToRevoke))
+            .thenReturn(onTasksRevokedCallbackExecuted);
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         when(subscriptionState.assignedPartitions())
             .thenReturn(Collections.emptySet())
             .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0), new TopicPartition(TOPIC_0, PARTITION_1)));
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0, PARTITION_1)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
 
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
-            new TopicPartition(TOPIC_0, PARTITION_1)
-        );
-        final Collection<TopicPartition> expectedAdditionalPartitionAssignment = Collections.emptySet();
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(
-            expectedPartitionAssignment,
-            expectedAdditionalPartitionAssignment
-        );
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
-        );
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        final Set<TopicPartition> expectedPartitionsToRevoke = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
+        final Collection<TopicPartition> expectedPartitionsToAssign = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
+        final Collection<TopicPartition> expectedAdditionalPartitionsToAssign = Collections.emptySet();
+        verify(subscriptionState).markPendingRevocation(expectedPartitionsToRevoke);
+        verify(subscriptionState, never()).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedAdditionalPartitionsToAssign);
+        onTasksRevokedCallbackExecuted.complete(null);
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedAdditionalPartitionsToAssign);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedAdditionalPartitionsToAssign);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        onTasksAssignedCallbackExecuted.complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionsToAssign);
         verifyInStateAcknowledging(membershipManager);
     }
 
@@ -274,79 +305,50 @@ public class StreamsMembershipManagerTest {
             SUB_TOPOLOGY_ID_0, TOPIC_0,
             SUB_TOPOLOGY_ID_1, TOPIC_1
         );
-        joining();
-
-        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0), SUB_TOPOLOGY_ID_1, List.of(PARTITION_0)));
-
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
-            new TopicPartition(TOPIC_0, PARTITION_0),
-            new TopicPartition(TOPIC_1, PARTITION_0)
-        );
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
         final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
             new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
             new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_1, PARTITION_0)
         );
-        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
-        verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
-        verifyInStateAcknowledging(membershipManager);
-    }
-
-    @Test
-    public void testReconcilingEmptyToMultipleActiveTaskOfConcatenatedSubtopologies() {
-        setupStreamsAssignmentInterfaceWithTwoConcatenedSubtopologies(
-            SUB_TOPOLOGY_ID_0, TOPIC_0,
-            SUB_TOPOLOGY_ID_1, TOPIC_1
-        );
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         joining();
 
-        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0), SUB_TOPOLOGY_ID_1, List.of(PARTITION_0)));
+        reconcile(makeHeartbeatResponse(
+            SUB_TOPOLOGY_ID_0, List.of(PARTITION_0),
+            SUB_TOPOLOGY_ID_1, List.of(PARTITION_0))
+        );
 
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
+        final Collection<TopicPartition> expectedPartitionsToAssign = Set.of(
             new TopicPartition(TOPIC_0, PARTITION_0),
             new TopicPartition(TOPIC_1, PARTITION_0)
         );
-        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
-            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_1, PARTITION_0)
-        );
-        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
-        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
-        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionsToAssign, expectedPartitionsToAssign);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().complete(null);
-        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        onTasksAssignedCallbackExecuted.complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionsToAssign);
         verifyInStateAcknowledging(membershipManager);
+        verify(streamsAssignmentInterface, never()).requestOnTasksRevokedCallbackInvocation(any());
     }
 
     @Test
     public void testReconcilingAndAssignmentCallbackFails() {
-        final String topicName = "test_topic";
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, topicName);
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
         final Set<StreamsAssignmentInterface.TaskId> activeTasks =
             Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecuted);
         joining();
 
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
 
-        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(topicName, PARTITION_0));
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
         verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
         verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
         verifyInStateReconciling(membershipManager);
-        onAssignmentCallbackNeededEvent.future().completeExceptionally(new RuntimeException("KABOOM!"));
+        onTasksAssignedCallbackExecuted.completeExceptionally(new RuntimeException("KABOOM!"));
         verifyInStateReconciling(membershipManager);
         verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
     }
@@ -365,6 +367,9 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testLeaveGroupWhenNotInGroupAndFenced() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
         fenced();
         final CompletableFuture<Void> future = membershipManager.leaveGroup();
@@ -380,39 +385,52 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testLeaveGroupWhenInGroupWithAssignment() {
-        final StreamsAssignmentInterface.Assignment emptyStreamsAssignment = makeTaskAssignment(Collections.emptySet());
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        final CompletableFuture<Void> onTasksRevokedCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksRevokedCallbackInvocation(activeTasks))
+            .thenReturn(onTasksRevokedCallbackExecuted);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
-        final CompletableFuture<Void> future = membershipManager.leaveGroup();
+        final CompletableFuture<Void> onGroupLeft = membershipManager.leaveGroup();
 
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        assertEquals(emptyStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        assertFalse(onGroupLeft.isDone());
         verify(subscriptionState, never()).unsubscribe();
         verifyInStatePrepareLeaving(membershipManager);
-        final CompletableFuture<Void> futureBeforeRevocationCallback = membershipManager.leaveGroup();
-        assertEquals(future, futureBeforeRevocationCallback);
-        onAssignmentCallbackNeededEvent.future().complete(null);
+        final CompletableFuture<Void> onGroupLeftBeforeRevocationCallback = membershipManager.leaveGroup();
+        assertEquals(onGroupLeft, onGroupLeftBeforeRevocationCallback);
+        onTasksRevokedCallbackExecuted.complete(null);
         verify(subscriptionState).unsubscribe();
-        assertFalse(future.isDone());
+        assertFalse(onGroupLeft.isDone());
         verifyInStateLeaving(membershipManager);
-        final CompletableFuture<Void> futureAfterRevocationCallback = membershipManager.leaveGroup();
-        assertEquals(future, futureAfterRevocationCallback);
+        final CompletableFuture<Void> onGroupLeftAfterRevocationCallback = membershipManager.leaveGroup();
+        assertEquals(onGroupLeft, onGroupLeftAfterRevocationCallback);
         membershipManager.transitionToUnsubscribeIfLeaving();
         verifyInStateUnsubscribed(membershipManager);
     }
 
     @Test
     public void testTransitionToUnsubscribeWhenInLeaving() {
-        final StreamsGroupHeartbeatResponse response = makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0));
         setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        final CompletableFuture<Void> onAllTasksRevokedCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksRevokedCallbackInvocation(activeTasksSetup))
+            .thenReturn(onAllTasksRevokedCallbackExecuted);
         joining();
-        reconcile(response);
-        acknowledging();
-        CompletableFuture<Void> future = leaving();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
+        CompletableFuture<Void> future = leaving(onAllTasksRevokedCallbackExecuted);
 
         membershipManager.transitionToUnsubscribeIfLeaving();
 
@@ -424,10 +442,15 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnPollTimerExpired() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         membershipManager.onPollTimerExpired();
 
@@ -437,10 +460,15 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnHeartbeatRequestGeneratedWhenInAcknowleding() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         membershipManager.onHeartbeatRequestGenerated();
 
@@ -449,11 +477,16 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnHeartbeatRequestGeneratedWhenInAcknowledgingAndNewTargetAssignment() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         membershipManager.onHeartbeatRequestGenerated();
 
@@ -462,8 +495,11 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnHeartbeatRequestGeneratedWhenInLeaving() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
-        leaving();
+        leaving(onAllTasksLostCallbackExecuted);
 
         membershipManager.onHeartbeatRequestGenerated();
 
@@ -472,6 +508,9 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnHeartbeatRequestGeneratedWhenInLeavingAndPollTimerExpired() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
         membershipManager.onPollTimerExpired();
 
@@ -489,51 +528,69 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnFencedWhenInReconciling() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        backgroundEventQueue.poll();
 
         testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
     }
 
     @Test
     public void testOnFencedWhenInAcknowledging() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
         testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
     }
 
     @Test
     public void testOnFencedWhenInStable() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasks)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
         stable();
 
         testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
     }
 
     private void testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
+
         membershipManager.onFenced();
 
         verifyInStateFenced(membershipManager);
         assertEquals(StreamsGroupHeartbeatRequest.JOIN_GROUP_MEMBER_EPOCH, membershipManager.memberEpoch());
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(Collections.emptySet());
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
-        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState, never()).assignFromSubscribed(Collections.emptySet());
+        onAllTasksLostCallbackExecuted.complete(null);
         verify(subscriptionState).assignFromSubscribed(Collections.emptySet());
         verifyInStateJoining(membershipManager);
     }
 
     @Test
     public void testOnFencedWhenInPrepareLeaving() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
 
         testOnFencedWhenInPrepareLeavingOrLeaving(prepareLeaving());
@@ -541,9 +598,12 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testOnFencedWhenInLeaving() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
 
-        testOnFencedWhenInPrepareLeavingOrLeaving(leaving());
+        testOnFencedWhenInPrepareLeavingOrLeaving(leaving(onAllTasksLostCallbackExecuted));
     }
 
     private void testOnFencedWhenInPrepareLeavingOrLeaving(final CompletableFuture<Void> onGroupLeft) {
@@ -558,6 +618,9 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testTransitionToFatalWhenInPrepareLeaving() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
 
         testTransitionToFatalWhenInPrepareLeavingOrLeaving(prepareLeaving());
@@ -565,9 +628,12 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testTransitionToFatalWhenInLeaving() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
 
-        testTransitionToFatalWhenInPrepareLeavingOrLeaving(leaving());
+        testTransitionToFatalWhenInPrepareLeavingOrLeaving(leaving(onAllTasksLostCallbackExecuted));
     }
 
     private void testTransitionToFatalWhenInPrepareLeavingOrLeaving(final CompletableFuture<Void> onGroupLeft) {
@@ -581,63 +647,89 @@ public class StreamsMembershipManagerTest {
 
     @Test
     public void testTransitionToFatalWhenInJoining() {
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
 
-        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable(onAllTasksLostCallbackExecuted);
     }
 
     @Test
     public void testTransitionToFatalWhenInReconciling() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        backgroundEventQueue.poll();
 
-        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable(onAllTasksLostCallbackExecuted);
     }
 
     @Test
     public void testTransitionToFatalWhenInAcknowledging() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
 
-        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable(onAllTasksLostCallbackExecuted);
     }
 
     @Test
     public void testTransitionToFatalWhenInStable() {
-        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        final CompletableFuture<Void> onTasksAssignedCallbackExecutedSetup = new CompletableFuture<>();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasksSetup = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0)
+        );
+        when(streamsAssignmentInterface.requestOnTasksAssignedCallbackInvocation(makeTaskAssignment(activeTasksSetup)))
+            .thenReturn(onTasksAssignedCallbackExecutedSetup);
+        final CompletableFuture<Void> onAllTasksLostCallbackExecuted = new CompletableFuture<>();
+        when(streamsAssignmentInterface.requestOnAllTasksLostCallbackInvocation())
+            .thenReturn(onAllTasksLostCallbackExecuted);
         joining();
         reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
-        acknowledging();
+        acknowledging(onTasksAssignedCallbackExecutedSetup);
         stable();
 
-        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable(onAllTasksLostCallbackExecuted);
     }
 
-    private void testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable() {
+    private void testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable(final CompletableFuture<Void> future) {
         membershipManager.transitionToFatal();
 
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(Collections.emptySet());
-        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
-        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState, never()).assignFromSubscribed(Collections.emptySet());
+        future.complete(null);
         verify(subscriptionState).assignFromSubscribed(Collections.emptySet());
         verifyInStateFatal(membershipManager);
     }
 
     @Test
-    public void testOnTaskAssignmentCallbackCompleted() {
+    public void testOnTasksAssignedCallbackCompleted() {
         final CompletableFuture<Void> future = new CompletableFuture<>();
-        final StreamsOnAssignmentCallbackCompletedEvent event = new StreamsOnAssignmentCallbackCompletedEvent(
+        final StreamsOnTasksAssignedCallbackCompletedEvent event = new StreamsOnTasksAssignedCallbackCompletedEvent(
             future,
             Optional.empty()
         );
 
-        membershipManager.onTaskAssignmentCallbackCompleted(event);
+        membershipManager.onTasksAssignedCallbackCompleted(event);
 
         assertTrue(future.isDone());
         assertFalse(future.isCancelled());
@@ -645,15 +737,30 @@ public class StreamsMembershipManagerTest {
     }
 
     @Test
-    public void testOnTaskAssignmentCallbackCompletedWhenCallbackFails() {
+    public void testOnAllTasksLostCallbackCompleted() {
+        final CompletableFuture<Void> future = new CompletableFuture<>();
+        final StreamsOnAllTasksLostCallbackCompletedEvent event = new StreamsOnAllTasksLostCallbackCompletedEvent(
+            future,
+            Optional.empty()
+        );
+
+        membershipManager.onAllTasksLostCallbackCompleted(event);
+
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertFalse(future.isCompletedExceptionally());
+    }
+
+    @Test
+    public void testOnTasksAssignedCallbackCompletedWhenCallbackFails() {
         final String errorMessage = "KABOOM!";
         final CompletableFuture<Void> future = new CompletableFuture<>();
-        final StreamsOnAssignmentCallbackCompletedEvent event = new StreamsOnAssignmentCallbackCompletedEvent(
+        final StreamsOnAllTasksLostCallbackCompletedEvent event = new StreamsOnAllTasksLostCallbackCompletedEvent(
             future,
             Optional.of(new KafkaException(errorMessage))
         );
 
-        membershipManager.onTaskAssignmentCallbackCompleted(event);
+        membershipManager.onAllTasksLostCallbackCompleted(event);
 
         assertTrue(future.isDone());
         assertFalse(future.isCancelled());
@@ -781,43 +888,6 @@ public class StreamsMembershipManagerTest {
         );
     }
 
-    private void setupStreamsAssignmentInterfaceWithTwoConcatenedSubtopologies(final String subtopologyId1,
-                                                                               final String topicName1,
-                                                                               final String subtopologyId2,
-                                                                               final String topicName2) {
-        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
-            mkMap(
-                mkEntry(
-                    subtopologyId1,
-                    new StreamsAssignmentInterface.Subtopology(
-                        Set.of(topicName1),
-                        Collections.emptySet(),
-                        Collections.emptyMap(),
-                        Collections.emptyMap(),
-                        Collections.emptyList()
-                    )
-                ),
-                mkEntry(
-                    subtopologyId2,
-                    new StreamsAssignmentInterface.Subtopology(
-                        Set.of(topicName2),
-                        Collections.emptySet(),
-                        mkMap(mkEntry(
-                            topicName2,
-                            new StreamsAssignmentInterface.TopicInfo(
-                                Optional.empty(),
-                                Optional.empty(),
-                                Collections.emptyMap()
-                            )
-                        )),
-                        Collections.emptyMap(),
-                        Collections.emptyList()
-                    )
-                )
-            )
-        );
-    }
-
     private StreamsGroupHeartbeatResponse makeHeartbeatResponse(final String subtopologyId,
                                                                 final List<Integer> partitions) {
         return makeHeartbeatResponse(Collections.singletonList(
@@ -874,23 +944,26 @@ public class StreamsMembershipManagerTest {
     }
 
     private void acknowledging() {
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final StreamsOnTasksAssignedCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnTasksAssignedCallbackNeededEvent) backgroundEventQueue.poll();
         onAssignmentCallbackNeededEvent.future().complete(null);
         verifyInStateAcknowledging(membershipManager);
     }
 
+    private void acknowledging(final CompletableFuture<Void> future) {
+        future.complete(null);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
     private CompletableFuture<Void> prepareLeaving() {
         final CompletableFuture<Void> onGroupLeft = membershipManager.leaveGroup();
         verifyInStatePrepareLeaving(membershipManager);
         return onGroupLeft;
     }
 
-    private CompletableFuture<Void> leaving() {
+    private CompletableFuture<Void> leaving(final CompletableFuture<Void> onAllTasksRevokedCallbackExecuted) {
         final CompletableFuture<Void> future = prepareLeaving();
-        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
-            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
-        onAssignmentCallbackNeededEvent.future().complete(null);
+        onAllTasksRevokedCallbackExecuted.complete(null);
         verifyInStateLeaving(membershipManager);
         return future;
     }
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
index 25e41a88257..511e602b9bf 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
@@ -31,6 +31,8 @@ import org.apache.kafka.clients.consumer.internals.MockRebalanceListener;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate;
 import org.apache.kafka.clients.consumer.internals.OffsetsRequestManager;
 import org.apache.kafka.clients.consumer.internals.RequestManagers;
+import org.apache.kafka.clients.consumer.internals.StreamsGroupHeartbeatRequestManager;
+import org.apache.kafka.clients.consumer.internals.StreamsMembershipManager;
 import org.apache.kafka.clients.consumer.internals.SubscriptionState;
 import org.apache.kafka.clients.consumer.internals.TopicMetadataRequestManager;
 import org.apache.kafka.common.Cluster;
@@ -81,6 +83,8 @@ public class ApplicationEventProcessorTest {
     private final CommitRequestManager commitRequestManager = mock(CommitRequestManager.class);
     private final ConsumerHeartbeatRequestManager heartbeatRequestManager = mock(ConsumerHeartbeatRequestManager.class);
     private final ConsumerMembershipManager membershipManager = mock(ConsumerMembershipManager.class);
+    private final StreamsGroupHeartbeatRequestManager streamsGroupHeartbeatRequestManager = mock(StreamsGroupHeartbeatRequestManager.class);
+    private final StreamsMembershipManager streamsMembershipManager = mock(StreamsMembershipManager.class);
     private final OffsetsRequestManager offsetsRequestManager = mock(OffsetsRequestManager.class);
     private SubscriptionState subscriptionState = mock(SubscriptionState.class);
     private final ConsumerMetadata metadata = mock(ConsumerMetadata.class);
@@ -96,6 +100,7 @@ public class ApplicationEventProcessorTest {
                 withGroupId ? Optional.of(commitRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(heartbeatRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(membershipManager) : Optional.empty(),
+                Optional.empty(),
                 Optional.empty()
         );
 
@@ -107,6 +112,28 @@ public class ApplicationEventProcessorTest {
         );
     }
 
+    private void setupProcessorWithStreamsMembershipManager() {
+        RequestManagers requestManagers = new RequestManagers(
+                new LogContext(),
+                offsetsRequestManager,
+                mock(TopicMetadataRequestManager.class),
+                mock(FetchRequestManager.class),
+                Optional.of(mock(CoordinatorRequestManager.class)),
+                Optional.of(commitRequestManager),
+                Optional.empty(),
+                Optional.empty(),
+                Optional.of(streamsGroupHeartbeatRequestManager),
+                Optional.of(streamsMembershipManager)
+        );
+
+        processor = new ApplicationEventProcessor(
+                new LogContext(),
+                requestManagers,
+                metadata,
+                subscriptionState
+        );
+    }
+
     @Test
     public void testPrepClosingCommitEvents() {
         setupProcessor(true);
@@ -125,6 +152,15 @@ public class ApplicationEventProcessorTest {
         verify(membershipManager).leaveGroup();
     }
 
+    @Test
+    public void testProcessUnsubscribeEventWithStreamsMembershipManager() {
+        setupProcessorWithStreamsMembershipManager();
+        when(heartbeatRequestManager.membershipManager()).thenReturn(membershipManager);
+        when(streamsMembershipManager.leaveGroup()).thenReturn(CompletableFuture.completedFuture(null));
+        processor.process(new UnsubscribeEvent(0));
+        verify(streamsMembershipManager).leaveGroup();
+    }
+
     @Test
     public void testProcessUnsubscribeEventWithoutGroupId() {
         setupProcessor(false);
@@ -501,6 +537,55 @@ public class ApplicationEventProcessorTest {
         );
     }
 
+    @Test
+    public void testSubscriptionChangeEventWithStreamsMembershipManager() {
+        Set<String> topics = Set.of("topic1", "topic2");
+        Optional<ConsumerRebalanceListener> listener = Optional.of(new MockRebalanceListener());
+        TopicSubscriptionChangeEvent event = new TopicSubscriptionChangeEvent(topics, listener, 12345);
+
+        setupProcessorWithStreamsMembershipManager();
+        processor.process(event);
+        verify(streamsMembershipManager).onSubscriptionUpdated();
+        // verify member state doesn't transition to JOINING.
+        verify(streamsMembershipManager, never()).onConsumerPoll();
+    }
+
+    @Test
+    public void testOnTasksRevokedCallbackExecuted() {
+        StreamsOnTasksRevokedCallbackCompletedEvent event = new StreamsOnTasksRevokedCallbackCompletedEvent(
+            new CompletableFuture<>(),
+            Optional.empty()
+        );
+
+        setupProcessorWithStreamsMembershipManager();
+        processor.process(event);
+        verify(streamsMembershipManager).onTasksRevokedCallbackCompleted(event);
+    }
+
+    @Test
+    public void testOnTasksAssignedCallbackExecuted() {
+        StreamsOnTasksAssignedCallbackCompletedEvent event = new StreamsOnTasksAssignedCallbackCompletedEvent(
+            new CompletableFuture<>(),
+            Optional.empty()
+        );
+
+        setupProcessorWithStreamsMembershipManager();
+        processor.process(event);
+        verify(streamsMembershipManager).onTasksAssignedCallbackCompleted(event);
+    }
+
+    @Test
+    public void testOnAllTasksLostCallbackExecuted() {
+        StreamsOnAllTasksLostCallbackCompletedEvent event = new StreamsOnAllTasksLostCallbackCompletedEvent(
+            new CompletableFuture<>(),
+            Optional.empty()
+        );
+
+        setupProcessorWithStreamsMembershipManager();
+        processor.process(event);
+        verify(streamsMembershipManager).onAllTasksLostCallbackCompleted(event);
+    }
+
     private List<NetworkClientDelegate.UnsentRequest> mockCommitResults() {
         return Collections.singletonList(mock(NetworkClientDelegate.UnsentRequest.class));
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 4270e0d80c9..4af85ad97c9 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -833,7 +833,7 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
      * @param record        The record to apply to the state machine.
      * @throws RuntimeException
      */
-    @SuppressWarnings("CyclomaticComplexity")
+    @SuppressWarnings({"CyclomaticComplexity", "MethodLength"})
     @Override
     public void replay(
         long offset,
@@ -954,48 +954,55 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 break;
 
             case 16:
+                groupMetadataManager.replay(
+                    (ConsumerGroupRegularExpressionKey) key.message(),
+                    (ConsumerGroupRegularExpressionValue) Utils.messageOrNull(value)
+                );
+                break;
+
+            case 17:
                 groupMetadataManager.replay(
                     (StreamsGroupMetadataKey) key.message(),
                     (StreamsGroupMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 17:
+            case 18:
                 groupMetadataManager.replay(
                     (StreamsGroupPartitionMetadataKey) key.message(),
                     (StreamsGroupPartitionMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 18:
+            case 19:
                 groupMetadataManager.replay(
                     (StreamsGroupMemberMetadataKey) key.message(),
                     (StreamsGroupMemberMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 19:
+            case 20:
                 groupMetadataManager.replay(
                     (StreamsGroupTargetAssignmentMetadataKey) key.message(),
                     (StreamsGroupTargetAssignmentMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 20:
+            case 21:
                 groupMetadataManager.replay(
                     (StreamsGroupTargetAssignmentMemberKey) key.message(),
                     (StreamsGroupTargetAssignmentMemberValue) messageOrNull(value)
                 );
                 break;
 
-            case 21:
+            case 22:
                 groupMetadataManager.replay(
                     (StreamsGroupCurrentMemberAssignmentKey) key.message(),
                     (StreamsGroupCurrentMemberAssignmentValue) messageOrNull(value)
                 );
                 break;
 
-            case 22:
+            case 23:
                 groupMetadataManager.replay(
                     (StreamsGroupTopologyKey) key.message(),
                     (StreamsGroupTopologyValue) messageOrNull(value)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 6e834eb2ba0..9a3236a16a4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -58,7 +58,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 17
+                (short) 19
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMemberMetadataValue()
@@ -96,7 +96,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 17
+                (short) 19
             ),
             null // Tombstone.
         );
@@ -137,7 +137,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 16
+                (short) 18
             ),
             new ApiMessageAndVersion(
                 value,
@@ -159,7 +159,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 16
+                (short) 18
             ),
             null // Tombstone.
         );
@@ -173,7 +173,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 15
+                (short) 17
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataValue()
@@ -196,7 +196,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 15
+                (short) 17
             ),
             null // Tombstone.
         );
@@ -239,7 +239,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 19
+                (short) 21
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMemberValue()
@@ -267,7 +267,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 19
+                (short) 21
             ),
             null // Tombstone.
         );
@@ -282,7 +282,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 18
+                (short) 20
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataValue()
@@ -305,7 +305,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 18
+                (short) 20
             ),
             null // Tombstone.
         );
@@ -320,7 +320,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 20
+                (short) 22
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupCurrentMemberAssignmentValue()
@@ -354,7 +354,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 20
+                (short) 22
             ),
             null // Tombstone
         );
@@ -396,7 +396,7 @@ public class CoordinatorStreamsRecordHelpers {
         return new CoordinatorRecord(new ApiMessageAndVersion(
             new StreamsGroupTopologyKey()
                 .setGroupId(groupId),
-            (short) 21),
+            (short) 23),
             new ApiMessageAndVersion(value, (short) 0));
     }
 
@@ -466,7 +466,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId(groupId),
-                (short) 21
+                (short) 23
             ),
             null // Tombstone
         );
diff --git a/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json b/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
index 2cb82e4de10..3f761b694e4 100644
--- a/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
+++ b/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
@@ -20,9 +20,9 @@
   "validVersions": "16",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "44",
+    { "name": "GroupId", "type": "string", "versions": "16",
       "about": "The group id." },
-    { "name": "RegularExpression", "type": "string", "versions": "44",
+    { "name": "RegularExpression", "type": "string", "versions": "16",
       "about": "The regular expression." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
index a99e32754c6..5f199f7b00a 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupCurrentMemberAssignmentKey",
-  "validVersions": "20",
+  "validVersions": "22",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "20",
+    { "name": "GroupId", "type": "string", "versions": "22",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "20",
+    { "name": "MemberId", "type": "string", "versions": "22",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
index 8e0f66deba7..7136d03c149 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupMemberMetadataKey",
-  "validVersions": "17",
+  "validVersions": "19",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "17",
+    { "name": "GroupId", "type": "string", "versions": "19",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "17",
+    { "name": "MemberId", "type": "string", "versions": "19",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
index 6c54fb8bd14..d018df39dcf 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupMetadataKey",
-  "validVersions": "15",
+  "validVersions": "17",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "15",
+    { "name": "GroupId", "type": "string", "versions": "17",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
index 618fbc78451..4ca6baf7b32 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupPartitionMetadataKey",
-  "validVersions": "56",
+  "validVersions": "18",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "56",
+    { "name": "GroupId", "type": "string", "versions": "18",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
index f96f6f89e01..0da4f6684e9 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMemberKey",
-  "validVersions": "19",
+  "validVersions": "21",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "19",
+    { "name": "GroupId", "type": "string", "versions": "21",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "19",
+    { "name": "MemberId", "type": "string", "versions": "21",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
index 514885f8ad7..c8e81d84260 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMetadataKey",
-  "validVersions": "18",
+  "validVersions": "20",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "18",
+    { "name": "GroupId", "type": "string", "versions": "20",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
index 2e51c117bd7..4cfef5740a0 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTopologyKey",
-  "validVersions": "21",
+  "validVersions": "23",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "21",
+    { "name": "GroupId", "type": "string", "versions": "23",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 029c3b8025f..61a77bb5693 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -118,7 +118,7 @@ class CoordinatorStreamsRecordHelpersTest {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId("group-id"),
-                (short) 21),
+                (short) 23),
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyValue()
                     .setTopology(expectedTopology),
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index 90e17194b6f..7f45577dca8 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -26,7 +26,6 @@ import org.apache.kafka.clients.consumer.InvalidOffsetException;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.clients.consumer.OffsetResetStrategy;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.KafkaFuture;
@@ -718,6 +717,11 @@ public class StreamThread extends Thread implements ProcessingThread {
         this.streamsUncaughtExceptionHandler = streamsUncaughtExceptionHandler;
         this.cacheResizer = cacheResizer;
         this.streamsAssignmentInterface = streamsAssignmentInterface;
+        if (streamsAssignmentInterface != null) {
+            streamsAssignmentInterface.setOnTasksRevokedCallback(this::onTasksRevoked);
+            streamsAssignmentInterface.setOnTasksAssignedCallback(this::onTasksAssigned);
+            streamsAssignmentInterface.setOnAllTasksLostCallback(this::onAllTasksLost);
+        }
         this.streamsMetadataState = streamsMetadataState;
 
         // The following sensors are created here but their references are not stored in this object, since within
@@ -1074,6 +1078,8 @@ public class StreamThread extends Thread implements ProcessingThread {
         final long startMs = time.milliseconds();
         now = startMs;
 
+        maybeHandleAssignmentFromStreamsRebalanceProtocol();
+
         final long pollLatency;
         taskManager.resumePollingForPartitionsWithAvailableSpace();
         pollLatency = pollPhase();
@@ -1404,23 +1410,59 @@ public class StreamThread extends Thread implements ProcessingThread {
             );
 
             // Process assignment from Streams Rebalance Protocol
-            final Assignment newAssignment = streamsAssignmentInterface.targetAssignment.get();
-            if (!newAssignment.equals(streamsAssignmentInterface.reconciledAssignment.get())) {
-
-                final Map<TaskId, Set<TopicPartition>> activeTasksWithPartitions =
-                    pairWithTopicPartitions(newAssignment.activeTasks.stream());
-                final Map<TaskId, Set<TopicPartition>> standbyTasksWithPartitions =
-                    pairWithTopicPartitions(Stream.concat(newAssignment.standbyTasks.stream(), newAssignment.warmupTasks.stream()));
+            streamsAssignmentInterface.processStreamsRebalanceEvents();
+        }
+    }
 
-                log.info("Processing new assignment {} from Streams Rebalance Protocol", newAssignment);
+    private Optional<Exception> onTasksRevoked(final Set<StreamsAssignmentInterface.TaskId> activeTasksToRevoke) {
+        try {
+            final Map<TaskId, Set<TopicPartition>> activeTasksToRevokeWithPartitions =
+                pairWithTopicPartitions(activeTasksToRevoke.stream());
+            final Set<TopicPartition> partitionsToRevoke = activeTasksToRevokeWithPartitions.values().stream()
+                .flatMap(Collection::stream)
+                .collect(Collectors.toSet());
 
-                taskManager.handleAssignment(
-                    activeTasksWithPartitions,
-                    standbyTasksWithPartitions
-                );
-                streamsAssignmentInterface.reconciledAssignment.set(newAssignment);
+            final long start = time.milliseconds();
+            try {
+                log.info("Revoking active tasks {}.", activeTasksToRevoke);
+                taskManager.handleRevocation(partitionsToRevoke);
+            } finally {
+                log.info("partition revocation took {} ms.", time.milliseconds() - start);
             }
+            if (state() != State.PENDING_SHUTDOWN) {
+                setState(State.PARTITIONS_REVOKED);
+            }
+        } catch (final Exception exception) {
+            return Optional.of(exception);
+        }
+        return Optional.empty();
+    }
+
+    private Optional<Exception> onTasksAssigned(final StreamsAssignmentInterface.Assignment assignment) {
+        try {
+            final Map<TaskId, Set<TopicPartition>> activeTasksWithPartitions =
+                pairWithTopicPartitions(assignment.activeTasks.stream());
+            final Map<TaskId, Set<TopicPartition>> standbyTasksWithPartitions =
+                pairWithTopicPartitions(Stream.concat(assignment.standbyTasks.stream(), assignment.warmupTasks.stream()));
+
+            log.info("Processing new assignment {} from Streams Rebalance Protocol", assignment);
+
+            taskManager.handleAssignment(activeTasksWithPartitions, standbyTasksWithPartitions);
+            setState(State.PARTITIONS_ASSIGNED);
+            taskManager.handleRebalanceComplete();
+        } catch (final Exception exception) {
+            return Optional.of(exception);
+        }
+        return Optional.empty();
+    }
+
+    private Optional<Exception> onAllTasksLost() {
+        try {
+            taskManager.handleLostAll();
+        } catch (final Exception exception) {
+            return Optional.of(exception);
         }
+        return Optional.empty();
     }
 
     static Map<TopicPartition, PartitionInfo> getTopicPartitionInfo(final Map<HostInfo, Set<TopicPartition>> partitionsByHost) {
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
index 49428724b1a..a2f504cab0f 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
@@ -52,8 +52,6 @@ public class StreamsRebalanceListener implements ConsumerRebalanceListener {
     @Override
     public void onPartitionsAssigned(final Collection<TopicPartition> partitions) {
 
-        streamThread.maybeHandleAssignmentFromStreamsRebalanceProtocol();
-
         // NB: all task management is already handled by:
         // org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.onAssignment
         if (assignmentErrorCode.get() == AssignorError.INCOMPLETE_SOURCE_TOPIC_METADATA.code()) {


(kafka) 15/42: Reslove conflicts from 11/25 rebase - Create assignment-related classes for streams groups

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 049aece0aa336fedfa56cc127c9d54d53bae891f
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Wed Jun 19 11:44:31 2024 +0200

    Reslove conflicts from 11/25 rebase - Create assignment-related classes for streams groups
    
    Translate from org.apache.kafka.coordinator.group.consumer package
    
    CurrentAssignmentBuilder
    
    TargetAssignmentBuilder
    
    See https://github.com/lucasbru/kafka/pull/23
    
    copy unit tests that can be preserved easily
---
 .../group/GroupCoordinatorRecordHelpers.java       | 335 +++++++--
 .../coordinator/group/streams/Assignment.java      |   7 +
 .../group/streams/CurrentAssignmentBuilder.java    | 374 ++++++++++
 .../coordinator/group/streams/MemberState.java     |  17 +-
 .../coordinator/group/streams/StreamsGroup.java    | 301 +++++---
 .../group/streams/StreamsGroupMember.java          |  63 +-
 .../coordinator/group/streams/StreamsTopology.java |  82 ++
 .../group/streams/SubscribedTopicMetadata.java     |  98 ---
 .../group/streams/TargetAssignmentBuilder.java     | 390 ++++++++++
 .../kafka/coordinator/group/streams/TopicIds.java  | 176 -----
 .../coordinator/group/streams/TopicMetadata.java   |  29 +-
 .../group/streams/TopologyMetadata.java            | 105 +++
 .../StreamsGroupCurrentMemberAssignmentKey.json    |   4 +-
 .../message/StreamsGroupMemberMetadataKey.json     |   4 +-
 .../common/message/StreamsGroupMetadataKey.json    |   2 +-
 .../message/StreamsGroupPartitionMetadataKey.json  |   2 +-
 .../StreamsGroupTargetAssignmentMemberKey.json     |   4 +-
 .../StreamsGroupTargetAssignmentMetadataKey.json   |   2 +-
 .../common/message/StreamsGroupTopologyKey.json    |   2 +-
 .../coordinator/group/AssignmentTestUtil.java      |  19 -
 .../coordinator/group/streams/AssignmentTest.java  |  22 +-
 .../streams/CurrentAssignmentBuilderTest.java      | 576 +++++++++++++++
 .../group/streams/StreamsGroupMemberTest.java      | 117 +--
 .../group/streams/StreamsGroupTest.java            |  68 +-
 .../group/streams/TargetAssignmentBuilderTest.java | 821 +++++++++++++++++++++
 .../group/streams/TaskAssignmentTestUtil.java      | 124 ++++
 26 files changed, 3133 insertions(+), 611 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index ea657361480..da399312e30 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -58,6 +58,8 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKe
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
@@ -80,8 +82,7 @@ import java.util.Set;
 import java.util.stream.Collectors;
 
 /**
- * This class contains helper methods to create records stored in
- * the __consumer_offsets topic.
+ * This class contains helper methods to create records stored in the __consumer_offsets topic.
  */
 @SuppressWarnings("ClassDataAbstractionCoupling")
 public class GroupCoordinatorRecordHelpers {
@@ -90,8 +91,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupMemberMetadata record.
      *
-     * @param groupId   The consumer group id.
-     * @param member    The consumer group member.
+     * @param groupId The consumer group id.
+     * @param member  The consumer group member.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupMemberSubscriptionRecord(
@@ -123,6 +124,28 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    /**
+     * Creates a ConsumerGroupMemberMetadata tombstone.
+     *
+     * @param groupId  The consumer group id.
+     * @param memberId The consumer group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newConsumerGroupMemberSubscriptionTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new ConsumerGroupMemberMetadataKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 5
+            ),
+            null // Tombstone.
+        );
+    }
+
     public static CoordinatorRecord newStreamsGroupMemberRecord(
         String groupId,
         StreamsGroupMember member
@@ -144,31 +167,39 @@ public class GroupCoordinatorRecordHelpers {
                     .setTopologyHash(member.topologyHash())
                     .setProcessId(member.processId())
                     .setHostInfo(member.hostInfo())
-                    .setClientTags(member.clientTags())
+                    .setClientTags(member.clientTags().entrySet().stream().map(e ->
+                        new StreamsGroupMemberMetadataValue.KeyValue()
+                            .setKey(e.getKey())
+                            .setValue(e.getValue())
+                    ).collect(Collectors.toList()))
                     .setUserData(member.userData())
-                    .setAssignmentConfigs(member.assignmentConfigs()),
-               (short) 0
+                    .setAssignmentConfigs(member.assignmentConfigs().entrySet().stream().map(e ->
+                        new StreamsGroupMemberMetadataValue.KeyValue()
+                            .setKey(e.getKey())
+                            .setValue(e.getValue())
+                    ).collect(Collectors.toList())),
+                (short) 0
             )
         );
     }
 
     /**
-     * Creates a ConsumerGroupMemberMetadata tombstone.
+     * Creates a StreamsGroupMemberMetadata tombstone.
      *
-     * @param groupId   The consumer group id.
-     * @param memberId  The consumer group member id.
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newConsumerGroupMemberSubscriptionTombstoneRecord(
+    public static CoordinatorRecord newStreamsMemberSubscriptionTombstoneRecord(
         String groupId,
         String memberId
     ) {
         return new CoordinatorRecord(
             new ApiMessageAndVersion(
-                new ConsumerGroupMemberMetadataKey()
+                new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 5
+                (short) 11
             ),
             null // Tombstone.
         );
@@ -177,8 +208,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupPartitionMetadata record.
      *
-     * @param groupId                   The consumer group id.
-     * @param newSubscriptionMetadata   The subscription metadata.
+     * @param groupId                 The consumer group id.
+     * @param newSubscriptionMetadata The subscription metadata.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupSubscriptionMetadataRecord(
@@ -210,7 +241,7 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupPartitionMetadata tombstone.
      *
-     * @param groupId   The consumer group id.
+     * @param groupId The consumer group id.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupSubscriptionMetadataTombstoneRecord(
@@ -226,6 +257,69 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    /**
+     * Creates a StreamsGroupPartitionMetadata record.
+     *
+     * @param groupId                 The streams group id.
+     * @param newSubscriptionMetadata The subscription metadata.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupSubscriptionMetadataRecord(
+        String groupId,
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newSubscriptionMetadata
+    ) {
+        StreamsGroupPartitionMetadataValue value = new StreamsGroupPartitionMetadataValue();
+        newSubscriptionMetadata.forEach((topicName, topicMetadata) -> {
+            List<StreamsGroupPartitionMetadataValue.PartitionMetadata> partitionMetadata = new ArrayList<>();
+            // If the partition rack information map is empty, store an empty list in the record.
+            if (!topicMetadata.partitionRacks().isEmpty()) {
+                topicMetadata.partitionRacks().forEach((partition, racks) ->
+                    partitionMetadata.add(new StreamsGroupPartitionMetadataValue.PartitionMetadata()
+                        .setPartition(partition)
+                        .setRacks(new ArrayList<>(racks))
+                    )
+                );
+            }
+            value.topics().add(new StreamsGroupPartitionMetadataValue.TopicMetadata()
+                .setTopicId(topicMetadata.id())
+                .setTopicName(topicMetadata.name())
+                .setNumPartitions(topicMetadata.numPartitions())
+                .setPartitionMetadata(partitionMetadata)
+            );
+        });
+
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupPartitionMetadataKey()
+                    .setGroupId(groupId),
+                (short) 10
+            ),
+            new ApiMessageAndVersion(
+                value,
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupPartitionMetadata tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupSubscriptionMetadataTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupPartitionMetadataKey()
+                    .setGroupId(groupId),
+                (short) 10
+            ),
+            null // Tombstone.
+        );
+    }
+
     /**
      * Creates a ConsumerGroupMetadata record.
      *
@@ -251,6 +345,25 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    /**
+     * Creates a ConsumerGroupMetadata tombstone.
+     *
+     * @param groupId The consumer group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newGroupEpochTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new ConsumerGroupMetadataKey()
+                    .setGroupId(groupId),
+                (short) 3
+            ),
+            null // Tombstone.
+        );
+    }
+
     public static CoordinatorRecord newStreamsGroupEpochRecord(
         String groupId,
         int newGroupEpoch
@@ -270,9 +383,28 @@ public class GroupCoordinatorRecordHelpers {
     }
 
     /**
-     * Creates a ConsumerGroupMetadata tombstone.
+     * Creates a StreamsGroupMetadata tombstone.
      *
-     * @param groupId   The consumer group id.
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupEpochTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataKey()
+                    .setGroupId(groupId),
+                (short) 9
+            ),
+            null // Tombstone.
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupMetadata tombstone.
+     *
+     * @param groupId The streams group id.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupEpochTombstoneRecord(
@@ -291,9 +423,9 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupTargetAssignmentMember record.
      *
-     * @param groupId       The consumer group id.
-     * @param memberId      The consumer group member id.
-     * @param partitions    The target partitions of the member.
+     * @param groupId    The consumer group id.
+     * @param memberId   The consumer group member id.
+     * @param partitions The target partitions of the member.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupTargetAssignmentRecord(
@@ -327,7 +459,29 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newTargetAssignmentRecord(
+    /**
+     * Creates a ConsumerGroupTargetAssignmentMember tombstone.
+     *
+     * @param groupId  The consumer group id.
+     * @param memberId The consumer group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newTargetAssignmentTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new ConsumerGroupTargetAssignmentMemberKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 7
+            ),
+            null // Tombstone.
+        );
+    }
+
+    public static CoordinatorRecord newStreamsTargetAssignmentRecord(
         String groupId,
         String memberId,
         Map<String, Set<Integer>> activeTasks,
@@ -377,22 +531,22 @@ public class GroupCoordinatorRecordHelpers {
     }
 
     /**
-     * Creates a ConsumerGroupTargetAssignmentMember tombstone.
+     * Creates a StreamsGroupTargetAssignmentMember tombstone.
      *
-     * @param groupId       The consumer group id.
-     * @param memberId      The consumer group member id.
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newConsumerGroupTargetAssignmentTombstoneRecord(
+    public static CoordinatorRecord newStreamsTargetAssignmentTombstoneRecord(
         String groupId,
         String memberId
     ) {
         return new CoordinatorRecord(
             new ApiMessageAndVersion(
-                new ConsumerGroupTargetAssignmentMemberKey()
+                new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 7
+                (short) 13
             ),
             null // Tombstone.
         );
@@ -401,8 +555,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupTargetAssignmentMetadata record.
      *
-     * @param groupId           The consumer group id.
-     * @param assignmentEpoch   The consumer group epoch.
+     * @param groupId         The consumer group id.
+     * @param assignmentEpoch The consumer group epoch.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupTargetAssignmentEpochRecord(
@@ -423,6 +577,26 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    /**
+     * Creates a ConsumerGroupTargetAssignmentMetadata tombstone.
+     *
+     * @param groupId The consumer group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newConsumerTargetAssignmentEpochTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new ConsumerGroupTargetAssignmentMetadataKey()
+                    .setGroupId(groupId),
+                (short) 6
+            ),
+            null // Tombstone.
+        );
+    }
+
+
     public static CoordinatorRecord newStreamsTargetAssignmentEpochRecord(
         String groupId,
         int assignmentEpoch
@@ -442,19 +616,19 @@ public class GroupCoordinatorRecordHelpers {
     }
 
     /**
-     * Creates a ConsumerGroupTargetAssignmentMetadata tombstone.
+     * Creates a StreamsGroupTargetAssignmentMetadata tombstone.
      *
-     * @param groupId   The consumer group id.
+     * @param groupId The streams group id.
      * @return The record.
      */
-    public static CoordinatorRecord newConsumerGroupTargetAssignmentEpochTombstoneRecord(
+    public static CoordinatorRecord newStreamsTargetAssignmentEpochTombstoneRecord(
         String groupId
     ) {
         return new CoordinatorRecord(
             new ApiMessageAndVersion(
-                new ConsumerGroupTargetAssignmentMetadataKey()
+                new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 6
+                (short) 12
             ),
             null // Tombstone.
         );
@@ -463,8 +637,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a ConsumerGroupCurrentMemberAssignment record.
      *
-     * @param groupId   The consumer group id.
-     * @param member    The consumer group member.
+     * @param groupId The consumer group id.
+     * @param member  The consumer group member.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupCurrentAssignmentRecord(
@@ -490,7 +664,29 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newCurrentAssignmentRecord(
+    /**
+     * Creates a ConsumerGroupCurrentMemberAssignment tombstone.
+     *
+     * @param groupId  The consumer group id.
+     * @param memberId The consumer group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newCurrentAssignmentTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new ConsumerGroupCurrentMemberAssignmentKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 8
+            ),
+            null // Tombstone
+        );
+    }
+
+    public static CoordinatorRecord newStreamsCurrentAssignmentRecord(
         String groupId,
         StreamsGroupMember member
     ) {
@@ -570,6 +766,28 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    /**
+     * Creates a StreamsGroupCurrentMemberAssignment tombstone.
+     *
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsCurrentAssignmentTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 14
+            ),
+            null // Tombstone
+        );
+    }
+
     /**
      * Creates a ConsumerGroupRegularExpression tombstone.
      *
@@ -595,9 +813,9 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a GroupMetadata record.
      *
-     * @param group              The classic group.
-     * @param assignment         The classic group assignment.
-     * @param metadataVersion    The metadata version.
+     * @param group           The classic group.
+     * @param assignment      The classic group assignment.
+     * @param metadataVersion The metadata version.
      * @return The record.
      */
     public static CoordinatorRecord newGroupMetadataRecord(
@@ -653,7 +871,7 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a GroupMetadata tombstone.
      *
-     * @param groupId  The group id.
+     * @param groupId The group id.
      * @return The record.
      */
     public static CoordinatorRecord newGroupMetadataTombstoneRecord(
@@ -672,8 +890,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates an empty GroupMetadata record.
      *
-     * @param group              The classic group.
-     * @param metadataVersion    The metadata version.
+     * @param group           The classic group.
+     * @param metadataVersion The metadata version.
      * @return The record.
      */
     public static CoordinatorRecord newEmptyGroupMetadataRecord(
@@ -742,9 +960,9 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates an OffsetCommit tombstone record.
      *
-     * @param groupId           The group id.
-     * @param topic             The topic name.
-     * @param partitionId       The partition id.
+     * @param groupId     The group id.
+     * @param topic       The topic name.
+     * @param partitionId The partition id.
      * @return The record.
      */
     public static CoordinatorRecord newOffsetCommitTombstoneRecord(
@@ -1108,8 +1326,8 @@ public class GroupCoordinatorRecordHelpers {
     /**
      * Creates a StreamsTopology record.
      *
-     * @param groupId                   The consumer group id.
-     * @param subtopologies             The subtopologies in the new topology.
+     * @param groupId       The consumer group id.
+     * @param subtopologies The subtopologies in the new topology.
      * @return The record.
      */
     public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
@@ -1141,4 +1359,23 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(value, (short) 0));
     }
 
+    /**
+     * Creates a StreamsGroupTopology tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupTopologyRecordTombstone(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyKey()
+                    .setGroupId(groupId),
+                (short) 15
+            ),
+            null // Tombstone
+        );
+    }
+
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
index b80e34cbfe5..17d94499d4c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -40,6 +40,13 @@ public class Assignment {
     private final Map<String, Set<Integer>> standbyTasks;
     private final Map<String, Set<Integer>> warmupTasks;
 
+    // TODO: Tests using this constructor probably should be extended to cover standby tasks
+    public Assignment(final Map<String, Set<Integer>> activeTasks) {
+        this.activeTasks = Collections.unmodifiableMap(Objects.requireNonNull(activeTasks));
+        this.standbyTasks = Collections.emptyMap();
+        this.warmupTasks = Collections.emptyMap();
+    }
+
     public Assignment(final Map<String, Set<Integer>> activeTasks,
                       final Map<String, Set<Integer>> standbyTasks,
                       final Map<String, Set<Integer>> warmupTasks) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
new file mode 100644
index 00000000000..30813ba5c13
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -0,0 +1,374 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.BiFunction;
+
+/**
+ * The CurrentAssignmentBuilder class encapsulates the reconciliation engine of the streams group protocol. Given the current state of a
+ * member and a desired or target assignment state, the state machine takes the necessary steps to converge them.
+ */
+public class CurrentAssignmentBuilder {
+
+    /**
+     * The streams group member which is reconciled.
+     */
+    private final StreamsGroupMember member;
+
+    /**
+     * The target assignment epoch.
+     */
+    private int targetAssignmentEpoch;
+
+    /**
+     * The target assignment.
+     */
+    private org.apache.kafka.coordinator.group.streams.Assignment targetAssignment;
+
+    /**
+     * A function which returns the current epoch of a topic-partition or -1 if the topic-partition is not assigned. The current epoch is
+     * the epoch of the current owner.
+     */
+    private BiFunction<String, Integer, Integer> currentPartitionEpoch;
+
+    /**
+     * The active tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     */
+    private List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks;
+
+    /**
+     * The standby tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     */
+    private List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks;
+
+    /**
+     * The warmup tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     */
+    private List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks;
+
+    /**
+     * Constructs the CurrentAssignmentBuilder based on the current state of the provided streams group member.
+     *
+     * @param member The streams group member that must be reconciled.
+     */
+    public CurrentAssignmentBuilder(StreamsGroupMember member) {
+        this.member = Objects.requireNonNull(member);
+    }
+
+    /**
+     * Sets the target assignment epoch and the target assignment that the streams group member must be reconciled to.
+     *
+     * @param targetAssignmentEpoch The target assignment epoch.
+     * @param targetAssignment      The target assignment.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withTargetAssignment(
+        int targetAssignmentEpoch,
+        Assignment targetAssignment
+    ) {
+        this.targetAssignmentEpoch = targetAssignmentEpoch;
+        this.targetAssignment = Objects.requireNonNull(targetAssignment);
+        return this;
+    }
+
+    /**
+     * Sets a BiFunction which allows to retrieve the current epoch of a partition. This is used by the state machine to determine if a
+     * partition is free or still used by another member.
+     *
+     * @param currentPartitionEpoch A BiFunction which gets the epoch of a topic id / tasks id pair.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withCurrentPartitionEpoch(
+        BiFunction<String, Integer, Integer> currentPartitionEpoch
+    ) {
+        this.currentPartitionEpoch = Objects.requireNonNull(currentPartitionEpoch);
+        return this;
+    }
+
+    /**
+     * Sets the active tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * determine if the member has revoked the necessary tasks.
+     *
+     * @param ownedActiveTasks A list of topic-tasks.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withOwnedActiveTasks(
+        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks
+    ) {
+        this.ownedActiveTasks = ownedActiveTasks;
+        return this;
+    }
+
+    /**
+     * Sets the standby tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * determine if the member has revoked the necessary tasks.
+     *
+     * @param ownedStandbyTasks A list of topic-tasks.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withOwnedStandbyTasks(
+        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks
+    ) {
+        this.ownedStandbyTasks = ownedStandbyTasks;
+        return this;
+    }
+
+    /**
+     * Sets the warmup tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * determine if the member has revoked the necessary tasks.
+     *
+     * @param ownedWarmupTasks A list of topic-tasks.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withOwnedWarmupTasks(
+        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks
+    ) {
+        this.ownedWarmupTasks = ownedWarmupTasks;
+        return this;
+    }
+
+
+    /**
+     * Builds the next state for the member or keep the current one if it is not possible to move forward with the current state.
+     *
+     * @return A new StreamsGroupMember or the current one.
+     */
+    public StreamsGroupMember build() {
+        switch (member.state()) {
+            case STABLE:
+                // When the member is in the STABLE state, we verify if a newer
+                // epoch (or target assignment) is available. If it is, we can
+                // reconcile the member towards it. Otherwise, we return.
+                if (member.memberEpoch() != targetAssignmentEpoch) {
+                    return computeNextAssignment(
+                        member.memberEpoch(),
+                        member.assignedActiveTasks(),
+                        member.assignedStandbyTasks(),
+                        member.assignedWarmupTasks()
+                    );
+                } else {
+                    return member;
+                }
+
+            case UNREVOKED_TASKS:
+                // When the member is in the UNREVOKED_TASKS state, we wait
+                // until the member has revoked the necessary tasks. They are
+                // considered revoked when they are not anymore reported in the
+                // owned tasks set in the StreamsHeartbeat API.
+
+                // If the member provides its owned tasks. We verify if it still
+                // owns any of the revoked tasks. If it does, we cannot progress.
+                if (ownsRevokedTasks(member.activeTasksPendingRevocation())) {
+                    return member;
+                }
+
+                // When the member has revoked all the pending tasks, it can
+                // transition to the next epoch (current + 1) and we can reconcile
+                // its state towards the latest target assignment.
+                return computeNextAssignment(
+                    member.memberEpoch() + 1,
+                    member.assignedActiveTasks(),
+                    member.assignedStandbyTasks(),
+                    member.assignedWarmupTasks()
+                );
+
+            case UNRELEASED_TASKS:
+                // When the member is in the UNRELEASED_TASKS, we reconcile the
+                // member towards the latest target assignment. This will assign any
+                // of the unreleased tasks when they become available.
+                return computeNextAssignment(
+                    member.memberEpoch(),
+                    member.assignedActiveTasks(),
+                    member.assignedStandbyTasks(),
+                    member.assignedWarmupTasks()
+                );
+
+            case UNKNOWN:
+                // We could only end up in this state if a new state is added in the
+                // future and the group coordinator is downgraded. In this case, the
+                // best option is to fence the member to force it to rejoin the group
+                // without any tasks and to reconcile it again from scratch.
+                if (ownedActiveTasks == null || !ownedActiveTasks.isEmpty()) {
+                    throw new FencedMemberEpochException("The streams group member is in a unknown state. "
+                        + "The member must abandon all its tasks and rejoin.");
+                }
+
+                return computeNextAssignment(
+                    targetAssignmentEpoch,
+                    member.assignedActiveTasks(),
+                    member.assignedStandbyTasks(),
+                    member.assignedWarmupTasks()
+                );
+        }
+
+        return member;
+    }
+
+    /**
+     * Decides whether the current ownedTopicTasks contains any partition that is pending revocation.
+     *
+     * @param assignment The assignment that has the tasks pending revocation.
+     * @return A boolean based on the condition mentioned above.
+     */
+    private boolean ownsRevokedTasks(
+        Map<String, Set<Integer>> assignment
+    ) {
+        if (ownedActiveTasks == null) {
+            return true;
+        }
+
+        for (StreamsHeartbeatRequestData.TaskIds activeTasks : ownedActiveTasks) {
+            Set<Integer> tasksPendingRevocation =
+                assignment.getOrDefault(activeTasks.subtopology(), Collections.emptySet());
+
+            for (Integer partitionId : activeTasks.partitions()) {
+                if (tasksPendingRevocation.contains(partitionId)) {
+                    return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * Computes the next assignment.
+     *
+     * @param memberEpoch                The epoch of the member to use. This may be different from the epoch in
+     *                                   {@link CurrentAssignmentBuilder#member}.
+     * @param memberAssignedActiveTasks  The assigned active tasks of the member to use.
+     * @param memberAssignedStandbyTasks The assigned standby tasks of the member to use.
+     * @param memberAssignedWarmupTasks  The assigned warmup tasks of the member to use.
+     * @return A new StreamsGroupMember.
+     */
+    private StreamsGroupMember computeNextAssignment(
+        int memberEpoch,
+        Map<String, Set<Integer>> memberAssignedActiveTasks,
+        Map<String, Set<Integer>> memberAssignedStandbyTasks,
+        Map<String, Set<Integer>> memberAssignedWarmupTasks
+    ) {
+        boolean hasUnreleasedTasks = false;
+        Map<String, Set<Integer>> newAssignedTasks = new HashMap<>();
+        Map<String, Set<Integer>> newTasksPendingRevocation = new HashMap<>();
+        Map<String, Set<Integer>> newTasksPendingAssignment = new HashMap<>();
+
+        Set<String> allSubtopologyIds = new HashSet<>(targetAssignment.activeTasks().keySet());
+        allSubtopologyIds.addAll(memberAssignedActiveTasks.keySet());
+
+        for (String subtopologyId : allSubtopologyIds) {
+            Set<Integer> target = targetAssignment.activeTasks()
+                .getOrDefault(subtopologyId, Collections.emptySet());
+            Set<Integer> currentAssignedTasks = memberAssignedActiveTasks
+                .getOrDefault(subtopologyId, Collections.emptySet());
+
+            // New Assigned Tasks = Previous Assigned Tasks ∩ Target
+            Set<Integer> assignedTasks = new HashSet<>(currentAssignedTasks);
+            assignedTasks.retainAll(target);
+
+            // Tasks Pending Revocation = Previous Assigned Tasks - New Assigned Tasks
+            Set<Integer> tasksPendingRevocation = new HashSet<>(currentAssignedTasks);
+            tasksPendingRevocation.removeAll(assignedTasks);
+
+            // Tasks Pending Assignment = Target - New Assigned Tasks - Unreleased Tasks
+            Set<Integer> tasksPendingAssignment = new HashSet<>(target);
+            tasksPendingAssignment.removeAll(assignedTasks);
+            hasUnreleasedTasks = tasksPendingAssignment.removeIf(partitionId ->
+                currentPartitionEpoch.apply(subtopologyId, partitionId) != -1
+            ) || hasUnreleasedTasks;
+
+            if (!assignedTasks.isEmpty()) {
+                newAssignedTasks.put(subtopologyId, assignedTasks);
+            }
+
+            if (!tasksPendingRevocation.isEmpty()) {
+                newTasksPendingRevocation.put(subtopologyId, tasksPendingRevocation);
+            }
+
+            if (!tasksPendingAssignment.isEmpty()) {
+                newTasksPendingAssignment.put(subtopologyId, tasksPendingAssignment);
+            }
+        }
+
+        if (!newTasksPendingRevocation.isEmpty() && ownsRevokedTasks(newTasksPendingRevocation)) {
+            // If there are tasks to be revoked, the member remains in its current
+            // epoch and requests the revocation of those tasks. It transitions to
+            // the UNREVOKED_TASKS state to wait until the client acknowledges the
+            // revocation of the tasks.
+            return new StreamsGroupMember.Builder(member)
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .updateMemberEpoch(memberEpoch)
+                .setAssignedActiveTasks(newAssignedTasks)
+                .setActiveTasksPendingRevocation(newTasksPendingRevocation)
+                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
+                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .build();
+        } else if (!newTasksPendingAssignment.isEmpty()) {
+            // If there are tasks to be assigned, the member transitions to the
+            // target epoch and requests the assignment of those tasks. Note that
+            // the tasks are directly added to the assigned tasks set. The
+            // member transitions to the STABLE state or to the UNRELEASED_TASKS
+            // state depending on whether there are unreleased tasks or not.
+            newTasksPendingAssignment.forEach((subtopologyId, tasks) -> newAssignedTasks
+                .computeIfAbsent(subtopologyId, __ -> new HashSet<>())
+                .addAll(tasks));
+            org.apache.kafka.coordinator.group.streams.MemberState newState =
+                hasUnreleasedTasks ? org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS
+                    : org.apache.kafka.coordinator.group.streams.MemberState.STABLE;
+            return new StreamsGroupMember.Builder(member)
+                .setState(newState)
+                .updateMemberEpoch(targetAssignmentEpoch)
+                .setAssignedActiveTasks(newAssignedTasks)
+                .setActiveTasksPendingRevocation(Collections.emptyMap())
+                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
+                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .build();
+        } else if (hasUnreleasedTasks) {
+            // If there are no tasks to be revoked nor to be assigned but some
+            // tasks are not available yet, the member transitions to the target
+            // epoch, to the UNRELEASED_TASKS state and waits.
+            return new StreamsGroupMember.Builder(member)
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .updateMemberEpoch(targetAssignmentEpoch)
+                .setAssignedActiveTasks(newAssignedTasks)
+                .setActiveTasksPendingRevocation(Collections.emptyMap())
+                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
+                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .build();
+        } else {
+            // Otherwise, the member transitions to the target epoch and to the
+            // STABLE state.
+            return new StreamsGroupMember.Builder(member)
+                .setState(MemberState.STABLE)
+                .updateMemberEpoch(targetAssignmentEpoch)
+                .setAssignedActiveTasks(newAssignedTasks)
+                .setActiveTasksPendingRevocation(Collections.emptyMap())
+                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
+                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .build();
+        }
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
index 53518e61934..f9ccb8f2ebc 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
@@ -20,8 +20,8 @@ import java.util.HashMap;
 import java.util.Map;
 
 /**
- * The various states that a member can be in. For their definition,
- * refer to the documentation of {{@link org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder}}.
+ * The various states that a member can be in. For their definition, refer to the documentation of
+ * {{@link org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder}}.
  */
 public enum MemberState {
 
@@ -31,28 +31,25 @@ public enum MemberState {
     STABLE((byte) 1),
 
     /**
-     * The member must revoke some tasks in order to be able to
-     * transition to the next epoch.
+     * The member must revoke some tasks in order to be able to transition to the next epoch.
      */
     UNREVOKED_TASKS((byte) 2),
 
     /**
-     * The member transitioned to the last epoch but waits on some
-     * tasks which have not been revoked by their previous
-     * owners yet.
+     * The member transitioned to the last epoch but waits on some tasks which have not been revoked by their previous owners yet.
      */
     UNRELEASED_TASKS((byte) 3),
 
     /**
-     * The member is in an unknown state. This can only happen if a future
-     * version of the software introduces a new state unknown by this version.
+     * The member is in an unknown state. This can only happen if a future version of the software introduces a new state unknown by this
+     * version.
      */
     UNKNOWN((byte) 127);
 
     private final static Map<Byte, MemberState> VALUES_TO_ENUMS = new HashMap<>();
 
     static {
-        for (MemberState state: MemberState.values()) {
+        for (MemberState state : MemberState.values()) {
             VALUES_TO_ENUMS.put(state.value(), state);
         }
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index d28e9218994..4ba97bc2288 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -29,7 +29,6 @@ import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
-import org.apache.kafka.coordinator.group.assignor.SubscriptionType;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.image.ClusterImage;
 import org.apache.kafka.image.TopicImage;
@@ -50,16 +49,13 @@ import java.util.Optional;
 import java.util.Set;
 
 import static java.util.Collections.emptyMap;
-import static org.apache.kafka.coordinator.group.assignor.SubscriptionType.HETEROGENEOUS;
-import static org.apache.kafka.coordinator.group.assignor.SubscriptionType.HOMOGENEOUS;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.ASSIGNING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.EMPTY;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.RECONCILING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.STABLE;
 
 /**
- * A Streams Group. All the metadata in this class are backed by
- * records in the __consumer_offsets partitions.
+ * A Streams Group. All the metadata in this class are backed by records in the __consumer_offsets partitions.
  */
 public class StreamsGroup implements Group {
 
@@ -90,6 +86,7 @@ public class StreamsGroup implements Group {
     }
 
     public static class DeadlineAndEpoch {
+
         static final DeadlineAndEpoch EMPTY = new DeadlineAndEpoch(0L, 0);
 
         public final long deadlineMs;
@@ -117,9 +114,8 @@ public class StreamsGroup implements Group {
     private final TimelineObject<StreamsGroupState> state;
 
     /**
-     * The group epoch. The epoch is incremented whenever the subscriptions
-     * are updated and it will trigger the computation of a new assignment
-     * for the group.
+     * The group epoch. The epoch is incremented whenever the subscriptions are updated and it will trigger the computation of a new
+     * assignment for the group.
      */
     private final TimelineInteger groupEpoch;
 
@@ -139,9 +135,13 @@ public class StreamsGroup implements Group {
     private final TimelineHashMap<String, Integer> assignors;
 
     /**
-     * The target assignment epoch. An assignment epoch smaller than the group epoch
-     * means that a new assignment is required. The assignment epoch is updated when
-     * a new assignment is installed.
+     * The metadata associated with each subscribed topic name.
+     */
+    private final TimelineHashMap<String, TopicMetadata> subscribedTopicMetadata;
+
+    /**
+     * The target assignment epoch. An assignment epoch smaller than the group epoch means that a new assignment is required. The assignment
+     * epoch is updated when a new assignment is installed.
      */
     private final TimelineInteger targetAssignmentEpoch;
 
@@ -151,17 +151,15 @@ public class StreamsGroup implements Group {
     private final TimelineHashMap<String, Assignment> targetAssignment;
 
     /**
-     * Reverse lookup map representing tasks with
-     * their current member assignments.
+     * Reverse lookup map representing tasks with their current member assignments.
      */
     private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetActiveTasksAssignment;
     private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetStandbyTasksAssignment;
     private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetWarmupTasksAssignment;
 
     /**
-     * The current partition epoch maps each topic-partitions to their current epoch where
-     * the epoch is the epoch of their owners. When a member revokes a partition, it removes
-     * its epochs from this map. When a member gets a partition, it adds its epochs to this map.
+     * The current partition epoch maps each topic-partitions to their current epoch where the epoch is the epoch of their owners. When a
+     * member revokes a partition, it removes its epochs from this map. When a member gets a partition, it adds its epochs to this map.
      */
     private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentActiveTasksEpoch;
     private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentStandbyTasksEpoch;
@@ -173,14 +171,16 @@ public class StreamsGroup implements Group {
     private final GroupCoordinatorMetricsShard metrics;
 
     /**
-     * The metadata refresh deadline. It consists of a timestamp in milliseconds together with
-     * the group epoch at the time of setting it. The metadata refresh time is considered as a
-     * soft state (read that it is not stored in a timeline data structure). It is like this
-     * because it is not persisted to the log. The group epoch is here to ensure that the
-     * metadata refresh deadline is invalidated if the group epoch does not correspond to
-     * the current group epoch. This can happen if the metadata refresh deadline is updated
-     * after having refreshed the metadata but the write operation failed. In this case, the
-     * time is not automatically rolled back.
+     * The Streams topology.
+     */
+    private final StreamsTopology topology;
+
+    /**
+     * The metadata refresh deadline. It consists of a timestamp in milliseconds together with the group epoch at the time of setting it.
+     * The metadata refresh time is considered as a soft state (read that it is not stored in a timeline data structure). It is like this
+     * because it is not persisted to the log. The group epoch is here to ensure that the metadata refresh deadline is invalidated if the
+     * group epoch does not correspond to the current group epoch. This can happen if the metadata refresh deadline is updated after having
+     * refreshed the metadata but the write operation failed. In this case, the time is not automatically rolled back.
      */
     private DeadlineAndEpoch metadataRefreshDeadline = DeadlineAndEpoch.EMPTY;
 
@@ -196,6 +196,7 @@ public class StreamsGroup implements Group {
         this.members = new TimelineHashMap<>(snapshotRegistry, 0);
         this.staticMembers = new TimelineHashMap<>(snapshotRegistry, 0);
         this.assignors = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.subscribedTopicMetadata = new TimelineHashMap<>(snapshotRegistry, 0);
         this.targetAssignmentEpoch = new TimelineInteger(snapshotRegistry);
         this.targetAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
         this.invertedTargetActiveTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
@@ -205,6 +206,7 @@ public class StreamsGroup implements Group {
         this.currentStandbyTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
         this.currentWarmupTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
         this.metrics = Objects.requireNonNull(metrics);
+        this.topology = null; // TODO
     }
 
     /**
@@ -241,6 +243,10 @@ public class StreamsGroup implements Group {
             .setGroupType(type().toString());
     }
 
+    public StreamsTopology topology() {
+        return topology;
+    }
+
     /**
      * @return The group id.
      */
@@ -298,11 +304,9 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Get member id of a static member that matches the given group
-     * instance id.
+     * Get member id of a static member that matches the given group instance id.
      *
      * @param groupInstanceId The group instance id.
-     *
      * @return The member id corresponding to the given instance id or null if it does not exist
      */
     public String staticMemberId(String groupInstanceId) {
@@ -310,13 +314,11 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Gets or creates a new member but without adding it to the group. Adding a member
-     * is done via the {@link StreamsGroup#updateMember(StreamsGroupMember)} method.
+     * Gets or creates a new member but without adding it to the group. Adding a member is done via the
+     * {@link StreamsGroup#updateMember(StreamsGroupMember)} method.
      *
      * @param memberId          The member id.
-     * @param createIfNotExists Booleans indicating whether the member must be
-     *                          created if it does not exist.
-     *
+     * @param createIfNotExists Booleans indicating whether the member must be created if it does not exist.
      * @return A StreamsGroupMember.
      */
     public StreamsGroupMember getOrMaybeCreateMember(
@@ -324,7 +326,9 @@ public class StreamsGroup implements Group {
         boolean createIfNotExists
     ) {
         StreamsGroupMember member = members.get(memberId);
-        if (member != null) return member;
+        if (member != null) {
+            return member;
+        }
 
         if (!createIfNotExists) {
             throw new UnknownMemberIdException(
@@ -339,7 +343,6 @@ public class StreamsGroup implements Group {
      * Gets a static member.
      *
      * @param instanceId The group instance id.
-     *
      * @return The member corresponding to the given instance id or null if it does not exist
      */
     public StreamsGroupMember staticMember(String instanceId) {
@@ -401,7 +404,6 @@ public class StreamsGroup implements Group {
      * Returns true if the member exists.
      *
      * @param memberId The member id.
-     *
      * @return A boolean indicating whether the member exists or not.
      */
     public boolean hasMember(String memberId) {
@@ -432,16 +434,14 @@ public class StreamsGroup implements Group {
     /**
      * Returns the target assignment of the member.
      *
-     * @return The StreamsGroupMemberAssignment or an EMPTY one if it does not
-     *         exist.
+     * @return The StreamsGroupMemberAssignment or an EMPTY one if it does not exist.
      */
     public Assignment targetAssignment(String memberId) {
         return targetAssignment.getOrDefault(memberId, Assignment.EMPTY);
     }
 
     /**
-     * @return An immutable map containing all the topic partitions
-     *         with their current member assignments.
+     * @return An immutable map containing all the topic partitions with their current member assignments.
      */
     public Map<String, Map<Integer, String>> invertedTargetActiveTasksAssignment() {
         return Collections.unmodifiableMap(invertedTargetActiveTasksAssignment);
@@ -488,8 +488,8 @@ public class StreamsGroup implements Group {
     /**
      * Updates the target assignment of a member.
      *
-     * @param memberId              The member id.
-     * @param newTargetAssignment   The new target assignment.
+     * @param memberId            The member id.
+     * @param newTargetAssignment The new target assignment.
      */
     public void updateTargetAssignment(String memberId, Assignment newTargetAssignment) {
         updateInvertedTargetActiveTasksAssignment(
@@ -553,9 +553,9 @@ public class StreamsGroup implements Group {
     /**
      * Updates the reverse lookup map of the target assignment.
      *
-     * @param memberId              The member Id.
-     * @param oldTargetAssignment   The old target assignment.
-     * @param newTargetAssignment   The new target assignment.
+     * @param memberId            The member Id.
+     * @param oldTargetAssignment The old target assignment.
+     * @param newTargetAssignment The new target assignment.
      */
     private void updateInvertedTargetAssignment(
         String memberId,
@@ -633,12 +633,10 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Returns the current epoch of a partition or -1 if the partition
-     * does not have one.
-     *
-     * @param topicId       The topic id.
-     * @param partitionId   The partition id.
+     * Returns the current epoch of a partition or -1 if the partition does not have one.
      *
+     * @param topicId     The topic id.
+     * @param partitionId The partition id.
      * @return The epoch or -1.
      */
     public int currentActiveTaskEpoch(
@@ -652,6 +650,108 @@ public class StreamsGroup implements Group {
         }
     }
 
+    /**
+     * Compute the preferred (server side) assignor for the group while taking into account the updated member. The computation relies on
+     * {{@link StreamsGroup#assignors}} persisted structure but it does not update it.
+     *
+     * @param oldMember The old member.
+     * @param newMember The new member.
+     * @return An Optional containing the preferred assignor.
+     */
+    public Optional<String> computePreferredServerAssignor(
+        StreamsGroupMember oldMember,
+        StreamsGroupMember newMember
+    ) {
+        // Copy the current count and update it.
+        Map<String, Integer> counts = new HashMap<>(this.assignors);
+        maybeUpdateAssignors(counts, oldMember, newMember);
+
+        return counts.entrySet().stream()
+            .max(Map.Entry.comparingByValue())
+            .map(Map.Entry::getKey);
+    }
+
+    /**
+     * @return The preferred assignor for the group.
+     */
+    public Optional<String> preferredServerAssignor() {
+        return preferredServerAssignor(Long.MAX_VALUE);
+    }
+
+    /**
+     * @return The preferred assignor for the group with given offset.
+     */
+    public Optional<String> preferredServerAssignor(long committedOffset) {
+        return assignors.entrySet(committedOffset).stream()
+            .max(Map.Entry.comparingByValue())
+            .map(Map.Entry::getKey);
+    }
+
+    /**
+     * @return An immutable Map of subscription metadata for each topic that the consumer group is subscribed to.
+     */
+    public Map<String, TopicMetadata> subscriptionMetadata() {
+        return Collections.unmodifiableMap(subscribedTopicMetadata);
+    }
+
+    /**
+     * Updates the subscription metadata. This replaces the previous one.
+     *
+     * @param subscriptionMetadata The new subscription metadata.
+     */
+    public void setSubscriptionMetadata(
+        Map<String, TopicMetadata> subscriptionMetadata
+    ) {
+        this.subscribedTopicMetadata.clear();
+        this.subscribedTopicMetadata.putAll(subscriptionMetadata);
+    }
+
+    /**
+     * Computes the subscription metadata based on the current subscription info.
+     *
+     * @param subscribedTopicNames Map of topic names to the number of subscribers.
+     * @param topicsImage          The current metadata for all available topics.
+     * @param clusterImage         The current metadata for the Kafka cluster.
+     * @return An immutable map of subscription metadata for each topic that the consumer group is subscribed to.
+     */
+    public Map<String, TopicMetadata> computeSubscriptionMetadata(
+        Map<String, Integer> subscribedTopicNames,
+        TopicsImage topicsImage,
+        ClusterImage clusterImage
+    ) {
+        // Create the topic metadata for each subscribed topic.
+        Map<String, TopicMetadata> newSubscriptionMetadata = new HashMap<>(subscribedTopicNames.size());
+
+        subscribedTopicNames.forEach((topicName, count) -> {
+            TopicImage topicImage = topicsImage.getTopic(topicName);
+            if (topicImage != null) {
+                Map<Integer, Set<String>> partitionRacks = new HashMap<>();
+                topicImage.partitions().forEach((partition, partitionRegistration) -> {
+                    Set<String> racks = new HashSet<>();
+                    for (int replica : partitionRegistration.replicas) {
+                        Optional<String> rackOptional = clusterImage.broker(replica).rack();
+                        // Only add the rack if it is available for the broker/replica.
+                        rackOptional.ifPresent(racks::add);
+                    }
+                    // If rack information is unavailable for all replicas of this partition,
+                    // no corresponding entry will be stored for it in the map.
+                    if (!racks.isEmpty()) {
+                        partitionRacks.put(partition, racks);
+                    }
+                });
+
+                newSubscriptionMetadata.put(topicName, new TopicMetadata(
+                    topicImage.id(),
+                    topicImage.name(),
+                    topicImage.partitions().size(),
+                    partitionRacks)
+                );
+            }
+        });
+
+        return Collections.unmodifiableMap(newSubscriptionMetadata);
+    }
+
     /**
      * Updates the metadata refresh deadline.
      *
@@ -673,11 +773,9 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Checks if a metadata refresh is required. A refresh is required in two cases:
-     * 1) The deadline is smaller or equal to the current time;
-     * 2) The group epoch associated with the deadline is larger than
-     *    the current group epoch. This means that the operations which updated
-     *    the deadline failed.
+     * Checks if a metadata refresh is required. A refresh is required in two cases: 1) The deadline is smaller or equal to the current
+     * time; 2) The group epoch associated with the deadline is larger than the current group epoch. This means that the operations which
+     * updated the deadline failed.
      *
      * @param currentTimeMs The current time in milliseconds.
      * @return A boolean indicating whether a refresh is required or not.
@@ -696,11 +794,10 @@ public class StreamsGroup implements Group {
     /**
      * Validates the OffsetCommit request.
      *
-     * @param memberId          The member id.
-     * @param groupInstanceId   The group instance id.
-     * @param memberEpoch       The member epoch.
-     * @param isTransactional   Whether the offset commit is transactional or not. It has no
-     *                          impact when a consumer group is used.
+     * @param memberId        The member id.
+     * @param groupInstanceId The group instance id.
+     * @param memberEpoch     The member epoch.
+     * @param isTransactional Whether the offset commit is transactional or not. It has no impact when a consumer group is used.
      */
     @Override
     public void validateOffsetCommit(
@@ -712,7 +809,9 @@ public class StreamsGroup implements Group {
         // When the member epoch is -1, the request comes from either the admin client
         // or a consumer which does not use the group management facility. In this case,
         // the request can commit offsets if the group is empty.
-        if (memberEpoch < 0 && members().isEmpty()) return;
+        if (memberEpoch < 0 && members().isEmpty()) {
+            return;
+        }
 
         final StreamsGroupMember member = getOrMaybeCreateMember(memberId, false);
         validateMemberEpoch(memberEpoch, member.memberEpoch());
@@ -721,9 +820,9 @@ public class StreamsGroup implements Group {
     /**
      * Validates the OffsetFetch request.
      *
-     * @param memberId              The member id for consumer groups.
-     * @param memberEpoch           The member epoch for consumer groups.
-     * @param lastCommittedOffset   The last committed offsets in the timeline.
+     * @param memberId            The member id for consumer groups.
+     * @param memberEpoch         The member epoch for consumer groups.
+     * @param lastCommittedOffset The last committed offsets in the timeline.
      */
     @Override
     public void validateOffsetFetch(
@@ -734,7 +833,9 @@ public class StreamsGroup implements Group {
         // When the member id is null and the member epoch is -1, the request either comes
         // from the admin client or from a client which does not provide them. In this case,
         // the fetch request is accepted.
-        if (memberId == null && memberEpoch < 0) return;
+        if (memberId == null && memberEpoch < 0) {
+            return;
+        }
 
         final StreamsGroupMember member = members.get(memberId, lastCommittedOffset);
         if (member == null) {
@@ -748,7 +849,8 @@ public class StreamsGroup implements Group {
      * Validates the OffsetDelete request.
      */
     @Override
-    public void validateOffsetDelete() {}
+    public void validateOffsetDelete() {
+    }
 
     /**
      * Validates the DeleteGroups request.
@@ -773,20 +875,21 @@ public class StreamsGroup implements Group {
     @Override
     public void createGroupTombstoneRecords(List<CoordinatorRecord> records) {
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newCurrentAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord(groupId(), memberId))
         );
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newTargetAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentTombstoneRecord(groupId(), memberId))
         );
-        records.add(CoordinatorRecordHelpers.newTargetAssignmentEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochTombstoneRecord(groupId()));
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newMemberSubscriptionTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorRecordHelpers.newStreamsMemberSubscriptionTombstoneRecord(groupId(), memberId))
         );
 
-        records.add(CoordinatorRecordHelpers.newGroupSubscriptionMetadataTombstoneRecord(groupId()));
-        records.add(CoordinatorRecordHelpers.newGroupEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupSubscriptionMetadataTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupTopologyRecordTombstone(groupId()));
     }
 
     @Override
@@ -810,8 +913,7 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Throws a StaleMemberEpochException if the received member epoch does not match
-     * the expected member epoch.
+     * Throws a StaleMemberEpochException if the received member epoch does not match the expected member epoch.
      */
     private void validateMemberEpoch(
         int receivedMemberEpoch,
@@ -845,30 +947,6 @@ public class StreamsGroup implements Group {
         state.set(newState);
     }
 
-    /**
-     * Compute the subscription type of the consumer group.
-     *
-     * @param subscribedTopicNames      A map of topic names to the count of members subscribed to each topic.
-     *
-     * @return {@link org.apache.kafka.coordinator.group.assignor.SubscriptionType#HOMOGENEOUS} if all members are subscribed to exactly the same topics;
-     *         otherwise, {@link org.apache.kafka.coordinator.group.assignor.SubscriptionType#HETEROGENEOUS}.
-     */
-    public static SubscriptionType subscriptionType(
-        Map<String, Integer> subscribedTopicNames,
-        int numberOfMembers
-    ) {
-        if (subscribedTopicNames.isEmpty()) {
-            return HOMOGENEOUS;
-        }
-
-        for (int subscriberCount : subscribedTopicNames.values()) {
-            if (subscriberCount != numberOfMembers) {
-                return HETEROGENEOUS;
-            }
-        }
-        return HOMOGENEOUS;
-    }
-
     /**
      * Updates the tasks epochs based on the old and the new member.
      *
@@ -936,8 +1014,7 @@ public class StreamsGroup implements Group {
      *
      * @param assignment    The assignment.
      * @param expectedEpoch The expected epoch.
-     * @throws IllegalStateException if the epoch does not match the expected one.
-     * package-private for testing.
+     * @throws IllegalStateException if the epoch does not match the expected one. package-private for testing.
      */
     private void removeTaskEpochs(
         Map<String, Set<Integer>> assignment,
@@ -972,12 +1049,11 @@ public class StreamsGroup implements Group {
     /**
      * Adds the partitions epoch based on the provided assignment.
      *
-     * @param activeTasks   The assigned active tasks.
-     * @param standbyTasks  The assigned standby tasks.
-     * @param warmupTasks   The assigned warmup tasks.
-     * @param epoch         The new epoch.
-     * @throws IllegalStateException if the partition already has an epoch assigned.
-     * package-private for testing.
+     * @param activeTasks  The assigned active tasks.
+     * @param standbyTasks The assigned standby tasks.
+     * @param warmupTasks  The assigned warmup tasks.
+     * @param epoch        The new epoch.
+     * @throws IllegalStateException if the partition already has an epoch assigned. package-private for testing.
      */
     void addTaskEpochs(
         Map<String, Set<Integer>> activeTasks,
@@ -1014,11 +1090,12 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Decrements value by 1; returns null when reaching zero. This helper is
-     * meant to be used with Map#compute.
+     * Decrements value by 1; returns null when reaching zero. This helper is meant to be used with Map#compute.
      */
     private static Integer decValue(String key, Integer value) {
-        if (value == null) return null;
+        if (value == null) {
+            return null;
+        }
         return value == 1 ? null : value - 1;
     }
 
@@ -1044,7 +1121,7 @@ public class StreamsGroup implements Group {
         records.add(CoordinatorRecordHelpers.newStreamsGroupEpochRecord(groupId(), groupEpoch()));
 
         members().forEach((streamsGroupMemberId, streamsGroupMember) ->
-            records.add(CoordinatorRecordHelpers.newTargetAssignmentRecord(
+            records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
                 groupId(),
                 streamsGroupMemberId,
                 targetAssignment(streamsGroupMemberId).activeTasks(),
@@ -1054,9 +1131,10 @@ public class StreamsGroup implements Group {
         );
 
         records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupSubscriptionMetadataRecord(groupId(), subscriptionMetadata()));
 
         members().forEach((__, streamsGroupMember) ->
-            records.add(CoordinatorRecordHelpers.newCurrentAssignmentRecord(groupId(), streamsGroupMember))
+            records.add(CoordinatorRecordHelpers.newStreamsCurrentAssignmentRecord(groupId(), streamsGroupMember))
         );
     }
 
@@ -1083,8 +1161,7 @@ public class StreamsGroup implements Group {
      * Checks whether the member has any unreleased tasks.
      *
      * @param member The member to check.
-     * @return A boolean indicating whether the member has partitions in the target
-     *         assignment that hasn't been revoked by other members.
+     * @return A boolean indicating whether the member has partitions in the target assignment that hasn't been revoked by other members.
      */
     public boolean waitingOnUnreleasedActiveTasks(StreamsGroupMember member) {
         if (member.state() == MemberState.UNRELEASED_TASKS) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index 0379a58bb2c..e24a4eb966e 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -18,7 +18,6 @@ package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.ConsumerGroupDescribeResponseData;
-import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
 import org.apache.kafka.image.TopicImage;
@@ -37,20 +36,18 @@ import java.util.Set;
 import java.util.stream.Collectors;
 
 /**
- * StreamsGroupMember contains all the information related to a member
- * within a Streams group. This class is immutable and is fully backed
+ * StreamsGroupMember contains all the information related to a member within a Streams group. This class is immutable and is fully backed
  * by records stored in the __consumer_offsets topic.
  */
 public class StreamsGroupMember {
 
     /**
-     * A builder that facilitates the creation of a new member or the update of
-     * an existing one.
-     *
-     * Please refer to the javadoc of {{@link StreamsGroupMember}} for the
-     * definition of the fields.
+     * A builder that facilitates the creation of a new member or the update of an existing one.
+     * <p>
+     * Please refer to the javadoc of {{@link StreamsGroupMember}} for the definition of the fields.
      */
     public static class Builder {
+
         private final String memberId;
         private int memberEpoch = 0;
         private int previousMemberEpoch = -1;
@@ -64,9 +61,9 @@ public class StreamsGroupMember {
         private String assignor;
         private String processId;
         private StreamsGroupMemberMetadataValue.HostInfo hostInfo;
-        private List<StreamsGroupMemberMetadataValue.KeyValue> clientTags;
+        private Map<String, String> clientTags;
         private byte[] userData;
-        private List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs;
+        private Map<String, String> assignmentConfigs;
         private Map<String, Set<Integer>> assignedActiveTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedStandbyTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedWarmupTasks = Collections.emptyMap();
@@ -188,7 +185,7 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setClientTags(List<StreamsGroupMemberMetadataValue.KeyValue> clientTags) {
+        public Builder setClientTags(Map<String, String> clientTags) {
             this.clientTags = clientTags;
             return this;
         }
@@ -198,7 +195,7 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setAssignmentConfigs(List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs) {
+        public Builder setAssignmentConfigs(Map<String, String> assignmentConfigs) {
             this.assignmentConfigs = assignmentConfigs;
             return this;
         }
@@ -233,9 +230,15 @@ public class StreamsGroupMember {
             setAssignor(record.assignor());
             setProcessId(record.processId());
             setHostInfo(record.hostInfo());
-            setClientTags(record.clientTags());
+            setClientTags(record.clientTags().stream().collect(Collectors.toMap(
+                StreamsGroupMemberMetadataValue.KeyValue::key,
+                StreamsGroupMemberMetadataValue.KeyValue::value
+            )));
             setUserData(record.userData());
-            setAssignmentConfigs(record.assignmentConfigs());
+            setAssignmentConfigs(record.assignmentConfigs().stream().collect(Collectors.toMap(
+                StreamsGroupMemberMetadataValue.KeyValue::key,
+                StreamsGroupMemberMetadataValue.KeyValue::value
+            )));
             return this;
         }
 
@@ -332,37 +335,37 @@ public class StreamsGroupMember {
     /**
      * The topology hash
      */
-    private byte[] topologyHash;
+    private final byte[] topologyHash;
 
     /**
      * The assignor
      */
-    private String assignor;
+    private final String assignor;
 
     /**
      * The process ID
      */
-    private String processId;
+    private final String processId;
 
     /**
      * The host info
      */
-    private StreamsGroupMemberMetadataValue.HostInfo hostInfo;
+    private final StreamsGroupMemberMetadataValue.HostInfo hostInfo;
 
     /**
      * The client tags
      */
-    private  List<StreamsGroupMemberMetadataValue.KeyValue> clientTags;
+    private final Map<String, String> clientTags;
 
     /**
      * The user data
      */
-    private byte[] userData;
+    private final byte[] userData;
 
     /**
      * The assignment configs
      */
-    private  List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs;
+    private final Map<String, String> assignmentConfigs;
 
     /**
      * Active tasks assigned to this member.
@@ -384,6 +387,7 @@ public class StreamsGroupMember {
      */
     private final Map<String, Set<Integer>> activeTasksPendingRevocation;
 
+    @SuppressWarnings("checkstyle:ParameterNumber")
     private StreamsGroupMember(
         String memberId,
         int memberEpoch,
@@ -397,9 +401,9 @@ public class StreamsGroupMember {
         String assignor,
         String processId,
         StreamsGroupMemberMetadataValue.HostInfo hostInfo,
-        List<StreamsGroupMemberMetadataValue.KeyValue> clientTags,
+        Map<String, String> clientTags,
         byte[] userData,
-        List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs,
+        Map<String, String> assignmentConfigs,
         MemberState state,
         Map<String, Set<Integer>> assignedActiveTasks,
         Map<String, Set<Integer>> assignedStandbyTasks,
@@ -515,7 +519,7 @@ public class StreamsGroupMember {
     /**
      * @return The client tags
      */
-    public List<StreamsGroupMemberMetadataValue.KeyValue> clientTags() {
+    public Map<String, String> clientTags() {
         return clientTags;
     }
 
@@ -526,7 +530,7 @@ public class StreamsGroupMember {
     /**
      * @return The assignment configs
      */
-    public List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs() {
+    public Map<String, String> assignmentConfigs() {
         return assignmentConfigs;
     }
 
@@ -601,10 +605,15 @@ public class StreamsGroupMember {
         }
     }
 
+    @SuppressWarnings("checkstyle:CyclomaticComplexity")
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
         StreamsGroupMember that = (StreamsGroupMember) o;
         return memberEpoch == that.memberEpoch
             && previousMemberEpoch == that.previousMemberEpoch
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
new file mode 100644
index 00000000000..0af7e375af0
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -0,0 +1,82 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+/**
+ * Immutable topology metadata.
+ */
+public class StreamsTopology {
+
+    private final byte[] topologyHash;
+
+    private final Map<String, Subtopology> subtopologies;
+
+    public StreamsTopology(final byte[] topologyHash, final Map<String, Subtopology> subtopologies) {
+        this.topologyHash = topologyHash;
+        this.subtopologies = subtopologies;
+    }
+
+    public byte[] topologyHash() {
+        return topologyHash;
+    }
+
+    public Map<String, Subtopology> subtopologies() {
+        return subtopologies;
+    }
+
+    public static StreamsTopology fromRecord(
+        StreamsGroupTopologyValue record
+    ) {
+        return new StreamsTopology(
+            record.topologyHash(),
+            record.topology().stream().collect(Collectors.toMap(Subtopology::subtopology, x -> x))
+        );
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final StreamsTopology that = (StreamsTopology) o;
+        return Objects.deepEquals(topologyHash, that.topologyHash) && Objects.equals(subtopologies, that.subtopologies);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(Arrays.hashCode(topologyHash), subtopologies);
+    }
+
+    @Override
+    public String toString() {
+        return "StreamsTopology{" +
+            "topologyHash=" + Arrays.toString(topologyHash) +
+            ", subtopologies=" + subtopologies +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java
deleted file mode 100644
index fb9b1133637..00000000000
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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 org.apache.kafka.coordinator.group.streams;
-
-import org.apache.kafka.common.Uuid;
-import org.apache.kafka.coordinator.group.assignor.SubscribedTopicDescriber;
-import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * The subscribed topic metadata class is used by the {@link org.apache.kafka.coordinator.group.assignor.PartitionAssignor} to obtain
- * topic and partition metadata for the topics that the consumer group is subscribed to.
- */
-public class SubscribedTopicMetadata implements SubscribedTopicDescriber {
-    /**
-     * The topic Ids mapped to their corresponding {@link org.apache.kafka.coordinator.group.consumer.TopicMetadata}
-     * object, which contains topic and partition metadata.
-     */
-    private final Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata;
-
-    public SubscribedTopicMetadata(Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata) {
-        this.topicMetadata = Objects.requireNonNull(topicMetadata);
-    }
-
-    /**
-     * Map of topic Ids to topic metadata.
-     *
-     * @return The map of topic Ids to topic metadata.
-     */
-    public Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata() {
-        return this.topicMetadata;
-    }
-
-    /**
-     * The number of partitions for the given topic Id.
-     *
-     * @param topicId   Uuid corresponding to the topic.
-     * @return The number of partitions corresponding to the given topic Id,
-     *         or -1 if the topic Id does not exist.
-     */
-    @Override
-    public int numPartitions(Uuid topicId) {
-        org.apache.kafka.coordinator.group.consumer.TopicMetadata topic = this.topicMetadata.get(topicId);
-        return topic == null ? -1 : topic.numPartitions();
-    }
-
-    /**
-     * Returns all the available racks associated with the replicas of the given partition.
-     *
-     * @param topicId       Uuid corresponding to the partition's topic.
-     * @param partition     Partition Id within the topic.
-     * @return The set of racks corresponding to the replicas of the topics partition.
-     *         If the topic Id does not exist or no partition rack information is available, an empty set is returned.
-     */
-    @Override
-    public Set<String> racksForPartition(Uuid topicId, int partition) {
-        TopicMetadata topic = this.topicMetadata.get(topicId);
-        return topic == null ? Collections.emptySet() : topic.partitionRacks().getOrDefault(partition, Collections.emptySet());
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-        SubscribedTopicMetadata that = (SubscribedTopicMetadata) o;
-        return topicMetadata.equals(that.topicMetadata);
-    }
-
-    @Override
-    public int hashCode() {
-        return topicMetadata.hashCode();
-    }
-
-    @Override
-    public String toString() {
-        return "SubscribedTopicMetadata(" +
-            "topicMetadata=" + topicMetadata +
-            ')';
-    }
-}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
new file mode 100644
index 00000000000..26bc409cb7b
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -0,0 +1,390 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
+import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
+import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
+import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
+import org.apache.kafka.coordinator.group.taskassignor.MemberAssignment;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignorException;
+import org.apache.kafka.image.TopicsImage;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newTargetAssignmentEpochRecord;
+
+/**
+ * Build a new Target Assignment based on the provided parameters. As a result, it yields the records that must be persisted to the log and
+ * the new member assignments as a map.
+ * <p>
+ * Records are only created for members which have a new target assignment. If their assignment did not change, no new record is needed.
+ * <p>
+ * When a member is deleted, it is assumed that its target assignment record is deleted as part of the member deletion process. In other
+ * words, this class does not yield a tombstone for removed members.
+ */
+public class TargetAssignmentBuilder {
+
+    /**
+     * The assignment result returned by {{@link TargetAssignmentBuilder#build()}}.
+     */
+    public static class TargetAssignmentResult {
+
+        /**
+         * The records that must be applied to the __streams_offsets topics to persist the new target assignment.
+         */
+        private final List<CoordinatorRecord> records;
+
+        /**
+         * The new target assignment for the group.
+         */
+        private final Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment;
+
+        TargetAssignmentResult(
+            List<CoordinatorRecord> records,
+            Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment
+        ) {
+            Objects.requireNonNull(records);
+            Objects.requireNonNull(targetAssignment);
+            this.records = records;
+            this.targetAssignment = targetAssignment;
+        }
+
+        /**
+         * @return The records.
+         */
+        public List<CoordinatorRecord> records() {
+            return records;
+        }
+
+        /**
+         * @return The target assignment.
+         */
+        public Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment() {
+            return targetAssignment;
+        }
+    }
+
+    /**
+     * The group id.
+     */
+    private final String groupId;
+
+    /**
+     * The group epoch.
+     */
+    private final int groupEpoch;
+
+    /**
+     * The partition assignor used to compute the assignment.
+     */
+    private final TaskAssignor assignor;
+
+    /**
+     * The members in the group.
+     */
+    private Map<String, StreamsGroupMember> members = Collections.emptyMap();
+
+    /**
+     * The subscription metadata.
+     */
+    private Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = Collections.emptyMap();
+
+    /**
+     * The existing target assignment.
+     */
+    private Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment = Collections.emptyMap();
+
+    /**
+     * Reverse lookup map representing tasks with their current member assignments.
+     */
+    private Map<String, Map<Integer, String>> invertedTargetAssignment = Collections.emptyMap();
+
+    /**
+     * The topics image.
+     */
+    private TopicsImage topicsImage = TopicsImage.EMPTY;
+
+    /**
+     * The topology.
+     */
+    private StreamsTopology topology;
+
+    /**
+     * The members which have been updated or deleted. Deleted members are signaled by a null value.
+     */
+    private final Map<String, StreamsGroupMember> updatedMembers = new HashMap<>();
+
+    /**
+     * The static members in the group.
+     */
+    private Map<String, String> staticMembers = new HashMap<>();
+
+    /**
+     * Constructs the object.
+     *
+     * @param groupId    The group id.
+     * @param groupEpoch The group epoch to compute a target assignment for.
+     * @param assignor   The assignor to use to compute the target assignment.
+     */
+    public TargetAssignmentBuilder(
+        String groupId,
+        int groupEpoch,
+        TaskAssignor assignor,
+        StreamsTopology topology
+    ) {
+        this.groupId = Objects.requireNonNull(groupId);
+        this.groupEpoch = groupEpoch;
+        this.assignor = Objects.requireNonNull(assignor);
+        this.topology = Objects.requireNonNull(topology);
+    }
+
+    /**
+     * Adds all the existing members.
+     *
+     * @param members The existing members in the streams group.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withMembers(
+        Map<String, StreamsGroupMember> members
+    ) {
+        this.members = members;
+        return this;
+    }
+
+    /**
+     * Adds all the existing static members.
+     *
+     * @param staticMembers The existing static members in the streams group.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withStaticMembers(
+        Map<String, String> staticMembers
+    ) {
+        this.staticMembers = staticMembers;
+        return this;
+    }
+
+    /**
+     * Adds the subscription metadata to use.
+     *
+     * @param subscriptionMetadata The subscription metadata.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withSubscriptionMetadata(
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata
+    ) {
+        this.subscriptionMetadata = subscriptionMetadata;
+        return this;
+    }
+
+    /**
+     * Adds the existing target assignment.
+     *
+     * @param targetAssignment The existing target assignment.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withTargetAssignment(
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment
+    ) {
+        this.targetAssignment = targetAssignment;
+        return this;
+    }
+
+    /**
+     * Adds the existing topic partition assignments.
+     *
+     * @param invertedTargetAssignment The reverse lookup map of the current target assignment.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withInvertedTargetAssignment(
+        Map<String, Map<Integer, String>> invertedTargetAssignment
+    ) {
+        this.invertedTargetAssignment = invertedTargetAssignment;
+        return this;
+    }
+
+    /**
+     * Adds the topics image.
+     *
+     * @param topicsImage The topics image.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder withTopicsImage(
+        TopicsImage topicsImage
+    ) {
+        this.topicsImage = topicsImage;
+        return this;
+    }
+
+    /**
+     * Adds or updates a member. This is useful when the updated member is not yet materialized in memory.
+     *
+     * @param memberId The member id.
+     * @param member   The member to add or update.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder addOrUpdateMember(
+        String memberId,
+        StreamsGroupMember member
+    ) {
+        this.updatedMembers.put(memberId, member);
+        return this;
+    }
+
+    /**
+     * Removes a member. This is useful when the removed member is not yet materialized in memory.
+     *
+     * @param memberId The member id.
+     * @return This object.
+     */
+    public TargetAssignmentBuilder removeMember(
+        String memberId
+    ) {
+        return addOrUpdateMember(memberId, null);
+    }
+
+    /**
+     * Builds the new target assignment.
+     *
+     * @return A TargetAssignmentResult which contains the records to update the existing target assignment.
+     * @throws TaskAssignorException if the target assignment cannot be computed.
+     */
+    public TargetAssignmentResult build() throws TaskAssignorException {
+        Map<String, AssignmentMemberSpec> memberSpecs = new HashMap<>();
+
+        // Prepare the member spec for all members.
+        members.forEach((memberId, member) -> memberSpecs.put(memberId, createAssignmentMemberSpec(
+            member,
+            targetAssignment.getOrDefault(memberId, org.apache.kafka.coordinator.group.streams.Assignment.EMPTY)
+        )));
+
+        // Update the member spec if updated or deleted members.
+        updatedMembers.forEach((memberId, updatedMemberOrNull) -> {
+            if (updatedMemberOrNull == null) {
+                memberSpecs.remove(memberId);
+            } else {
+                org.apache.kafka.coordinator.group.streams.Assignment assignment = targetAssignment.getOrDefault(memberId,
+                    org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+
+                // A new static member joins and needs to replace an existing departed one.
+                if (updatedMemberOrNull.instanceId() != null) {
+                    String previousMemberId = staticMembers.get(updatedMemberOrNull.instanceId());
+                    if (previousMemberId != null && !previousMemberId.equals(memberId)) {
+                        assignment = targetAssignment.getOrDefault(previousMemberId,
+                            org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+                    }
+                }
+
+                memberSpecs.put(memberId, createAssignmentMemberSpec(
+                    updatedMemberOrNull,
+                    assignment
+                ));
+            }
+        });
+
+        // Compute the assignment.
+        GroupAssignment newGroupAssignment = assignor.assign(
+            new GroupSpecImpl(
+                Collections.unmodifiableMap(memberSpecs),
+                new ArrayList<>(topology.subtopologies().keySet())
+            ),
+            new TopologyMetadata(subscriptionMetadata, topology)
+        );
+
+        // Compute delta from previous to new target assignment and create the
+        // relevant records.
+        List<CoordinatorRecord> records = new ArrayList<>();
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> newTargetAssignment = new HashMap<>();
+
+        memberSpecs.keySet().forEach(memberId -> {
+            org.apache.kafka.coordinator.group.streams.Assignment oldMemberAssignment = targetAssignment.get(memberId);
+            org.apache.kafka.coordinator.group.streams.Assignment newMemberAssignment = newMemberAssignment(newGroupAssignment, memberId);
+
+            newTargetAssignment.put(memberId, newMemberAssignment);
+
+            if (oldMemberAssignment == null) {
+                // If the member had no assignment, we always create a record for it.
+                records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
+                    groupId,
+                    memberId,
+                    newMemberAssignment.activeTasks(),
+                    newMemberAssignment.standbyTasks(),
+                    newMemberAssignment.warmupTasks()
+                ));
+            } else {
+                // If the member had an assignment, we only create a record if the
+                // new assignment is different.
+                if (!newMemberAssignment.equals(oldMemberAssignment)) {
+                    records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
+                        groupId,
+                        memberId,
+                        newMemberAssignment.activeTasks(),
+                        newMemberAssignment.standbyTasks(),
+                        newMemberAssignment.warmupTasks()
+                    ));
+                }
+            }
+        });
+
+        // Bump the target assignment epoch.
+        records.add(newTargetAssignmentEpochRecord(groupId, groupEpoch));
+
+        return new TargetAssignmentResult(records, newTargetAssignment);
+    }
+
+    private org.apache.kafka.coordinator.group.streams.Assignment newMemberAssignment(
+        org.apache.kafka.coordinator.group.taskassignor.GroupAssignment newGroupAssignment,
+        String memberId
+    ) {
+        MemberAssignment newMemberAssignment = newGroupAssignment.members().get(memberId);
+        if (newMemberAssignment != null) {
+            return new org.apache.kafka.coordinator.group.streams.Assignment(
+                newMemberAssignment.activeTasks(),
+                newMemberAssignment.standbyTasks(),
+                newMemberAssignment.warmupTasks()
+            );
+        } else {
+            return org.apache.kafka.coordinator.group.streams.Assignment.EMPTY;
+        }
+    }
+
+    static AssignmentMemberSpec createAssignmentMemberSpec(
+        StreamsGroupMember member,
+        Assignment targetAssignment
+    ) {
+        return new AssignmentMemberSpec(
+            Optional.ofNullable(member.instanceId()),
+            Optional.ofNullable(member.rackId()),
+            targetAssignment.activeTasks(),
+            targetAssignment.standbyTasks(),
+            targetAssignment.warmupTasks(),
+            member.processId(),
+            member.clientTags(),
+            member.assignmentConfigs(),
+            Collections.emptyMap() // TODO: TaskOffsets is missing
+        );
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java
deleted file mode 100644
index 7beb9b9e4ff..00000000000
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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 org.apache.kafka.coordinator.group.streams;
-
-import org.apache.kafka.common.Uuid;
-import org.apache.kafka.image.TopicImage;
-import org.apache.kafka.image.TopicsImage;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * TopicIds is initialized with topic names (String) but exposes a Set of topic ids (Uuid) to the
- * user and performs the conversion lazily with TopicsImage.
- */
-public class TopicIds implements Set<Uuid> {
-    private final Set<String> topicNames;
-    private final TopicsImage image;
-
-    public TopicIds(
-        Set<String> topicNames,
-        TopicsImage image
-    ) {
-        this.topicNames = Objects.requireNonNull(topicNames);
-        this.image = Objects.requireNonNull(image);
-    }
-
-    @Override
-    public int size() {
-        return topicNames.size();
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return topicNames.isEmpty();
-    }
-
-    @Override
-    public boolean contains(Object o) {
-        if (o instanceof Uuid) {
-            Uuid topicId = (Uuid) o;
-            TopicImage topicImage = image.getTopic(topicId);
-            if (topicImage == null) return false;
-            return topicNames.contains(topicImage.name());
-        }
-        return false;
-    }
-
-    private static class TopicIdIterator implements Iterator<Uuid> {
-        final Iterator<String> iterator;
-        final TopicsImage image;
-        private Uuid next = null;
-
-        private TopicIdIterator(
-            Iterator<String> iterator,
-            TopicsImage image
-        ) {
-            this.iterator = Objects.requireNonNull(iterator);
-            this.image = Objects.requireNonNull(image);
-        }
-
-        @Override
-        public boolean hasNext() {
-            if (next != null) return true;
-            Uuid result = null;
-            do {
-                if (!iterator.hasNext()) {
-                    return false;
-                }
-                String next = iterator.next();
-                TopicImage topicImage = image.getTopic(next);
-                if (topicImage != null) {
-                    result = topicImage.id();
-                }
-            } while (result == null);
-            next = result;
-            return true;
-        }
-
-        @Override
-        public Uuid next() {
-            if (!hasNext()) throw new NoSuchElementException();
-            Uuid result = next;
-            next = null;
-            return result;
-        }
-    }
-
-    @Override
-    public Iterator<Uuid> iterator() {
-        return new TopicIdIterator(topicNames.iterator(), image);
-    }
-
-    @Override
-    public Object[] toArray() {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public <T> T[] toArray(T[] a) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean add(Uuid o) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean remove(Object o) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean addAll(Collection c) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public void clear() {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean removeAll(Collection c) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean retainAll(Collection c) {
-        throw new UnsupportedOperationException();
-    }
-
-    @Override
-    public boolean containsAll(Collection c) {
-        for (Object o : c) {
-            if (!contains(o)) return false;
-        }
-        return true;
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-
-        TopicIds uuids = (TopicIds) o;
-
-        if (!Objects.equals(topicNames, uuids.topicNames)) return false;
-        return Objects.equals(image, uuids.image);
-    }
-
-    @Override
-    public int hashCode() {
-        int result = topicNames.hashCode();
-        result = 31 * result + image.hashCode();
-        return result;
-    }
-}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java
index b03afea1be1..b319b78914a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java
@@ -30,6 +30,7 @@ import java.util.Set;
  * Immutable topic metadata.
  */
 public class TopicMetadata {
+
     /**
      * The topic id.
      */
@@ -46,8 +47,8 @@ public class TopicMetadata {
     private final int numPartitions;
 
     /**
-     * Map of every partition Id to a set of its rack Ids, if they exist.
-     * If rack information is unavailable for all partitions, this is an empty map.
+     * Map of every partition Id to a set of its rack Ids, if they exist. If rack information is unavailable for all partitions, this is an
+     * empty map.
      */
     private final Map<Integer, Set<String>> partitionRacks;
 
@@ -94,8 +95,8 @@ public class TopicMetadata {
     }
 
     /**
-     * @return Every partition mapped to the set of corresponding available rack Ids of its replicas.
-     *         An empty map is returned if rack information is unavailable for all partitions.
+     * @return Every partition mapped to the set of corresponding available rack Ids of its replicas. An empty map is returned if rack
+     * information is unavailable for all partitions.
      */
     public Map<Integer, Set<String>> partitionRacks() {
         return this.partitionRacks;
@@ -103,14 +104,24 @@ public class TopicMetadata {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
 
         TopicMetadata that = (TopicMetadata) o;
 
-        if (!id.equals(that.id)) return false;
-        if (!name.equals(that.name)) return false;
-        if (numPartitions != that.numPartitions) return false;
+        if (!id.equals(that.id)) {
+            return false;
+        }
+        if (!name.equals(that.name)) {
+            return false;
+        }
+        if (numPartitions != that.numPartitions) {
+            return false;
+        }
         return partitionRacks.equals(that.partitionRacks);
     }
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java
new file mode 100644
index 00000000000..ebc0f239f7d
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java
@@ -0,0 +1,105 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+import org.apache.kafka.coordinator.group.taskassignor.TopologyDescriber;
+
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * The topology metadata class is used by the {@link org.apache.kafka.coordinator.group.taskassignor.TaskAssignor} to obtain topic and
+ * partition metadata for the topology that the streams group using.
+ */
+public class TopologyMetadata implements TopologyDescriber {
+
+    /**
+     * The topic Ids mapped to their corresponding {@link org.apache.kafka.coordinator.group.streams.TopicMetadata} object, which contains
+     * topic and partition metadata.
+     */
+    private final Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> topicMetadata;
+
+    private final StreamsTopology topology;
+
+    public TopologyMetadata(
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> topicMetadata,
+        StreamsTopology topology
+    ) {
+        this.topicMetadata = Objects.requireNonNull(topicMetadata);
+        this.topology = Objects.requireNonNull(topology);
+    }
+
+    /**
+     * Map of topic names to topic metadata.
+     *
+     * @return The map of topic Ids to topic metadata.
+     */
+    public Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> topicMetadata() {
+        return this.topicMetadata;
+    }
+
+    public StreamsTopology topology() {
+        return topology;
+    }
+
+    /**
+     * The number of partitions for the given subtopology ID.
+     *
+     * @param subtopologyId ID of the corresponding subtopology
+     * @return The number of partitions corresponding to the given subtopology ID, or -1 if the subtopology ID does not exist.
+     */
+    @Override
+    public int numPartitions(String subtopologyId) {
+        final Subtopology subtopology = topology.subtopologies().get(subtopologyId);
+        if (subtopology == null) {
+            return -1;
+        }
+        // TODO: We need to validate the validity of the subtopology here or somewhere else
+        final String firstSourceTopic = subtopology.sourceTopics().get(0);
+        if (firstSourceTopic == null) {
+            return -1;
+        }
+        org.apache.kafka.coordinator.group.streams.TopicMetadata topic = this.topicMetadata.get(firstSourceTopic);
+        return topic == null ? -1 : topic.numPartitions();
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final TopologyMetadata that = (TopologyMetadata) o;
+        return Objects.equals(topicMetadata, that.topicMetadata) && Objects.equals(topology, that.topology);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(topicMetadata, topology);
+    }
+
+    @Override
+    public String toString() {
+        return "TopologyMetadata{" +
+            "topicMetadata=" + topicMetadata +
+            ", topology=" + topology +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
index 6d8cb6b906c..30f775fa1f8 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
@@ -20,9 +20,9 @@
   "validVersions": "14",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "8",
+    { "name": "GroupId", "type": "string", "versions": "14",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "8",
+    { "name": "MemberId", "type": "string", "versions": "14",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
index bc54bc8010b..0834b3e41ee 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
@@ -20,9 +20,9 @@
   "validVersions": "11",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "5",
+    { "name": "GroupId", "type": "string", "versions": "11",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "5",
+    { "name": "MemberId", "type": "string", "versions": "11",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
index 0ad8fbce88b..8f287c05652 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
@@ -20,7 +20,7 @@
   "validVersions": "9",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "3",
+    { "name": "GroupId", "type": "string", "versions": "9",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
index 52b879dbcd1..954e5fd1182 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -20,7 +20,7 @@
   "validVersions": "10",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "4",
+    { "name": "GroupId", "type": "string", "versions": "10",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
index 6faac03a9e2..128bf44bba7 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
@@ -20,9 +20,9 @@
   "validVersions": "13",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "7",
+    { "name": "GroupId", "type": "string", "versions": "13",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "7",
+    { "name": "MemberId", "type": "string", "versions": "13",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
index 91f58c07f64..b583b3224b4 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
@@ -20,7 +20,7 @@
   "validVersions": "12",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "6",
+    { "name": "GroupId", "type": "string", "versions": "12",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
index 0e72d8c3372..11873d4403c 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
@@ -20,7 +20,7 @@
   "validVersions": "15",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "3",
+    { "name": "GroupId", "type": "string", "versions": "15",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
index 9759f41d727..489d0d1fdd0 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
@@ -71,25 +71,6 @@ public class AssignmentTestUtil {
         return Collections.unmodifiableMap(assignment);
     }
 
-    @SafeVarargs
-    public static Map<String, Set<Integer>> mkStreamsAssignment(Map.Entry<String, Set<Integer>>... entries) {
-        Map<String, Set<Integer>> assignment = new HashMap<>();
-        for (Map.Entry<String, Set<Integer>> entry : entries) {
-            assignment.put(entry.getKey(), entry.getValue());
-        }
-        return assignment;
-    }
-
-    public static Map.Entry<String, Set<Integer>> mkTaskAssignment(
-        String subtopology,
-        Integer... partitions
-    ) {
-        return new AbstractMap.SimpleEntry<>(
-            subtopology,
-            new HashSet<>(Arrays.asList(partitions))
-        );
-    }
-
     /**
      * Verifies that the expected assignment is equal to the computed assignment for every member in the group.
      */
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
index 49ba49753bc..ccec91a46db 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -26,8 +26,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
@@ -42,13 +42,13 @@ public class AssignmentTest {
 
     @Test
     public void testAttributes() {
-        Map<String, Set<Integer>> activeTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> activeTasks = mkAssignment(
             mkTaskAssignment("subtopology1", 1, 2, 3)
         );
-        Map<String, Set<Integer>> standbyTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> standbyTasks = mkAssignment(
             mkTaskAssignment("subtopology2", 9, 8, 7)
         );
-        Map<String, Set<Integer>> warmupTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> warmupTasks = mkAssignment(
             mkTaskAssignment("subtopology3", 4, 5, 6)
         );
         Assignment assignment = new Assignment(activeTasks, standbyTasks, warmupTasks);
@@ -92,21 +92,21 @@ public class AssignmentTest {
         Assignment assignment = Assignment.fromRecord(record);
 
         assertEquals(
-            mkStreamsAssignment(
+            mkAssignment(
                 mkTaskAssignment(subtopology1, 1, 2, 3),
                 mkTaskAssignment(subtopology2, 4, 5, 6)
             ),
             assignment.activeTasks()
         );
         assertEquals(
-            mkStreamsAssignment(
+            mkAssignment(
                 mkTaskAssignment(subtopology1, 7, 8, 9),
                 mkTaskAssignment(subtopology2, 1, 2, 3)
             ),
             assignment.standbyTasks()
         );
         assertEquals(
-            mkStreamsAssignment(
+            mkAssignment(
                 mkTaskAssignment(subtopology1, 4, 5, 6),
                 mkTaskAssignment(subtopology2, 7, 8, 9)
             ),
@@ -116,13 +116,13 @@ public class AssignmentTest {
 
     @Test
     public void testEquals() {
-        Map<String, Set<Integer>> activeTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> activeTasks = mkAssignment(
             mkTaskAssignment("subtopology1", 1, 2, 3)
         );
-        Map<String, Set<Integer>> standbyTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> standbyTasks = mkAssignment(
             mkTaskAssignment("subtopology2", 9, 8, 7)
         );
-        Map<String, Set<Integer>> warmupTasks = mkStreamsAssignment(
+        Map<String, Set<Integer>> warmupTasks = mkAssignment(
             mkTaskAssignment("subtopology3", 4, 5, 6)
         );
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
new file mode 100644
index 00000000000..e3531e11a37
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -0,0 +1,576 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class CurrentAssignmentBuilderTest {
+
+    @Test
+    public void testStableToStable() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testStableToStableWithNewTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
+                    mkTaskAssignment(subtopologyId2, 4, 5, 6, 7)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testStableToUnrevokedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setMemberEpoch(10)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .setActiveTasksPendingRevocation(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 1),
+                    mkTaskAssignment(subtopologyId2, 4)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testStableToUnreleasedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testStableToUnreleasedTasksWithOwnedTasksNotHavingRevokedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 4, 5, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, __) ->
+                subtopologyId2.equals(subtopologyId) ? 10 : -1
+            )
+            .withOwnedActiveTasks(Collections.emptyList())
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 4, 5)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnrevokedTasksToStable() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setActiveTasksPendingRevocation(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1),
+                mkTaskAssignment(subtopologyId2, 4)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withOwnedActiveTasks(Arrays.asList(
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId1)
+                    .setPartitions(Arrays.asList(2, 3)),
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId2)
+                    .setPartitions(Arrays.asList(5, 6))))
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testRemainsInUnrevokedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setActiveTasksPendingRevocation(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1),
+                mkTaskAssignment(subtopologyId2, 4)))
+            .build();
+
+        org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder currentAssignmentBuilder = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(
+            member)
+            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1);
+
+        assertEquals(
+            member,
+            currentAssignmentBuilder
+                .withOwnedActiveTasks(null)
+                .build()
+        );
+
+        assertEquals(
+            member,
+            currentAssignmentBuilder
+                .withOwnedActiveTasks(Arrays.asList(
+                    new StreamsHeartbeatRequestData.TaskIds()
+                        .setSubtopology(subtopologyId1)
+                        .setPartitions(Arrays.asList(1, 2, 3)),
+                    new StreamsHeartbeatRequestData.TaskIds()
+                        .setSubtopology(subtopologyId2)
+                        .setPartitions(Arrays.asList(5, 6))))
+                .build()
+        );
+
+        assertEquals(
+            member,
+            currentAssignmentBuilder
+                .withOwnedActiveTasks(Arrays.asList(
+                    new StreamsHeartbeatRequestData.TaskIds()
+                        .setSubtopology(subtopologyId1)
+                        .setPartitions(Arrays.asList(2, 3)),
+                    new StreamsHeartbeatRequestData.TaskIds()
+                        .setSubtopology(subtopologyId2)
+                        .setPartitions(Arrays.asList(4, 5, 6))))
+                .build()
+        );
+    }
+
+    @Test
+    public void testUnrevokedTasksToUnrevokedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setActiveTasksPendingRevocation(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 1),
+                mkTaskAssignment(subtopologyId2, 4)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withOwnedActiveTasks(Arrays.asList(
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId1)
+                    .setPartitions(Arrays.asList(2, 3)),
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId2)
+                    .setPartitions(Arrays.asList(5, 6))))
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(10)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 3),
+                    mkTaskAssignment(subtopologyId2, 6)))
+                .setActiveTasksPendingRevocation(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2),
+                    mkTaskAssignment(subtopologyId2, 5)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnrevokedTasksToUnreleasedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(10)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withOwnedActiveTasks(Arrays.asList(
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId1)
+                    .setPartitions(Arrays.asList(2, 3)),
+                new StreamsHeartbeatRequestData.TaskIds()
+                    .setSubtopology(subtopologyId2)
+                    .setPartitions(Arrays.asList(5, 6))))
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(11)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnreleasedTasksToStable() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setMemberEpoch(12)
+                .setPreviousMemberEpoch(11)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2, 3),
+                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnreleasedTasksToStableWithNewTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(11)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2, 3, 4),
+                    mkTaskAssignment(subtopologyId2, 5, 6, 7)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnreleasedTasksToUnreleasedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3, 4),
+                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build();
+
+        assertEquals(member, updatedMember);
+    }
+
+    @Test
+    public void testUnreleasedTasksToUnrevokedTasks() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2, 3),
+                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setMemberEpoch(11)
+                .setPreviousMemberEpoch(11)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 3),
+                    mkTaskAssignment(subtopologyId2, 6)))
+                .setActiveTasksPendingRevocation(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 2),
+                    mkTaskAssignment(subtopologyId2, 5)))
+                .build(),
+            updatedMember
+        );
+    }
+
+    @Test
+    public void testUnknownState() {
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNKNOWN)
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignedActiveTasks(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6)))
+            .setActiveTasksPendingRevocation(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 2),
+                mkTaskAssignment(subtopologyId2, 5)))
+            .build();
+
+        // When the member is in an unknown state, the member is first to force
+        // a reset of the client side member state.
+        assertThrows(FencedMemberEpochException.class, () -> new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .build());
+
+        // Then the member rejoins with no owned tasks.
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, new Assignment(mkAssignment(
+                mkTaskAssignment(subtopologyId1, 3),
+                mkTaskAssignment(subtopologyId2, 6))))
+            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 11)
+            .withOwnedActiveTasks(Collections.emptyList())
+            .build();
+
+        assertEquals(
+            new StreamsGroupMember.Builder("member")
+                .setState(MemberState.STABLE)
+                .setMemberEpoch(12)
+                .setPreviousMemberEpoch(11)
+                .setAssignedActiveTasks(mkAssignment(
+                    mkTaskAssignment(subtopologyId1, 3),
+                    mkTaskAssignment(subtopologyId2, 6)))
+                .build(),
+            updatedMember
+        );
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index 5041aa9cf07..5995381e7b4 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -17,18 +17,23 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue.TaskIds;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue.KeyValue;
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.Optional;
 import java.util.OptionalInt;
 
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class StreamsGroupMemberTest {
 
@@ -49,13 +54,13 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(mkMap(mkEntry("client", "tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
             .build();
 
         assertEquals("member-id", member.memberId());
@@ -65,33 +70,33 @@ public class StreamsGroupMemberTest {
         assertEquals("rack-id", member.rackId());
         assertEquals("client-id", member.clientId());
         assertEquals("hostname", member.clientHost());
-        assertTrue(Arrays.equals("topology-hash".getBytes(), member.topologyHash()));
+        assertArrayEquals("topology-hash".getBytes(), member.topologyHash());
         assertEquals("assignor", member.assignor().get());
         assertEquals("process-id", member.processId());
         assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
         assertEquals(
-            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")),
+            mkMap(mkEntry("client", "tag")),
             member.clientTags()
         );
-        assertTrue(Arrays.equals("user-data".getBytes(), member.userData()));
+        assertArrayEquals("user-data".getBytes(), member.userData());
         assertEquals(
-            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")),
+            mkMap(mkEntry("assignment", "config")),
             member.assignmentConfigs()
         );
         assertEquals(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)),
+            mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)),
             member.assignedActiveTasks()
         );
         assertEquals(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)),
+            mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)),
             member.assignedStandbyTasks()
         );
         assertEquals(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)),
+            mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)),
             member.assignedWarmupTasks()
         );
         assertEquals(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)),
+            mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)),
             member.activeTasksPendingRevocation()
         );
     }
@@ -113,13 +118,13 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(mkMap(mkEntry("client", "tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
             .build();
 
         StreamsGroupMember member2 = new StreamsGroupMember.Builder("member-id")
@@ -134,13 +139,13 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(mkMap(mkEntry("client", "tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
             .build();
 
         StreamsGroupMember member3 = new StreamsGroupMember.Builder("member3-id")
@@ -155,13 +160,13 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(mkMap(mkEntry("client", "tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
             .build();
 
         assertEquals(member1, member2);
@@ -185,13 +190,13 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(mkMap(mkEntry("client", "tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
             .build();
 
         // This is a no-op.
@@ -214,7 +219,7 @@ public class StreamsGroupMemberTest {
         assertEquals("new-instance-id", updatedMember.instanceId());
         assertEquals("new-rack-id", updatedMember.rackId());
         assertEquals(6000, updatedMember.rebalanceTimeoutMs());
-        assertEquals("new-assignor", updatedMember.assignor());
+        assertEquals("new-assignor", updatedMember.assignor().get());
     }
 
     @Test
@@ -229,9 +234,9 @@ public class StreamsGroupMemberTest {
             .setAssignor("assignor")
             .setProcessId("process-id")
             .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setClientTags(Collections.singletonList(new KeyValue().setKey("client").setValue("tag")))
             .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")));
+            .setAssignmentConfigs(Collections.singletonList(new KeyValue().setKey("assignment").setValue("config")));
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
             .updateWith(record)
@@ -242,17 +247,17 @@ public class StreamsGroupMemberTest {
         assertEquals("client-id", member.clientId());
         assertEquals("host-id", member.clientHost());
         assertEquals(1000, member.rebalanceTimeoutMs());
-        assertTrue(Arrays.equals("topology-hash".getBytes(), member.topologyHash()));
+        assertArrayEquals("topology-hash".getBytes(), member.topologyHash());
         assertEquals("assignor", member.assignor().get());
         assertEquals("process-id", member.processId());
         assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
         assertEquals(
-            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")),
+            mkMap(mkEntry("client", "tag")),
             member.clientTags()
         );
-        assertTrue(Arrays.equals("user-data".getBytes(), member.userData()));
+        assertArrayEquals("user-data".getBytes(), member.userData());
         assertEquals(
-            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")),
+            mkMap(mkEntry("assignment", "config")),
             member.assignmentConfigs()
         );
     }
@@ -266,19 +271,19 @@ public class StreamsGroupMemberTest {
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(9)
             .setState((byte) 1)
-            .setActiveTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+            .setActiveTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId1)
                 .setPartitions(Arrays.asList(1, 2, 3)))
             )
-            .setStandbyTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+            .setStandbyTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId2)
                 .setPartitions(Arrays.asList(6, 5, 4)))
             )
-            .setWarmupTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+            .setWarmupTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId1)
                 .setPartitions(Arrays.asList(7, 8, 9)))
             )
-            .setActiveTasksPendingRevocation(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+            .setActiveTasksPendingRevocation(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId2)
                 .setPartitions(Arrays.asList(2, 3, 1)))
             );
@@ -290,9 +295,9 @@ public class StreamsGroupMemberTest {
         assertEquals(10, member.memberEpoch());
         assertEquals(9, member.previousMemberEpoch());
         assertEquals(MemberState.STABLE, member.state());
-        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)), member.assignedActiveTasks());
-        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)), member.assignedStandbyTasks());
-        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)), member.assignedWarmupTasks());
-        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 2, 3, 1)), member.activeTasksPendingRevocation());
+        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)), member.assignedActiveTasks());
+        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)), member.assignedStandbyTasks());
+        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)), member.assignedWarmupTasks());
+        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId2, 2, 3, 1)), member.activeTasksPendingRevocation());
     }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index d2f2f4fd22d..4dd727b8050 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -31,6 +31,7 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.ValueSource;
 
+import java.util.Collections;
 import java.util.Optional;
 import java.util.OptionalInt;
 import java.util.OptionalLong;
@@ -38,9 +39,8 @@ import java.util.OptionalLong;
 import static java.util.Collections.emptyMap;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
-import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
-import static org.apache.kafka.server.immutable.ImmutableSet.singleton;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -164,9 +164,9 @@ public class StreamsGroupTest {
 
         member = new StreamsGroupMember.Builder("member")
             .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkStreamsAssignment(
+            .setAssignedActiveTasks(mkAssignment(
                 mkTaskAssignment(fooSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(barSubtopology, 4, 5, 6)))
             .build();
 
@@ -184,9 +184,9 @@ public class StreamsGroupTest {
 
         member = new StreamsGroupMember.Builder(member)
             .setMemberEpoch(11)
-            .setAssignedActiveTasks(mkStreamsAssignment(
+            .setAssignedActiveTasks(mkAssignment(
                 mkTaskAssignment(barSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(zarSubtopology, 4, 5, 6)))
             .build();
 
@@ -215,7 +215,7 @@ public class StreamsGroupTest {
             .setAssignedActiveTasks(emptyMap())
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1)))
             .build();
 
@@ -225,7 +225,7 @@ public class StreamsGroupTest {
 
         member = new StreamsGroupMember.Builder(member)
             .setMemberEpoch(11)
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
             .setActiveTasksPendingRevocation(emptyMap())
@@ -243,7 +243,7 @@ public class StreamsGroupTest {
 
         StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
             .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
             .build();
@@ -252,7 +252,7 @@ public class StreamsGroupTest {
 
         StreamsGroupMember m2 = new StreamsGroupMember.Builder("m2")
             .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
             .build();
@@ -269,20 +269,20 @@ public class StreamsGroupTest {
 
         // Removing should fail because there is no epoch set.
         assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
-            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
             10
         ));
 
         StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
             .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
             .build();
 
         streamsGroup.updateMember(m1);
 
         // Removing should fail because the expected epoch is incorrect.
         assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
-            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
             11
         ));
     }
@@ -293,7 +293,7 @@ public class StreamsGroupTest {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
         streamsGroup.addTaskEpochs(
-            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
             emptyMap(),
             emptyMap(),
             10
@@ -302,10 +302,10 @@ public class StreamsGroupTest {
         // Changing the epoch should fail because the owner of the partition
         // should remove it first.
         assertThrows(IllegalStateException.class, () -> streamsGroup.addTaskEpochs(
-                mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
-                emptyMap(),
-                emptyMap(),
-                11
+            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            emptyMap(),
+            emptyMap(),
+            11
         ));
     }
 
@@ -320,9 +320,9 @@ public class StreamsGroupTest {
 
         member = new StreamsGroupMember.Builder("member")
             .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkStreamsAssignment(
+            .setAssignedActiveTasks(mkAssignment(
                 mkTaskAssignment(fooSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(barSubtopology, 4, 5, 6)))
             .build();
 
@@ -362,7 +362,7 @@ public class StreamsGroupTest {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
         streamsGroup.updateTargetAssignment(memberId1,
             new Assignment(
-                mkStreamsAssignment(
+                mkAssignment(
                     mkTaskAssignment(fooSubtopology, 1, 2, 3),
                     mkTaskAssignment(zarSubtopology, 7, 8, 9)
                 ),
@@ -373,10 +373,10 @@ public class StreamsGroupTest {
         StreamsGroupMember member1 = new StreamsGroupMember.Builder(memberId1)
             .setMemberEpoch(10)
             .setState(MemberState.UNRELEASED_TASKS)
-            .setAssignedActiveTasks(mkStreamsAssignment(
+            .setAssignedActiveTasks(mkAssignment(
                 mkTaskAssignment(fooSubtopology, 1, 2, 3)
             ))
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(barSubtopology, 4, 5, 6)
             ))
             .build();
@@ -386,7 +386,7 @@ public class StreamsGroupTest {
 
         StreamsGroupMember member2 = new StreamsGroupMember.Builder(memberId2)
             .setMemberEpoch(10)
-            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+            .setActiveTasksPendingRevocation(mkAssignment(
                 mkTaskAssignment(zarSubtopology, 7)))
             .build();
         streamsGroup.updateMember(member2);
@@ -478,7 +478,7 @@ public class StreamsGroupTest {
 
         // Initial assignment for member1
         Assignment initialAssignment = new Assignment(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 0)),
+            mkAssignment(mkTaskAssignment(subtopologyId, 0)),
             emptyMap(),
             emptyMap()
         );
@@ -494,7 +494,7 @@ public class StreamsGroupTest {
 
         // New assignment for member1
         Assignment newAssignment = new Assignment(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 1)),
+            mkAssignment(mkTaskAssignment(subtopologyId, 1)),
             emptyMap(),
             emptyMap()
         );
@@ -510,7 +510,7 @@ public class StreamsGroupTest {
 
         // New assignment for member2 to add partition 1
         Assignment newAssignment2 = new Assignment(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 1)),
+            mkAssignment(mkTaskAssignment(subtopologyId, 1)),
             emptyMap(),
             emptyMap()
         );
@@ -526,7 +526,7 @@ public class StreamsGroupTest {
 
         // New assignment for member1 to revoke partition 1 and assign partition 0
         Assignment newAssignment1 = new Assignment(
-            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 0)),
+            mkAssignment(mkTaskAssignment(subtopologyId, 0)),
             emptyMap(),
             emptyMap()
         );
@@ -717,14 +717,14 @@ public class StreamsGroupTest {
         );
         StreamsGroup group = new StreamsGroup(snapshotRegistry, "group-foo", metricsShard);
         snapshotRegistry.getOrCreateSnapshot(0);
-        assertTrue(group.isInStates(singleton("empty"), 0));
-        assertFalse(group.isInStates(singleton("Empty"), 0));
+        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
+        assertFalse(group.isInStates(Collections.singleton("Empty"), 0));
 
         group.updateMember(new StreamsGroupMember.Builder("member1")
             .build());
         snapshotRegistry.getOrCreateSnapshot(1);
-        assertTrue(group.isInStates(singleton("empty"), 0));
-        assertTrue(group.isInStates(singleton("stable"), 1));
-        assertFalse(group.isInStates(singleton("empty"), 1));
+        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
+        assertTrue(group.isInStates(Collections.singleton("stable"), 1));
+        assertFalse(group.isInStates(Collections.singleton("empty"), 1));
     }
 }
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
new file mode 100644
index 00000000000..ec82b8e99a7
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -0,0 +1,821 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
+import org.apache.kafka.coordinator.group.MetadataImageBuilder;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
+import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
+import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
+import org.apache.kafka.coordinator.group.taskassignor.MemberAssignment;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
+import org.apache.kafka.image.TopicsImage;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.coordinator.group.Assertions.assertUnorderedListEquals;
+import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
+import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class TargetAssignmentBuilderTest {
+
+    public static class TargetAssignmentBuilderTestContext {
+
+        private final String groupId;
+        private final int groupEpoch;
+        private final TaskAssignor assignor = mock(TaskAssignor.class);
+        private final StreamsTopology topology = new StreamsTopology(new byte[0], new HashMap<>());
+        private final Map<String, StreamsGroupMember> members = new HashMap<>();
+        private final Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = new HashMap<>();
+        private final Map<String, StreamsGroupMember> updatedMembers = new HashMap<>();
+        private final Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment = new HashMap<>();
+        private final Map<String, MemberAssignment> memberAssignments = new HashMap<>();
+        private final Map<String, String> staticMembers = new HashMap<>();
+        private MetadataImageBuilder topicsImageBuilder = new MetadataImageBuilder();
+
+        public TargetAssignmentBuilderTestContext(
+            String groupId,
+            int groupEpoch
+        ) {
+            this.groupId = groupId;
+            this.groupEpoch = groupEpoch;
+        }
+
+        public void addGroupMember(
+            String memberId,
+            Map<String, Set<Integer>> targetTasks
+        ) {
+            addGroupMember(memberId, null, targetTasks);
+        }
+
+        private void addGroupMember(
+            String memberId,
+            String instanceId,
+            Map<String, Set<Integer>> targetTasks
+        ) {
+            StreamsGroupMember.Builder memberBuilder = new StreamsGroupMember.Builder(memberId);
+            memberBuilder.setProcessId("processId");
+            memberBuilder.setClientTags(Collections.emptyMap());
+            memberBuilder.setAssignmentConfigs(Collections.emptyMap());
+            memberBuilder.setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090));
+
+            if (instanceId != null) {
+                memberBuilder.setInstanceId(instanceId);
+                staticMembers.put(instanceId, memberId);
+            }
+            members.put(memberId, memberBuilder.build());
+            targetAssignment.put(memberId, new org.apache.kafka.coordinator.group.streams.Assignment(targetTasks));
+        }
+
+        public String addSubtopologyWithSingleSourceTopic(
+            String topicName,
+            int numTasks,
+            Map<Integer, Set<String>> partitionRacks
+        ) {
+            String subtopologyId = Uuid.randomUuid().toString();
+            Uuid topicId = Uuid.randomUuid();
+            subscriptionMetadata.put(topicName, new org.apache.kafka.coordinator.group.streams.TopicMetadata(
+                topicId,
+                topicName,
+                numTasks,
+                partitionRacks
+            ));
+            topicsImageBuilder = topicsImageBuilder.addTopic(topicId, topicName, numTasks);
+            topology.subtopologies().put(subtopologyId, new StreamsGroupTopologyValue.Subtopology()
+                .setSubtopology(subtopologyId)
+                .setSourceTopics(Collections.singletonList(topicId.toString())));
+
+            return subtopologyId;
+        }
+
+        public void updateMemberSubscription(
+            String memberId
+        ) {
+            updateMemberSubscription(
+                memberId,
+                Optional.empty(),
+                Optional.empty()
+            );
+        }
+
+        public void updateMemberSubscription(
+            String memberId,
+            Optional<String> instanceId,
+            Optional<String> rackId
+        ) {
+            StreamsGroupMember existingMember = members.get(memberId);
+            StreamsGroupMember.Builder builder;
+            if (existingMember != null) {
+                builder = new StreamsGroupMember.Builder(existingMember);
+            } else {
+                builder = new StreamsGroupMember.Builder(memberId);
+                builder.setProcessId("processId");
+                builder.setClientTags(Collections.emptyMap());
+                builder.setAssignmentConfigs(Collections.emptyMap());
+                builder.setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090));
+            }
+            updatedMembers.put(memberId, builder
+                .maybeUpdateInstanceId(instanceId)
+                .maybeUpdateRackId(rackId)
+                .build());
+        }
+
+        public void removeMemberSubscription(
+            String memberId
+        ) {
+            this.updatedMembers.put(memberId, null);
+        }
+
+        public void prepareMemberAssignment(
+            String memberId,
+            Map<String, Set<Integer>> activeTasks
+        ) {
+            memberAssignments.put(memberId, new MemberAssignment(activeTasks, Collections.emptyMap(), Collections.emptyMap()));
+        }
+
+        public org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult build() {
+            TopicsImage topicsImage = topicsImageBuilder.build().topics();
+            // Prepare expected member specs.
+            Map<String, AssignmentMemberSpec> memberSpecs = new HashMap<>();
+
+            // All the existing members are prepared.
+            members.forEach((memberId, member) ->
+                memberSpecs.put(memberId, createAssignmentMemberSpec(
+                        member,
+                        targetAssignment.getOrDefault(memberId, org.apache.kafka.coordinator.group.streams.Assignment.EMPTY)
+                    )
+                ));
+
+            // All the updated are added and all the deleted
+            // members are removed.
+            updatedMembers.forEach((memberId, updatedMemberOrNull) -> {
+                if (updatedMemberOrNull == null) {
+                    memberSpecs.remove(memberId);
+                } else {
+                    org.apache.kafka.coordinator.group.streams.Assignment assignment = targetAssignment.getOrDefault(memberId,
+                        org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+
+                    // A new static member joins and needs to replace an existing departed one.
+                    if (updatedMemberOrNull.instanceId() != null) {
+                        String previousMemberId = staticMembers.get(updatedMemberOrNull.instanceId());
+                        if (previousMemberId != null && !previousMemberId.equals(memberId)) {
+                            assignment = targetAssignment.getOrDefault(previousMemberId,
+                                org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+                        }
+                    }
+
+                    memberSpecs.put(memberId, createAssignmentMemberSpec(
+                        updatedMemberOrNull,
+                        assignment
+                    ));
+                }
+            });
+
+            // Prepare the expected subscription topic metadata.
+            TopologyMetadata topologyMetadata = new TopologyMetadata(subscriptionMetadata, topology);
+
+            // Prepare the member assignments per topic partition.
+            Map<String, Map<Integer, String>> invertedTargetAssignment = TaskAssignmentTestUtil.invertedTargetAssignment(memberSpecs);
+
+            // Prepare the expected assignment spec.
+            GroupSpecImpl groupSpec = new GroupSpecImpl(memberSpecs, new ArrayList<>(topology.subtopologies().keySet()));
+
+            // We use `any` here to always return an assignment but use `verify` later on
+            // to ensure that the input was correct.
+            when(assignor.assign(any(), any()))
+                .thenReturn(new GroupAssignment(memberAssignments));
+
+            // Create and populate the assignment builder.
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder builder = new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(
+                groupId, groupEpoch, assignor, topology)
+                .withMembers(members)
+                .withStaticMembers(staticMembers)
+                .withSubscriptionMetadata(subscriptionMetadata)
+                .withTargetAssignment(targetAssignment)
+                .withInvertedTargetAssignment(invertedTargetAssignment)
+                .withTopicsImage(topicsImage);
+
+            // Add the updated members or delete the deleted members.
+            updatedMembers.forEach((memberId, updatedMemberOrNull) -> {
+                if (updatedMemberOrNull != null) {
+                    builder.addOrUpdateMember(memberId, updatedMemberOrNull);
+                } else {
+                    builder.removeMember(memberId);
+                }
+            });
+
+            // Execute the builder.
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = builder.build();
+
+            // Verify that the assignor was called once with the expected
+            // assignment spec.
+            verify(assignor, times(1))
+                .assign(groupSpec, topologyMetadata);
+
+            return result;
+        }
+    }
+
+    @Test
+    public void testCreateAssignmentMemberSpec() {
+        Uuid fooTopicId = Uuid.randomUuid();
+        Uuid barTopicId = Uuid.randomUuid();
+        String fooSubtopologyId = Uuid.randomUuid().toString();
+        String barSubtopologyId = Uuid.randomUuid().toString();
+        TopicsImage topicsImage = new MetadataImageBuilder()
+            .addTopic(fooTopicId, "foo", 5)
+            .addTopic(barTopicId, "bar", 5)
+            .build()
+            .topics();
+
+        final Map<String, String> clientTags = mkMap(mkEntry("tag1", "value1"), mkEntry("tag2", "value2"));
+        final Map<String, String> assignmentConfigs = mkMap(mkEntry("conf1", "value1"), mkEntry("conf2", "value2"));
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
+            .setRackId("rackId")
+            .setInstanceId("instanceId")
+            .setProcessId("processId")
+            .setAssignor("assignor")
+            .setClientTags(clientTags)
+            .setAssignmentConfigs(assignmentConfigs)
+            .build();
+
+        org.apache.kafka.coordinator.group.streams.Assignment assignment = new org.apache.kafka.coordinator.group.streams.Assignment(
+            mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+            ));
+
+        AssignmentMemberSpec assignmentMemberSpec = createAssignmentMemberSpec(
+            member,
+            assignment
+        );
+
+        assertEquals(new AssignmentMemberSpec(
+            Optional.of("instanceId"),
+            Optional.of("rackId"),
+            assignment.activeTasks(),
+            assignment.standbyTasks(),
+            assignment.warmupTasks(),
+            "processId",
+            clientTags,
+            assignmentConfigs,
+            Collections.emptyMap()
+        ), assignmentMemberSpec);
+    }
+
+    @Test
+    public void testEmpty() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+        assertEquals(Collections.singletonList(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        )), result.records());
+        assertEquals(Collections.emptyMap(), result.targetAssignment());
+    }
+
+    @Test
+    public void testAssignmentHasNotChanged() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(Collections.singletonList(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        )), result.records());
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testAssignmentSwapped() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(3, result.records().size());
+
+        assertUnorderedListEquals(Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+                mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 2));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(2));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        )));
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testNewMember() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        context.updateMemberSubscription("member-3");
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.prepareMemberAssignment("member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(4, result.records().size());
+
+        assertUnorderedListEquals(Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1, 2),
+                mkTaskAssignment(barSubtopologyId, 1, 2)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 3, 4),
+                mkTaskAssignment(barSubtopologyId, 3, 4)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 5, 6),
+                mkTaskAssignment(barSubtopologyId, 5, 6)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 3));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(3));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        )));
+        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testUpdateMember() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.addGroupMember("member-3", mkAssignment(
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        context.updateMemberSubscription(
+            "member-3",
+            Optional.of("instance-id-3"),
+            Optional.of("rack-0")
+        );
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.prepareMemberAssignment("member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(4, result.records().size());
+
+        assertUnorderedListEquals(Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1, 2),
+                mkTaskAssignment(barSubtopologyId, 1, 2)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 3, 4),
+                mkTaskAssignment(barSubtopologyId, 3, 4)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 5, 6),
+                mkTaskAssignment(barSubtopologyId, 5, 6)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 3));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(3));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        )));
+        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testPartialAssignmentUpdate() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, mkMapOfPartitionRacks(6));
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, mkMapOfPartitionRacks(6));
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.addGroupMember("member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
+            mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+        ));
+
+        context.prepareMemberAssignment("member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 6),
+            mkTaskAssignment(barSubtopologyId, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(3, result.records().size());
+
+        // Member 1 has no record because its assignment did not change.
+        assertUnorderedListEquals(Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
+                mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 6),
+                mkTaskAssignment(barSubtopologyId, 6)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 2));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(2));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
+            mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+        )));
+        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 6),
+            mkTaskAssignment(barSubtopologyId, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testDeleteMember() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.addGroupMember("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.addGroupMember("member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        context.removeMemberSubscription("member-3");
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        ));
+
+        org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(3, result.records().size());
+
+        assertUnorderedListEquals(Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+            ), Collections.emptyMap(), Collections.emptyMap()),
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+                mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 2));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(2));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
+            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+
+    @Test
+    public void testReplaceStaticMember() {
+        TargetAssignmentBuilderTestContext context = new TargetAssignmentBuilderTestContext(
+            "my-group",
+            20
+        );
+
+        String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
+        String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
+
+        context.addGroupMember("member-1", "instance-member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.addGroupMember("member-2", "instance-member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.addGroupMember("member-3", "instance-member-3", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        // Static member 3 leaves
+        context.removeMemberSubscription("member-3");
+
+        // Another static member joins with the same instance id as the departed one
+        context.updateMemberSubscription("member-3-a", Optional.of("instance-member-3"),
+            Optional.empty());
+
+        context.prepareMemberAssignment("member-1", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        ));
+
+        context.prepareMemberAssignment("member-2", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        ));
+
+        context.prepareMemberAssignment("member-3-a", mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        ));
+
+        TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
+
+        assertEquals(2, result.records().size());
+
+        assertUnorderedListEquals(Collections.singletonList(
+            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
+                mkTaskAssignment(fooSubtopologyId, 5, 6),
+                mkTaskAssignment(barSubtopologyId, 5, 6)
+            ), Collections.emptyMap(), Collections.emptyMap())
+        ), result.records().subList(0, 1));
+
+        assertEquals(newTargetAssignmentEpochRecord(
+            "my-group",
+            20
+        ), result.records().get(1));
+
+        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 1, 2),
+            mkTaskAssignment(barSubtopologyId, 1, 2)
+        )));
+        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 3, 4),
+            mkTaskAssignment(barSubtopologyId, 3, 4)
+        )));
+
+        expectedAssignment.put("member-3-a", new Assignment(mkAssignment(
+            mkTaskAssignment(fooSubtopologyId, 5, 6),
+            mkTaskAssignment(barSubtopologyId, 5, 6)
+        )));
+
+        assertEquals(expectedAssignment, result.targetAssignment());
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
new file mode 100644
index 00000000000..d53398238f7
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
@@ -0,0 +1,124 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
+import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
+
+import java.util.AbstractMap;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class TaskAssignmentTestUtil {
+
+    public static Map.Entry<String, Set<Integer>> mkTaskAssignment(
+        String subtopologyId,
+        Integer... tasks
+    ) {
+        return new AbstractMap.SimpleEntry<>(
+            subtopologyId,
+            new HashSet<>(Arrays.asList(tasks))
+        );
+    }
+
+    public static Map.Entry<String, Set<Integer>> mkSortedTaskAssignment(
+        String subtopologyId,
+        Integer... tasks
+    ) {
+        return new AbstractMap.SimpleEntry<>(
+            subtopologyId,
+            new TreeSet<>(Arrays.asList(tasks))
+        );
+    }
+
+    @SafeVarargs
+    public static Map<String, Set<Integer>> mkAssignment(Map.Entry<String, Set<Integer>>... entries) {
+        Map<String, Set<Integer>> assignment = new HashMap<>();
+        for (Map.Entry<String, Set<Integer>> entry : entries) {
+            assignment.put(entry.getKey(), entry.getValue());
+        }
+        return assignment;
+    }
+
+    @SafeVarargs
+    public static Map<String, Set<Integer>> mkSortedAssignment(Map.Entry<String, Set<Integer>>... entries) {
+        Map<String, Set<Integer>> assignment = new LinkedHashMap<>();
+        for (Map.Entry<String, Set<Integer>> entry : entries) {
+            assignment.put(entry.getKey(), entry.getValue());
+        }
+        return assignment;
+    }
+
+    @SafeVarargs
+    public static Map<String, Set<Integer>> mkStreamsAssignment(Map.Entry<String, Set<Integer>>... entries) {
+        Map<String, Set<Integer>> assignment = new HashMap<>();
+        for (Map.Entry<String, Set<Integer>> entry : entries) {
+            assignment.put(entry.getKey(), entry.getValue());
+        }
+        return assignment;
+    }
+
+    /**
+     * Verifies that the expected assignment is equal to the computed assignment for every member in the group.
+     */
+    public static void assertAssignment(
+        Map<String, Map<String, Set<Integer>>> expectedAssignment,
+        GroupAssignment computedGroupAssignment
+    ) {
+        assertEquals(expectedAssignment.size(), computedGroupAssignment.members().size());
+        computedGroupAssignment.members().forEach((memberId, memberAssignment) -> {
+            Map<String, Set<Integer>> computedAssignmentForMember = memberAssignment.activeTasks();
+            assertEquals(expectedAssignment.get(memberId), computedAssignmentForMember);
+        });
+    }
+
+    /**
+     * Generate a reverse look up map of partition to member target assignments from the given member spec.
+     *
+     * @param memberSpec A map where the key is the member Id and the value is an AssignmentMemberSpec object containing the member's
+     *                   partition assignments.
+     * @return Map of topic partition to member assignments.
+     */
+    public static Map<String, Map<Integer, String>> invertedTargetAssignment(
+        Map<String, AssignmentMemberSpec> memberSpec
+    ) {
+        Map<String, Map<Integer, String>> invertedTargetAssignment = new HashMap<>();
+        for (Map.Entry<String, AssignmentMemberSpec> memberEntry : memberSpec.entrySet()) {
+            String memberId = memberEntry.getKey();
+            Map<String, Set<Integer>> topicsAndTasks = memberEntry.getValue().activeTasks();
+
+            for (Map.Entry<String, Set<Integer>> topicEntry : topicsAndTasks.entrySet()) {
+                String subtopologyId = topicEntry.getKey();
+                Set<Integer> tasks = topicEntry.getValue();
+
+                Map<Integer, String> partitionMap = invertedTargetAssignment.computeIfAbsent(subtopologyId, k -> new HashMap<>());
+
+                for (Integer partitionId : tasks) {
+                    partitionMap.put(partitionId, memberId);
+                }
+            }
+        }
+        return invertedTargetAssignment;
+    }
+}


(kafka) 22/42: Minor: Revert test changes

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit a002fe9c241b5b982d70e7818ea23e077f9b629e
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue Aug 20 11:14:17 2024 +0200

    Minor: Revert test changes
---
 .../kafka/clients/consumer/internals/AbstractMembershipManager.java   | 1 -
 .../processor/internals/assignment/TaskAssignorConvergenceTest.java   | 4 ++--
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
index 049944ed09f..c6aa70d805e 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
@@ -1270,7 +1270,6 @@ public abstract class AbstractMembershipManager<R extends AbstractResponse> impl
 
     protected void updateMemberEpoch(int newEpoch) {
         boolean newEpochReceived = this.memberEpoch != newEpoch;
-        log.info("Updating member epoch to {}", newEpoch);
         this.memberEpoch = newEpoch;
         // Simply notify based on epoch changes only, since the member will generate a member ID
         // at startup, and it will remain unchanged for its entire lifetime.
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
index 19eb361a1d3..936c9eb6a85 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
@@ -471,8 +471,8 @@ public class TaskAssignorConvergenceTest {
 
     @ParameterizedTest
     @ValueSource(strings = {
-//        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_NONE,
-//        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_MIN_TRAFFIC,
+        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_NONE,
+        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_MIN_TRAFFIC,
         StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_BALANCE_SUBTOPOLOGY
     })
     public void randomClusterPerturbationsShouldConverge(final String rackAwareStrategy) {


(kafka) 26/42: Resolve conflict from 11/25 trunk rebase - Streams reconciliation logic

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 133a442e66ba8bc2d2ddc5482f34b79b89973b65
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue Sep 3 12:28:39 2024 +0200

    Resolve conflict from 11/25 trunk rebase - Streams reconciliation logic
    
    This PR implements the new reconciliation logic for Kafka Streams. In
    the POC, we used the reconciliation logic for topic partitions on the
    broker side, developed as part of KIP-848. This worked for active tasks,
    but does not take standby tasks or warm-up tasks into account.
    The new reconciliation logic also takes standby and warm up tasks into
    account. Inside the streams group object, we keep track of the process
    IDs that own a task, and in which role. This replaces task epochs from
    KIP-848. Using the process IDs, we can check the assignment invariants:
    
    * A. A process can own a task only once in any role. For example, if
    processX already owns a task as a standby, it cannot own it as an active
    as well.
    
    * B. For active tasks, since there can never two instances owning the
    same task in an active role, the invariant is different: An active task
    can be assigned only if no other member owns it (as an active task).
    
    The reconciliation logic will make sure that these invariants are
    followed. For this, it uses the same states for the member as KIP-848,
    just with different state transitions:
    
    A member is in state UNREVOKED whenever we are waiting for the member to
    confirm revocation of at least one task. We expect the member to revoke
    all tasks that are not in its target assignment before transitioning to
    the next epoch. Once the member has revoked all tasks that are not in
    its target assignment, it transitions to the new epoch and gets new
    tasks assigned. Once all tasks are assigned, we transition to STABLE,
    but it may be that some tasks cannot be assigned yet, because of the
    above invariants:
    
    * A. For any task, another instance of the same process may own the task
    in any role (active/standby/warmup), and we are still awaiting
    revocation.
    
    * B. For an active task, an instance of any process may own the same
    active task, and we are still awaiting revocation.
    
    As long as tasks cannot be assigned, we remain in state UNRELEASED.
    
    The testing required some changes, so that I could parameterize the test
    on the task role which is causing state transitions. There are some
    utitlity changes / clean-ups to construct assignments.
---
 .../coordinator/group/GroupCoordinatorShard.java   |   2 +-
 .../coordinator/group/GroupMetadataManager.java    |  22 +-
 .../metrics/GroupCoordinatorMetricsShard.java      |   6 +
 .../coordinator/group/streams/Assignment.java      |   7 -
 .../streams/CoordinatorStreamsRecordHelpers.java   |   4 +-
 .../group/streams/CurrentAssignmentBuilder.java    | 381 +++++++++---
 .../coordinator/group/streams/StreamsGroup.java    | 235 ++++---
 .../group/streams/StreamsGroupMember.java          | 127 +++-
 .../StreamsGroupCurrentMemberAssignmentValue.json  |   6 +-
 .../group/GroupMetadataManagerTest.java            |  10 +-
 .../coordinator/group/streams/AssignmentTest.java  |  46 +-
 .../streams/CurrentAssignmentBuilderTest.java      | 676 +++++++++++++--------
 .../group/streams/StreamsGroupBuilder.java         |   6 +-
 .../group/streams/StreamsGroupMemberTest.java      |  99 +--
 .../group/streams/StreamsGroupTest.java            | 232 +++----
 .../group/streams/TargetAssignmentBuilderTest.java | 437 ++++++-------
 .../group/streams/TaskAssignmentTestUtil.java      |  85 ++-
 17 files changed, 1476 insertions(+), 905 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 225b56f58e1..1809db63f13 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -851,7 +851,7 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
      * @param record        The record to apply to the state machine.
      * @throws RuntimeException
      */
-    @SuppressWarnings({"CyclomaticComplexity"})
+    @SuppressWarnings("CyclomaticComplexity")
     @Override
     public void replay(
         long offset,
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index bc551a1d89f..dfb768f9fb5 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -2391,7 +2391,9 @@ public class GroupMetadataManager {
         updatedMember = maybeReconcile(
             groupId,
             updatedMember,
-            group::currentActiveTaskEpoch,
+            group::currentActiveTaskProcessId,
+            group::currentStandbyTaskProcessIds,
+            group::currentWarmupTaskProcessIds,
             targetAssignmentEpoch,
             targetAssignment,
             ownedActiveTasks,
@@ -3720,8 +3722,12 @@ public class GroupMetadataManager {
      *
      * @param groupId               The group id.
      * @param member                The member to reconcile.
-     * @param currentActiveTaskEpoch The function returning the current epoch of
-     *                              a given partition.
+     * @param currentActiveTaskProcessId The function returning the current process ID of
+     *                              a given active task.
+     * @param currentStandbyTaskProcessIds The function returning the current process IDs of
+     *                              a given standby task.
+     * @param currentWarmupTaskProcessIds The function returning the current process IDs of
+     *                              a given warmup task.
      * @param targetAssignmentEpoch The target assignment epoch.
      * @param targetAssignment      The target assignment.
      * @param ownedActiveTasks      The list of active tasks owned by the member. This
@@ -3740,7 +3746,9 @@ public class GroupMetadataManager {
     private StreamsGroupMember maybeReconcile(
         String groupId,
         StreamsGroupMember member,
-        BiFunction<String, Integer, Integer> currentActiveTaskEpoch,
+        BiFunction<String, Integer, String> currentActiveTaskProcessId,
+        BiFunction<String, Integer, Set<String>> currentStandbyTaskProcessIds,
+        BiFunction<String, Integer, Set<String>> currentWarmupTaskProcessIds,
         int targetAssignmentEpoch,
         org.apache.kafka.coordinator.group.streams.Assignment targetAssignment,
         List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks,
@@ -3754,7 +3762,9 @@ public class GroupMetadataManager {
 
         StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
             .withTargetAssignment(targetAssignmentEpoch, targetAssignment)
-            .withCurrentActiveTaskEpoch(currentActiveTaskEpoch)
+            .withCurrentActiveTaskProcessId(currentActiveTaskProcessId)
+            .withCurrentStandbyTaskProcessIds(currentStandbyTaskProcessIds)
+            .withCurrentWarmupTaskProcessIds(currentWarmupTaskProcessIds)
             .withOwnedActiveTasks(ownedActiveTasks)
             .withOwnedStandbyTasks(ownedStandbyTasks)
             .withOwnedWarmupTasks(ownedWarmupTasks)
@@ -5624,6 +5634,8 @@ public class GroupMetadataManager {
                 .setAssignedStandbyTasks(Collections.emptyMap())
                 .setAssignedWarmupTasks(Collections.emptyMap())
                 .setActiveTasksPendingRevocation(Collections.emptyMap())
+                .setStandbyTasksPendingRevocation(Collections.emptyMap())
+                .setWarmupTasksPendingRevocation(Collections.emptyMap())
                 .build();
             streamsGroup.updateMember(newMember);
         }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
index 4ad6e7460f6..9a50c0a32cc 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
@@ -508,6 +508,9 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                 case EMPTY:
                     incrementNumStreamsGroups(StreamsGroupState.EMPTY);
                     break;
+                case INITIALIZING:
+                    incrementNumStreamsGroups(StreamsGroupState.INITIALIZING);
+                    break;
                 case ASSIGNING:
                     incrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
                     break;
@@ -527,6 +530,9 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                 case EMPTY:
                     decrementNumStreamsGroups(StreamsGroupState.EMPTY);
                     break;
+                case INITIALIZING:
+                    decrementNumStreamsGroups(StreamsGroupState.INITIALIZING);
+                    break;
                 case ASSIGNING:
                     decrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
                     break;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
index 17d94499d4c..b80e34cbfe5 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -40,13 +40,6 @@ public class Assignment {
     private final Map<String, Set<Integer>> standbyTasks;
     private final Map<String, Set<Integer>> warmupTasks;
 
-    // TODO: Tests using this constructor probably should be extended to cover standby tasks
-    public Assignment(final Map<String, Set<Integer>> activeTasks) {
-        this.activeTasks = Collections.unmodifiableMap(Objects.requireNonNull(activeTasks));
-        this.standbyTasks = Collections.emptyMap();
-        this.warmupTasks = Collections.emptyMap();
-    }
-
     public Assignment(final Map<String, Set<Integer>> activeTasks,
                       final Map<String, Set<Integer>> standbyTasks,
                       final Map<String, Set<Integer>> warmupTasks) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 0e615db1c14..679e987f407 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -330,7 +330,9 @@ public class CoordinatorStreamsRecordHelpers {
                     .setActiveTasks(toTaskIds(member.assignedActiveTasks()))
                     .setStandbyTasks(toTaskIds(member.assignedStandbyTasks()))
                     .setWarmupTasks(toTaskIds(member.assignedWarmupTasks()))
-                    .setActiveTasksPendingRevocation(toTaskIds(member.activeTasksPendingRevocation())),
+                    .setActiveTasksPendingRevocation(toTaskIds(member.activeTasksPendingRevocation()))
+                    .setStandbyTasksPendingRevocation(toTaskIds(member.standbyTasksPendingRevocation()))
+                    .setWarmupTasksPendingRevocation(toTaskIds(member.warmupTasksPendingRevocation())),
                 (short) 0
             )
         );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index 4ff347c66b7..24e8a2f2a6c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -19,6 +19,7 @@ package org.apache.kafka.coordinator.group.streams;
 import org.apache.kafka.common.errors.FencedMemberEpochException;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -27,6 +28,8 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
 import java.util.function.BiFunction;
+import java.util.function.BiPredicate;
+import java.util.stream.Collectors;
 
 /**
  * The CurrentAssignmentBuilder class encapsulates the reconciliation engine of the streams group protocol. Given the current state of a
@@ -50,23 +53,35 @@ public class CurrentAssignmentBuilder {
     private Assignment targetAssignment;
 
     /**
-     * A function which returns the current epoch of a topic-partition or -1 if the topic-partition is not assigned. The current epoch is
-     * the epoch of the current owner.
+     * A function which returns the current process ID of an active task or null if the active task
+     * is not assigned. The current process ID is the process ID of the current owner.
      */
-    private BiFunction<String, Integer, Integer> currentTaskEpoch;
+    private BiFunction<String, Integer, String> currentActiveTaskProcessId;
 
     /**
-     * The active tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
+     * A function which returns the current process IDs of a standby task or null if the standby
+     * task is not assigned. The current process IDs are the process IDs of all current owners.
+     */
+    private BiFunction<String, Integer, Set<String>> currentStandbyTaskProcessIds;
+
+    /**
+     * A function which returns the current process IDs of a warmup task or null if the warmup task
+     * is not assigned. The current process IDs are the process IDs of all current owners.
+     */
+    private BiFunction<String, Integer, Set<String>> currentWarmupTaskProcessIds;
+
+    /**
+     * The active tasks owned by the member. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks;
 
     /**
-     * The standby tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
+     * The standby tasks owned by the member. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks;
 
     /**
-     * The warmup tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
+     * The warmup tasks owned by the member. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks;
 
@@ -96,16 +111,77 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Sets a BiFunction which allows to retrieve the current epoch of a partition. This is used by the state machine to determine if a
-     * partition is free or still used by another member.
+     * Sets a BiFunction which allows to retrieve the current process ID of an active task. This is
+     * used by the state machine to determine if an active task is free or still used by another
+     * member, and if there is still a task on a specific process that is not yet revoked.
      *
-     * @param currentTaskEpoch A BiFunction which gets the epoch of a topic id / tasks id pair.
+     * @param currentActiveTaskProcessId A BiFunction which gets the memberId of a subtopology id /
+     *                                   partition id pair.
      * @return This object.
      */
-    public CurrentAssignmentBuilder withCurrentActiveTaskEpoch(
-        BiFunction<String, Integer, Integer> currentTaskEpoch
+    public CurrentAssignmentBuilder withCurrentActiveTaskProcessId(
+        BiFunction<String, Integer, String> currentActiveTaskProcessId
     ) {
-        this.currentTaskEpoch = Objects.requireNonNull(currentTaskEpoch);
+        this.currentActiveTaskProcessId = Objects.requireNonNull(currentActiveTaskProcessId);
+        return this;
+    }
+
+    /**
+     * Sets a BiFunction which allows to retrieve the current process IDs of a standby task. This is
+     * used by the state machine to determine if there is still a task on a specific process that is
+     * not yet revoked.
+     *
+     * @param currentStandbyTaskProcessIds A BiFunction which gets the memberIds of a subtopology
+     *                                     ids / partition ids pair.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withCurrentStandbyTaskProcessIds(
+        BiFunction<String, Integer, Set<String>> currentStandbyTaskProcessIds
+    ) {
+        this.currentStandbyTaskProcessIds = Objects.requireNonNull(currentStandbyTaskProcessIds);
+        return this;
+    }
+
+    /**
+     * Sets a BiFunction which allows to retrieve the current process IDs of a warmup task. This is
+     * used by the state machine to determine if there is still a task on a specific process that is
+     * not yet revoked.
+     *
+     * @param currentWarmupTaskProcessIds A BiFunction which gets the memberIds of a subtopology ids
+     *                                    / partition ids pair.
+     * @return This object.
+     */
+    public CurrentAssignmentBuilder withCurrentWarmupTaskProcessIds(
+        BiFunction<String, Integer, Set<String>> currentWarmupTaskProcessIds
+    ) {
+        this.currentWarmupTaskProcessIds = Objects.requireNonNull(currentWarmupTaskProcessIds);
+        return this;
+    }
+
+    protected CurrentAssignmentBuilder withOwnedAssignment(
+        Assignment ownedAssignment
+    ) {
+        if (ownedAssignment == null) {
+            this.ownedActiveTasks = null;
+            this.ownedStandbyTasks = null;
+            this.ownedWarmupTasks = null;
+        } else {
+            this.ownedActiveTasks = ownedAssignment.activeTasks().entrySet().stream()
+                .map(activeTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
+                    .setSubtopology(activeTaskIds.getKey())
+                    .setPartitions(new ArrayList<>(activeTaskIds.getValue())))
+                .collect(Collectors.toList());
+            this.ownedStandbyTasks = ownedAssignment.standbyTasks().entrySet().stream()
+                .map(standbyTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
+                    .setSubtopology(standbyTaskIds.getKey())
+                    .setPartitions(new ArrayList<>(standbyTaskIds.getValue())))
+                .collect(Collectors.toList());
+            this.ownedWarmupTasks = ownedAssignment.warmupTasks().entrySet().stream()
+                .map(warmupTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
+                    .setSubtopology(warmupTaskIds.getKey())
+                    .setPartitions(new ArrayList<>(warmupTaskIds.getValue())))
+                .collect(Collectors.toList());
+        }
         return this;
     }
 
@@ -182,7 +258,12 @@ public class CurrentAssignmentBuilder {
 
                 // If the member provides its owned tasks. We verify if it still
                 // owns any of the revoked tasks. If it does, we cannot progress.
-                if (ownsRevokedActiveTasks(member.activeTasksPendingRevocation())) {
+                if (
+                    ownRevokedTasks(member.activeTasksPendingRevocation(), ownedActiveTasks)
+                        || ownRevokedTasks(member.standbyTasksPendingRevocation(),
+                        ownedStandbyTasks)
+                        || ownRevokedTasks(member.warmupTasksPendingRevocation(), ownedWarmupTasks)
+                ) {
                     return member;
                 }
 
@@ -212,9 +293,12 @@ public class CurrentAssignmentBuilder {
                 // future and the group coordinator is downgraded. In this case, the
                 // best option is to fence the member to force it to rejoin the group
                 // without any tasks and to reconcile it again from scratch.
-                if (ownedActiveTasks == null || !ownedActiveTasks.isEmpty()) {
-                    throw new FencedMemberEpochException("The streams group member is in a unknown state. "
-                        + "The member must abandon all its tasks and rejoin.");
+                if ((ownedActiveTasks == null || !ownedActiveTasks.isEmpty())
+                    || (ownedStandbyTasks == null || !ownedStandbyTasks.isEmpty())
+                    || (ownedWarmupTasks == null || !ownedWarmupTasks.isEmpty())) {
+                    throw new FencedMemberEpochException(
+                        "The streams group member is in a unknown state. "
+                            + "The member must abandon all its tasks and rejoin.");
                 }
 
                 return computeNextAssignment(
@@ -229,23 +313,25 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Decides whether the current ownedActiveTasks contains any partition that is pending revocation.
+     * Decides whether the given owned tasks contains any partition that is pending revocation.
      *
      * @param assignment The assignment that has the tasks pending revocation.
+     * @param ownedTasks The set of tasks from the response.
      * @return A boolean based on the condition mentioned above.
      */
-    private boolean ownsRevokedActiveTasks(
-        Map<String, Set<Integer>> assignment
+    private static boolean ownRevokedTasks(
+        Map<String, Set<Integer>> assignment,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedTasks
     ) {
-        if (ownedActiveTasks == null) {
+        if (ownedTasks == null) {
             return true;
         }
 
-        for (StreamsGroupHeartbeatRequestData.TaskIds activeTasks : ownedActiveTasks) {
+        for (StreamsGroupHeartbeatRequestData.TaskIds owned : ownedTasks) {
             Set<Integer> tasksPendingRevocation =
-                assignment.getOrDefault(activeTasks.subtopology(), Collections.emptySet());
+                assignment.getOrDefault(owned.subtopology(), Collections.emptySet());
 
-            for (Integer partitionId : activeTasks.partitions()) {
+            for (Integer partitionId : owned.partitions()) {
                 if (tasksPendingRevocation.contains(partitionId)) {
                     return true;
                 }
@@ -256,107 +342,230 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Computes the next assignment.
+     * Takes the current currentAssignment and the targetAssignment, and generates three
+     * collections:
      *
-     * @param memberEpoch                The epoch of the member to use. This may be different from the epoch in
-     *                                   {@link CurrentAssignmentBuilder#member}.
-     * @param memberAssignedActiveTasks  The assigned active tasks of the member to use.
-     * @param memberAssignedStandbyTasks The assigned standby tasks of the member to use.
-     * @param memberAssignedWarmupTasks  The assigned warmup tasks of the member to use.
-     * @return A new StreamsGroupMember.
+     * - the resultAssignedTasks: the tasks that are assigned in both the current and target
+     * assignments.
+     * - the resultTasksPendingRevocation: the tasks that are assigned in the current
+     * assignment but not in the target assignment.
+     * - the resultTasksPendingAssignment: the tasks that are assigned in the target assignment but
+     * not in the current assignment, and can be assigned currently (i.e., they are not owned by
+     * another member, as defined by the `isUnreleasedTask` predicate).
      */
-    private StreamsGroupMember computeNextAssignment(
-        int memberEpoch,
-        Map<String, Set<Integer>> memberAssignedActiveTasks,
-        Map<String, Set<Integer>> memberAssignedStandbyTasks,
-        Map<String, Set<Integer>> memberAssignedWarmupTasks
+    private boolean computeAssignmentDifference(
+        Map<String, Set<Integer>> currentAssignment,
+        Map<String, Set<Integer>> targetAssignment,
+        Map<String, Set<Integer>> resultAssignedTasks,
+        Map<String, Set<Integer>> resultTasksPendingRevocation,
+        Map<String, Set<Integer>> resultTasksPendingAssignment,
+        BiPredicate<String, Integer> isUnreleasedTask
     ) {
         boolean hasUnreleasedTasks = false;
-        Map<String, Set<Integer>> newAssignedTasks = new HashMap<>();
-        Map<String, Set<Integer>> newTasksPendingRevocation = new HashMap<>();
-        Map<String, Set<Integer>> newTasksPendingAssignment = new HashMap<>();
 
-        Set<String> allSubtopologyIds = new HashSet<>(targetAssignment.activeTasks().keySet());
-        allSubtopologyIds.addAll(memberAssignedActiveTasks.keySet());
+        Set<String> allSubtopologyIds = new HashSet<>(targetAssignment.keySet());
+        allSubtopologyIds.addAll(currentAssignment.keySet());
 
         for (String subtopologyId : allSubtopologyIds) {
-            Set<Integer> target = targetAssignment.activeTasks()
-                .getOrDefault(subtopologyId, Collections.emptySet());
-            Set<Integer> currentAssignedTasks = memberAssignedActiveTasks
-                .getOrDefault(subtopologyId, Collections.emptySet());
-
-            // New Assigned Tasks = Previous Assigned Tasks ∩ Target
-            Set<Integer> assignedTasks = new HashSet<>(currentAssignedTasks);
-            assignedTasks.retainAll(target);
-
-            // Tasks Pending Revocation = Previous Assigned Tasks - New Assigned Tasks
-            Set<Integer> tasksPendingRevocation = new HashSet<>(currentAssignedTasks);
-            tasksPendingRevocation.removeAll(assignedTasks);
-
-            // Tasks Pending Assignment = Target - New Assigned Tasks - Unreleased Tasks
-            Set<Integer> tasksPendingAssignment = new HashSet<>(target);
-            tasksPendingAssignment.removeAll(assignedTasks);
-            hasUnreleasedTasks = tasksPendingAssignment.removeIf(partitionId ->
-                currentTaskEpoch.apply(subtopologyId, partitionId) != -1
+            Set<Integer> currentPartitions = currentAssignment.getOrDefault(subtopologyId, Collections.emptySet());
+            Set<Integer> targetPartitions = targetAssignment.getOrDefault(subtopologyId, Collections.emptySet());
+
+            // Result Assigned Partitions = Current Partitions ∩ Target Partitions
+            // i.e. we remove all partitions from the current assignment that are not in the target
+            //         assignment
+            Set<Integer> resultAssignedPartitions = new HashSet<>(currentPartitions);
+            resultAssignedPartitions.retainAll(targetPartitions);
+
+            // Result Partitions Pending Revocation = Current Partitions - Result Assigned Partitions
+            // i.e. we will ask the member to revoke all partitions in its current assignment that
+            //      are not in the target assignment
+            Set<Integer> resultPartitionsPendingRevocation = new HashSet<>(currentPartitions);
+            resultPartitionsPendingRevocation.removeAll(resultAssignedPartitions);
+
+            // Result Partitions Pending Assignment = Target Partitions - Result Assigned Partitions - Unreleased Partitions
+            // i.e. we will ask the member to assign all partitions in its target assignment,
+            //      except those that are already assigned, and those that are unrelead
+            Set<Integer> resultPartitionsPendingAssignment = new HashSet<>(targetPartitions);
+            resultPartitionsPendingAssignment.removeAll(resultAssignedPartitions);
+            hasUnreleasedTasks = resultPartitionsPendingAssignment.removeIf(partitionId ->
+                isUnreleasedTask.test(subtopologyId, partitionId)
             ) || hasUnreleasedTasks;
 
-            if (!assignedTasks.isEmpty()) {
-                newAssignedTasks.put(subtopologyId, assignedTasks);
+            if (!resultAssignedPartitions.isEmpty()) {
+                resultAssignedTasks.put(subtopologyId, resultAssignedPartitions);
             }
 
-            if (!tasksPendingRevocation.isEmpty()) {
-                newTasksPendingRevocation.put(subtopologyId, tasksPendingRevocation);
+            if (!resultPartitionsPendingRevocation.isEmpty()) {
+                resultTasksPendingRevocation.put(subtopologyId, resultPartitionsPendingRevocation);
             }
 
-            if (!tasksPendingAssignment.isEmpty()) {
-                newTasksPendingAssignment.put(subtopologyId, tasksPendingAssignment);
+            if (!resultPartitionsPendingAssignment.isEmpty()) {
+                resultTasksPendingAssignment.put(subtopologyId, resultPartitionsPendingAssignment);
             }
         }
+        return hasUnreleasedTasks;
+    }
+
+    /**
+     * Computes the next assignment.
+     *
+     * @param memberEpoch                The epoch of the member to use. This may be different from
+     *                                   the epoch in {@link CurrentAssignmentBuilder#member}.
+     * @param memberAssignedActiveTasks  The assigned active tasks of the member to use.
+     * @param memberAssignedStandbyTasks The assigned standby tasks of the member to use.
+     * @param memberAssignedWarmupTasks  The assigned warmup tasks of the member to use.
+     * @return A new StreamsGroupMember.
+     */
+    private StreamsGroupMember computeNextAssignment(
+        int memberEpoch,
+        Map<String, Set<Integer>> memberAssignedActiveTasks,
+        Map<String, Set<Integer>> memberAssignedStandbyTasks,
+        Map<String, Set<Integer>> memberAssignedWarmupTasks
+    ) {
+        Map<String, Set<Integer>> newActiveAssignedTasks = new HashMap<>();
+        Map<String, Set<Integer>> newActiveTasksPendingRevocation = new HashMap<>();
+        Map<String, Set<Integer>> newActiveTasksPendingAssignment = new HashMap<>();
+        Map<String, Set<Integer>> newStandbyAssignedTasks = new HashMap<>();
+        Map<String, Set<Integer>> newStandbyTasksPendingRevocation = new HashMap<>();
+        Map<String, Set<Integer>> newStandbyTasksPendingAssignment = new HashMap<>();
+        Map<String, Set<Integer>> newWarmupAssignedTasks = new HashMap<>();
+        Map<String, Set<Integer>> newWarmupTasksPendingRevocation = new HashMap<>();
+        Map<String, Set<Integer>> newWarmupTasksPendingAssignment = new HashMap<>();
+
+        boolean hasUnreleasedTasks = computeAssignmentDifference(
+            memberAssignedActiveTasks,
+            targetAssignment.activeTasks(),
+            newActiveAssignedTasks,
+            newActiveTasksPendingRevocation,
+            newActiveTasksPendingAssignment,
+            (subtopologyId, partitionId) ->
+                currentActiveTaskProcessId.apply(subtopologyId, partitionId) != null ||
+                    currentStandbyTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId()) ||
+                    currentWarmupTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId())
+        );
+
+        hasUnreleasedTasks = computeAssignmentDifference(
+            memberAssignedStandbyTasks,
+            targetAssignment.standbyTasks(),
+            newStandbyAssignedTasks,
+            newStandbyTasksPendingRevocation,
+            newStandbyTasksPendingAssignment,
+            (subtopologyId, partitionId) ->
+                Objects.equals(currentActiveTaskProcessId.apply(subtopologyId, partitionId),
+                    member.processId()) ||
+                    currentStandbyTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId()) ||
+                    currentWarmupTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId())
+        ) || hasUnreleasedTasks;
+
+        hasUnreleasedTasks = computeAssignmentDifference(
+            memberAssignedWarmupTasks,
+            targetAssignment.warmupTasks(),
+            newWarmupAssignedTasks,
+            newWarmupTasksPendingRevocation,
+            newWarmupTasksPendingAssignment,
+            (subtopologyId, partitionId) ->
+                Objects.equals(currentActiveTaskProcessId.apply(subtopologyId, partitionId),
+                    member.processId()) ||
+                    currentStandbyTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId()) ||
+                    currentWarmupTaskProcessIds.apply(subtopologyId, partitionId)
+                        .contains(member.processId())
+        ) || hasUnreleasedTasks;
+
+        return buildNewMember(memberEpoch, newActiveTasksPendingRevocation,
+            newStandbyTasksPendingRevocation, newWarmupTasksPendingRevocation,
+            newActiveAssignedTasks,
+            newStandbyAssignedTasks, newWarmupAssignedTasks, newActiveTasksPendingAssignment,
+            newStandbyTasksPendingAssignment, newWarmupTasksPendingAssignment, hasUnreleasedTasks);
+    }
 
-        if (!newTasksPendingRevocation.isEmpty() && ownsRevokedActiveTasks(newTasksPendingRevocation)) {
+    private StreamsGroupMember buildNewMember(
+        final int memberEpoch,
+        final Map<String, Set<Integer>> newActiveTasksPendingRevocation,
+        final Map<String, Set<Integer>> newStandbyTasksPendingRevocation,
+        final Map<String, Set<Integer>> newWarmupTasksPendingRevocation,
+        final Map<String, Set<Integer>> newActiveAssignedTasks,
+        final Map<String, Set<Integer>> newStandbyAssignedTasks,
+        final Map<String, Set<Integer>> newWarmupAssignedTasks,
+        final Map<String, Set<Integer>> newActiveTasksPendingAssignment,
+        final Map<String, Set<Integer>> newStandbyTasksPendingAssignment,
+        final Map<String, Set<Integer>> newWarmupTasksPendingAssignment,
+        final boolean hasUnreleasedTasks) {
+
+        final boolean hasTasksToBeRevoked =
+            (!newActiveTasksPendingRevocation.isEmpty() && ownRevokedTasks(
+                newActiveTasksPendingRevocation, ownedActiveTasks)) ||
+                (!newStandbyTasksPendingRevocation.isEmpty() && ownRevokedTasks(
+                    newStandbyTasksPendingRevocation, ownedStandbyTasks)) ||
+                (!newWarmupTasksPendingRevocation.isEmpty() && ownRevokedTasks(
+                    newWarmupTasksPendingRevocation, ownedWarmupTasks));
+
+        if (hasTasksToBeRevoked) {
             // If there are tasks to be revoked, the member remains in its current
             // epoch and requests the revocation of those tasks. It transitions to
             // the UNREVOKED_TASKS state to wait until the client acknowledges the
             // revocation of the tasks.
             return new StreamsGroupMember.Builder(member)
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setState(MemberState.UNREVOKED_TASKS)
                 .updateMemberEpoch(memberEpoch)
-                .setAssignedActiveTasks(newAssignedTasks)
-                .setActiveTasksPendingRevocation(newTasksPendingRevocation)
-                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
-                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .setAssignedActiveTasks(newActiveAssignedTasks)
+                .setAssignedStandbyTasks(newStandbyAssignedTasks)
+                .setAssignedWarmupTasks(newWarmupAssignedTasks)
+                .setActiveTasksPendingRevocation(newActiveTasksPendingRevocation)
+                .setStandbyTasksPendingRevocation(newStandbyTasksPendingRevocation)
+                .setWarmupTasksPendingRevocation(newWarmupTasksPendingRevocation)
                 .build();
-        } else if (!newTasksPendingAssignment.isEmpty()) {
+        } else if (
+            !newActiveTasksPendingAssignment.isEmpty() ||
+                !newStandbyTasksPendingAssignment.isEmpty() ||
+                !newWarmupTasksPendingAssignment.isEmpty()
+        ) {
             // If there are tasks to be assigned, the member transitions to the
             // target epoch and requests the assignment of those tasks. Note that
             // the tasks are directly added to the assigned tasks set. The
             // member transitions to the STABLE state or to the UNRELEASED_TASKS
             // state depending on whether there are unreleased tasks or not.
-            newTasksPendingAssignment.forEach((subtopologyId, tasks) -> newAssignedTasks
+            newActiveTasksPendingAssignment.forEach((subtopologyId, tasks) -> newActiveAssignedTasks
+                .computeIfAbsent(subtopologyId, __ -> new HashSet<>())
+                .addAll(tasks));
+            newStandbyTasksPendingAssignment.forEach(
+                (subtopologyId, tasks) -> newStandbyAssignedTasks
+                    .computeIfAbsent(subtopologyId, __ -> new HashSet<>())
+                    .addAll(tasks));
+            newWarmupTasksPendingAssignment.forEach((subtopologyId, tasks) -> newWarmupAssignedTasks
                 .computeIfAbsent(subtopologyId, __ -> new HashSet<>())
                 .addAll(tasks));
-            org.apache.kafka.coordinator.group.streams.MemberState newState =
-                hasUnreleasedTasks ? org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS
-                    : org.apache.kafka.coordinator.group.streams.MemberState.STABLE;
+            MemberState newState =
+                hasUnreleasedTasks
+                    ? MemberState.UNRELEASED_TASKS
+                    : MemberState.STABLE;
             return new StreamsGroupMember.Builder(member)
                 .setState(newState)
                 .updateMemberEpoch(targetAssignmentEpoch)
-                .setAssignedActiveTasks(newAssignedTasks)
+                .setAssignedActiveTasks(newActiveAssignedTasks)
+                .setAssignedStandbyTasks(newStandbyAssignedTasks)
+                .setAssignedWarmupTasks(newWarmupAssignedTasks)
                 .setActiveTasksPendingRevocation(Collections.emptyMap())
-                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
-                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .setStandbyTasksPendingRevocation(Collections.emptyMap())
+                .setWarmupTasksPendingRevocation(Collections.emptyMap())
                 .build();
         } else if (hasUnreleasedTasks) {
             // If there are no tasks to be revoked nor to be assigned but some
             // tasks are not available yet, the member transitions to the target
             // epoch, to the UNRELEASED_TASKS state and waits.
             return new StreamsGroupMember.Builder(member)
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setState(MemberState.UNRELEASED_TASKS)
                 .updateMemberEpoch(targetAssignmentEpoch)
-                .setAssignedActiveTasks(newAssignedTasks)
+                .setAssignedActiveTasks(newActiveAssignedTasks)
+                .setAssignedStandbyTasks(newStandbyAssignedTasks)
+                .setAssignedWarmupTasks(newWarmupAssignedTasks)
                 .setActiveTasksPendingRevocation(Collections.emptyMap())
-                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
-                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .setStandbyTasksPendingRevocation(Collections.emptyMap())
+                .setWarmupTasksPendingRevocation(Collections.emptyMap())
                 .build();
         } else {
             // Otherwise, the member transitions to the target epoch and to the
@@ -364,10 +573,12 @@ public class CurrentAssignmentBuilder {
             return new StreamsGroupMember.Builder(member)
                 .setState(MemberState.STABLE)
                 .updateMemberEpoch(targetAssignmentEpoch)
-                .setAssignedActiveTasks(newAssignedTasks)
+                .setAssignedActiveTasks(newActiveAssignedTasks)
+                .setAssignedStandbyTasks(newStandbyAssignedTasks)
+                .setAssignedWarmupTasks(newWarmupAssignedTasks)
                 .setActiveTasksPendingRevocation(Collections.emptyMap())
-                .setAssignedStandbyTasks(memberAssignedStandbyTasks)
-                .setAssignedWarmupTasks(memberAssignedWarmupTasks)
+                .setStandbyTasksPendingRevocation(Collections.emptyMap())
+                .setWarmupTasksPendingRevocation(Collections.emptyMap())
                 .build();
         }
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 4003b9a1125..11f0cc198fd 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -155,12 +155,12 @@ public class StreamsGroup implements Group {
     private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetWarmupTasksAssignment;
 
     /**
-     * The current partition epoch maps each topic-partitions to their current epoch where the epoch is the epoch of their owners. When a
-     * member revokes a partition, it removes its epochs from this map. When a member gets a partition, it adds its epochs to this map.
+     * The current task memberID maps each active/standby/warmup task to the member ID(s) their current owner. When a
+     * member revokes a partition, it removes its member ID from this map. When a member gets a partition, it adds its member ID to this map.
      */
-    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentActiveTasksEpoch;
-    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentStandbyTasksEpoch;
-    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentWarmupTasksEpoch;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, String>> currentActiveTaskProcessId;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, Set<String>>> currentStandbyTaskProcessIds;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, Set<String>>> currentWarmupTaskProcessIds;
 
     /**
      * The coordinator metrics.
@@ -198,9 +198,9 @@ public class StreamsGroup implements Group {
         this.invertedTargetActiveTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
         this.invertedTargetStandbyTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
         this.invertedTargetWarmupTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
-        this.currentActiveTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
-        this.currentStandbyTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
-        this.currentWarmupTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentActiveTaskProcessId = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentStandbyTaskProcessIds = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentWarmupTaskProcessIds = new TimelineHashMap<>(snapshotRegistry, 0);
         this.metrics = Objects.requireNonNull(metrics);
         this.topology = new TimelineObject<>(snapshotRegistry, Optional.empty());
     }
@@ -361,7 +361,7 @@ public class StreamsGroup implements Group {
             throw new IllegalArgumentException("newMember cannot be null.");
         }
         StreamsGroupMember oldMember = members.put(newMember.memberId(), newMember);
-        maybeUpdateTaskEpoch(oldMember, newMember);
+        maybeUpdateTaskProcessId(oldMember, newMember);
         updateStaticMember(newMember);
         maybeUpdateGroupState();
     }
@@ -384,7 +384,7 @@ public class StreamsGroup implements Group {
      */
     public void removeMember(String memberId) {
         StreamsGroupMember oldMember = members.remove(memberId);
-        maybeRemoveTaskEpoch(oldMember);
+        maybeRemoveTaskProcessId(oldMember);
         removeStaticMember(oldMember);
         maybeUpdateGroupState();
     }
@@ -603,20 +603,56 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Returns the current epoch of a partition or -1 if the partition does not have one.
+     * Returns the current processId of a task or null if the task does not have one.
      *
-     * @param topicId     The topic id.
-     * @param partitionId The partition id.
-     * @return The epoch or -1.
+     * @param subtopologyId     The topic id.
+     * @param taskId The task id.
+     * @return The processId or null.
      */
-    public int currentActiveTaskEpoch(
-        String topicId, int partitionId
+    public String currentActiveTaskProcessId(
+        String subtopologyId, int taskId
     ) {
-        Map<Integer, Integer> partitions = currentActiveTasksEpoch.get(topicId);
-        if (partitions == null) {
-            return -1;
+        Map<Integer, String> tasks = currentActiveTaskProcessId.get(subtopologyId);
+        if (tasks == null) {
+            return null;
         } else {
-            return partitions.getOrDefault(partitionId, -1);
+            return tasks.getOrDefault(taskId, null);
+        }
+    }
+
+    /**
+     * Returns the current member IDs of a task or empty set if the task does not have one.
+     *
+     * @param subtopologyId     The topic id.
+     * @param taskId The task id.
+     * @return The member IDs or empty set.
+     */
+    public Set<String> currentStandbyTaskProcessIds(
+        String subtopologyId, int taskId
+    ) {
+        Map<Integer, Set<String>> tasks = currentStandbyTaskProcessIds.get(subtopologyId);
+        if (tasks == null) {
+            return Collections.emptySet();
+        } else {
+            return tasks.getOrDefault(taskId, Collections.emptySet());
+        }
+    }
+
+    /**
+     * Returns the current member ID of a task or empty set if the task does not have one.
+     *
+     * @param subtopologyId     The topic id.
+     * @param taskId The task id.
+     * @return The member IDs or empty set.
+     */
+    public Set<String> currentWarmupTaskProcessIds(
+        String subtopologyId, int taskId
+    ) {
+        Map<Integer, Set<String>> tasks = currentWarmupTaskProcessIds.get(subtopologyId);
+        if (tasks == null) {
+            return Collections.emptySet();
+        } else {
+            return tasks.getOrDefault(taskId, Collections.emptySet());
         }
     }
 
@@ -904,88 +940,90 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Updates the tasks epochs based on the old and the new member.
+     * Updates the tasks process IDs based on the old and the new member.
      *
      * @param oldMember The old member.
      * @param newMember The new member.
      */
-    private void maybeUpdateTaskEpoch(
+    private void maybeUpdateTaskProcessId(
         StreamsGroupMember oldMember,
         StreamsGroupMember newMember
     ) {
-        maybeRemoveTaskEpoch(oldMember);
-        addTaskEpochs(
+        maybeRemoveTaskProcessId(oldMember);
+        addTaskProcessId(
             newMember.assignedActiveTasks(),
             newMember.assignedStandbyTasks(),
             newMember.assignedWarmupTasks(),
-            newMember.memberEpoch()
+            newMember.processId()
         );
-        addTaskEpochs(
+        addTaskProcessId(
             newMember.activeTasksPendingRevocation(),
-            emptyMap(),
-            emptyMap(),
-            newMember.memberEpoch()
+            newMember.standbyTasksPendingRevocation(),
+            newMember.warmupTasksPendingRevocation(),
+            newMember.processId()
         );
     }
 
     /**
-     * Removes the task epochs for the provided member.
+     * Removes the task process IDs for the provided member.
      *
      * @param oldMember The old member.
      */
-    private void maybeRemoveTaskEpoch(
+    private void maybeRemoveTaskProcessId(
         StreamsGroupMember oldMember
     ) {
         if (oldMember != null) {
-            removeActiveTaskEpochs(oldMember.assignedActiveTasks(), oldMember.memberEpoch());
-            removeStandbyTaskEpochs(oldMember.assignedStandbyTasks(), oldMember.memberEpoch());
-            removeWarmupTaskEpochs(oldMember.assignedWarmupTasks(), oldMember.memberEpoch());
-            removeActiveTaskEpochs(oldMember.activeTasksPendingRevocation(), oldMember.memberEpoch());
+            removeActiveTaskProcessIds(oldMember.assignedActiveTasks(), oldMember.processId());
+            removeStandbyTaskProcessIds(oldMember.assignedStandbyTasks(), oldMember.processId());
+            removeWarmupTaskProcessIds(oldMember.assignedWarmupTasks(), oldMember.processId());
+            removeActiveTaskProcessIds(oldMember.activeTasksPendingRevocation(), oldMember.processId());
+            removeStandbyTaskProcessIds(oldMember.standbyTasksPendingRevocation(), oldMember.processId());
+            removeWarmupTaskProcessIds(oldMember.warmupTasksPendingRevocation(), oldMember.processId());
         }
     }
 
-    void removeActiveTaskEpochs(
+    void removeActiveTaskProcessIds(
         Map<String, Set<Integer>> assignment,
-        int expectedEpoch
+        String processId
     ) {
-        removeTaskEpochs(assignment, currentActiveTasksEpoch, expectedEpoch);
+        removeTaskProcessIds(assignment, currentActiveTaskProcessId, processId);
     }
 
-    void removeStandbyTaskEpochs(
+    void removeStandbyTaskProcessIds(
         Map<String, Set<Integer>> assignment,
-        int expectedEpoch
+        String processId
     ) {
-        removeTaskEpochs(assignment, currentStandbyTasksEpoch, expectedEpoch);
+        removeTaskProcessIdsFromSet(assignment, currentStandbyTaskProcessIds, processId);
     }
 
-    void removeWarmupTaskEpochs(
+    void removeWarmupTaskProcessIds(
         Map<String, Set<Integer>> assignment,
-        int expectedEpoch
+        String processId
     ) {
-        removeTaskEpochs(assignment, currentWarmupTasksEpoch, expectedEpoch);
+        removeTaskProcessIdsFromSet(assignment, currentWarmupTaskProcessIds, processId);
     }
 
     /**
-     * Removes the task epochs based on the provided assignment.
+     * Removes the task process IDs based on the provided assignment.
      *
      * @param assignment    The assignment.
-     * @param expectedEpoch The expected epoch.
-     * @throws IllegalStateException if the epoch does not match the expected one. package-private for testing.
+     * @param expectedProcessId The expected processId.
+     * @throws IllegalStateException if the processId does not match the expected one. package-private for testing.
      */
-    private void removeTaskEpochs(
+    private void removeTaskProcessIds(
         Map<String, Set<Integer>> assignment,
-        TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentTasksEpoch,
-        int expectedEpoch
+        TimelineHashMap<String, TimelineHashMap<Integer, String>> currentTasksProcessId,
+        String expectedProcessId
     ) {
         assignment.forEach((subtopologyId, assignedPartitions) -> {
-            currentTasksEpoch.compute(subtopologyId, (__, partitionsOrNull) -> {
+            currentTasksProcessId.compute(subtopologyId, (__, partitionsOrNull) -> {
                 if (partitionsOrNull != null) {
                     assignedPartitions.forEach(partitionId -> {
-                        Integer prevValue = partitionsOrNull.remove(partitionId);
-                        if (prevValue != expectedEpoch) {
+                        String prevValue = partitionsOrNull.remove(partitionId);
+                        if (!Objects.equals(prevValue, expectedProcessId)) {
                             throw new IllegalStateException(
-                                String.format("Cannot remove the epoch %d from task %s_%s because the partition is " +
-                                    "still owned at a different epoch %d", expectedEpoch, subtopologyId, partitionId, prevValue));
+                                String.format("Cannot remove the processId %s from task %s_%s because the partition is " +
+                                    "still owned at a different processId %s", expectedProcessId, subtopologyId, partitionId, prevValue));
                         }
                     });
                     if (partitionsOrNull.isEmpty()) {
@@ -995,8 +1033,44 @@ public class StreamsGroup implements Group {
                     }
                 } else {
                     throw new IllegalStateException(
-                        String.format("Cannot remove the epoch %d from %s because it does not have any epoch",
-                            expectedEpoch, subtopologyId));
+                        String.format("Cannot remove the processId %s from %s because it does not have any processId",
+                            expectedProcessId, subtopologyId));
+                }
+            });
+        });
+    }
+
+    /**
+     * Removes the task process IDs based on the provided assignment.
+     *
+     * @param assignment    The assignment.
+     * @param processIdToRemove The expected processId.
+     * @throws IllegalStateException if the processId does not match the expected one. package-private for testing.
+     */
+    private void removeTaskProcessIdsFromSet(
+        Map<String, Set<Integer>> assignment,
+        TimelineHashMap<String, TimelineHashMap<Integer, Set<String>>> currentTasksProcessId,
+        String processIdToRemove
+    ) {
+        assignment.forEach((subtopologyId, assignedPartitions) -> {
+            currentTasksProcessId.compute(subtopologyId, (__, partitionsOrNull) -> {
+                if (partitionsOrNull != null) {
+                    assignedPartitions.forEach(partitionId -> {
+                        if (!partitionsOrNull.get(partitionId).remove(processIdToRemove)) {
+                            throw new IllegalStateException(
+                                String.format("Cannot remove the processId %s from task %s_%s because the task is " +
+                                    "not owned by this process ID", processIdToRemove, subtopologyId, partitionId));
+                        }
+                    });
+                    if (partitionsOrNull.isEmpty()) {
+                        return null;
+                    } else {
+                        return partitionsOrNull;
+                    }
+                } else {
+                    throw new IllegalStateException(
+                        String.format("Cannot remove the processId %s from %s because it does not have any processId",
+                            processIdToRemove, subtopologyId));
                 }
             });
         });
@@ -1008,36 +1082,36 @@ public class StreamsGroup implements Group {
      * @param activeTasks  The assigned active tasks.
      * @param standbyTasks The assigned standby tasks.
      * @param warmupTasks  The assigned warmup tasks.
-     * @param epoch        The new epoch.
+     * @param processId    The process ID.
      * @throws IllegalStateException if the partition already has an epoch assigned. package-private for testing.
      */
-    void addTaskEpochs(
+    void addTaskProcessId(
         Map<String, Set<Integer>> activeTasks,
         Map<String, Set<Integer>> standbyTasks,
         Map<String, Set<Integer>> warmupTasks,
-        int epoch
+        String processId
     ) {
-        addTaskEpochs(activeTasks, epoch, currentActiveTasksEpoch);
-        addTaskEpochs(standbyTasks, epoch, currentStandbyTasksEpoch);
-        addTaskEpochs(warmupTasks, epoch, currentWarmupTasksEpoch);
+        addTaskProcessId(activeTasks, processId, currentActiveTaskProcessId);
+        addTaskProcessIdToSet(standbyTasks, processId, currentStandbyTaskProcessIds);
+        addTaskProcessIdToSet(warmupTasks, processId, currentWarmupTaskProcessIds);
     }
 
-    void addTaskEpochs(
+    private void addTaskProcessId(
         Map<String, Set<Integer>> tasks,
-        int epoch,
-        TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentTasksEpoch
+        String processId,
+        TimelineHashMap<String, TimelineHashMap<Integer, String>> currentTaskProcessId
     ) {
         tasks.forEach((subtopologyId, assignedTaskPartitions) -> {
-            currentTasksEpoch.compute(subtopologyId, (__, partitionsOrNull) -> {
+            currentTaskProcessId.compute(subtopologyId, (__, partitionsOrNull) -> {
                 if (partitionsOrNull == null) {
                     partitionsOrNull = new TimelineHashMap<>(snapshotRegistry, assignedTaskPartitions.size());
                 }
                 for (Integer partitionId : assignedTaskPartitions) {
-                    Integer prevValue = partitionsOrNull.put(partitionId, epoch);
+                    String prevValue = partitionsOrNull.put(partitionId, processId);
                     if (prevValue != null) {
                         throw new IllegalStateException(
-                            String.format("Cannot set the epoch of %s-%s to %d because the partition is " +
-                                "still owned at epoch %d", subtopologyId, partitionId, epoch, prevValue));
+                            String.format("Cannot set the process ID of %s-%s to %s because the partition is " +
+                                "still owned by process ID %s", subtopologyId, partitionId, processId, prevValue));
                     }
                 }
                 return partitionsOrNull;
@@ -1045,6 +1119,24 @@ public class StreamsGroup implements Group {
         });
     }
 
+    private void addTaskProcessIdToSet(
+        Map<String, Set<Integer>> tasks,
+        String processId,
+        TimelineHashMap<String, TimelineHashMap<Integer, Set<String>>> currentTaskProcessId
+    ) {
+        tasks.forEach((subtopologyId, assignedTaskPartitions) -> {
+            currentTaskProcessId.compute(subtopologyId, (__, partitionsOrNull) -> {
+                if (partitionsOrNull == null) {
+                    partitionsOrNull = new TimelineHashMap<>(snapshotRegistry, assignedTaskPartitions.size());
+                }
+                for (Integer partitionId : assignedTaskPartitions) {
+                    partitionsOrNull.computeIfAbsent(partitionId, ___ -> new HashSet<>()).add(processId);
+                }
+                return partitionsOrNull;
+            });
+        });
+    }
+
     public StreamsGroupDescribeResponseData.DescribedGroup asDescribedGroup(
         long committedOffset
     ) {
@@ -1122,13 +1214,14 @@ public class StreamsGroup implements Group {
      * @return A boolean indicating whether the member has partitions in the target assignment that hasn't been revoked by other members.
      */
     public boolean waitingOnUnreleasedActiveTasks(StreamsGroupMember member) {
+        // TODO: Duplicate this + Tests?
         if (member.state() == MemberState.UNRELEASED_TASKS) {
             for (Map.Entry<String, Set<Integer>> entry : targetAssignment().get(member.memberId()).activeTasks().entrySet()) {
                 String subtopologyId = entry.getKey();
                 Set<Integer> assignedActiveTasks = member.assignedActiveTasks().getOrDefault(subtopologyId, Collections.emptySet());
 
                 for (int partition : entry.getValue()) {
-                    if (!assignedActiveTasks.contains(partition) && currentActiveTaskEpoch(subtopologyId, partition) != -1) {
+                    if (!assignedActiveTasks.contains(partition) && currentActiveTaskProcessId(subtopologyId, partition) != null) {
                         return true;
                     }
                 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index e50e450feb4..7caa1f77ff0 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -61,6 +61,8 @@ public class StreamsGroupMember {
         private Map<String, Set<Integer>> assignedStandbyTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedWarmupTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> activeTasksPendingRevocation = Collections.emptyMap();
+        private Map<String, Set<Integer>> standbyTasksPendingRevocation = Collections.emptyMap();
+        private Map<String, Set<Integer>> warmupTasksPendingRevocation = Collections.emptyMap();
 
         public Builder(String memberId) {
             this.memberId = Objects.requireNonNull(memberId);
@@ -86,6 +88,8 @@ public class StreamsGroupMember {
             this.assignedStandbyTasks = member.assignedStandbyTasks;
             this.assignedWarmupTasks = member.assignedWarmupTasks;
             this.activeTasksPendingRevocation = member.activeTasksPendingRevocation;
+            this.standbyTasksPendingRevocation = member.standbyTasksPendingRevocation;
+            this.warmupTasksPendingRevocation = member.warmupTasksPendingRevocation;
         }
 
         public Builder updateMemberEpoch(int memberEpoch) {
@@ -169,7 +173,7 @@ public class StreamsGroupMember {
             this.processId = processId.orElse(this.processId);
             return this;
         }
-        
+
         public Builder setUserEndpoint(StreamsGroupMemberMetadataValue.Endpoint userEndpoint) {
             this.userEndpoint = userEndpoint;
             return this;
@@ -190,6 +194,13 @@ public class StreamsGroupMember {
             return this;
         }
 
+        public Builder setAssignment(Assignment assignment) {
+            this.assignedActiveTasks = assignment.activeTasks();
+            this.assignedStandbyTasks = assignment.standbyTasks();
+            this.assignedWarmupTasks = assignment.warmupTasks();
+            return this;
+        }
+
         public Builder setAssignedActiveTasks(Map<String, Set<Integer>> assignedActiveTasks) {
             this.assignedActiveTasks = assignedActiveTasks;
             return this;
@@ -205,11 +216,31 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setActiveTasksPendingRevocation(Map<String, Set<Integer>> activeTasksPendingRevocation) {
+        public Builder setAssignmentPendingRevocation(Assignment assignment) {
+            this.activeTasksPendingRevocation = assignment.activeTasks();
+            this.standbyTasksPendingRevocation = assignment.standbyTasks();
+            this.warmupTasksPendingRevocation = assignment.warmupTasks();
+            return this;
+        }
+
+        public Builder setActiveTasksPendingRevocation(
+            Map<String, Set<Integer>> activeTasksPendingRevocation) {
             this.activeTasksPendingRevocation = activeTasksPendingRevocation;
             return this;
         }
 
+        public Builder setStandbyTasksPendingRevocation(
+            Map<String, Set<Integer>> standbyTasksPendingRevocation) {
+            this.standbyTasksPendingRevocation = standbyTasksPendingRevocation;
+            return this;
+        }
+
+        public Builder setWarmupTasksPendingRevocation(
+            Map<String, Set<Integer>> warmupTasksPendingRevocation) {
+            this.warmupTasksPendingRevocation = warmupTasksPendingRevocation;
+            return this;
+        }
+
         public Builder updateWith(StreamsGroupMemberMetadataValue record) {
             setInstanceId(record.instanceId());
             setRackId(record.rackId());
@@ -233,7 +264,12 @@ public class StreamsGroupMember {
             setAssignedActiveTasks(assignmentFromTaskIds(record.activeTasks()));
             setAssignedStandbyTasks(assignmentFromTaskIds(record.standbyTasks()));
             setAssignedWarmupTasks(assignmentFromTaskIds(record.warmupTasks()));
-            setActiveTasksPendingRevocation(assignmentFromTaskIds(record.activeTasksPendingRevocation()));
+            setActiveTasksPendingRevocation(
+                assignmentFromTaskIds(record.activeTasksPendingRevocation()));
+            setStandbyTasksPendingRevocation(
+                assignmentFromTaskIds(record.standbyTasksPendingRevocation()));
+            setWarmupTasksPendingRevocation(
+                assignmentFromTaskIds(record.warmupTasksPendingRevocation()));
             return this;
         }
 
@@ -263,7 +299,9 @@ public class StreamsGroupMember {
                 assignedActiveTasks,
                 assignedStandbyTasks,
                 assignedWarmupTasks,
-                activeTasksPendingRevocation
+                activeTasksPendingRevocation,
+                standbyTasksPendingRevocation,
+                warmupTasksPendingRevocation
             );
         }
     }
@@ -353,6 +391,16 @@ public class StreamsGroupMember {
      */
     private final Map<String, Set<Integer>> activeTasksPendingRevocation;
 
+    /**
+     * Standby tasks being revoked by this member.
+     */
+    private final Map<String, Set<Integer>> standbyTasksPendingRevocation;
+
+    /**
+     * Warmup tasks being revoked by this member.
+     */
+    private final Map<String, Set<Integer>> warmupTasksPendingRevocation;
+
     @SuppressWarnings("checkstyle:ParameterNumber")
     private StreamsGroupMember(
         String memberId,
@@ -371,7 +419,9 @@ public class StreamsGroupMember {
         Map<String, Set<Integer>> assignedActiveTasks,
         Map<String, Set<Integer>> assignedStandbyTasks,
         Map<String, Set<Integer>> assignedWarmupTasks,
-        Map<String, Set<Integer>> activeTasksPendingRevocation
+        Map<String, Set<Integer>> activeTasksPendingRevocation,
+        Map<String, Set<Integer>> standbyTasksPendingRevocation,
+        Map<String, Set<Integer>> warmupTasksPendingRevocation
     ) {
         this.memberId = memberId;
         this.memberEpoch = memberEpoch;
@@ -390,6 +440,8 @@ public class StreamsGroupMember {
         this.assignedStandbyTasks = assignedStandbyTasks;
         this.assignedWarmupTasks = assignedWarmupTasks;
         this.activeTasksPendingRevocation = activeTasksPendingRevocation;
+        this.standbyTasksPendingRevocation = standbyTasksPendingRevocation;
+        this.warmupTasksPendingRevocation = warmupTasksPendingRevocation;
     }
 
     /**
@@ -518,6 +570,20 @@ public class StreamsGroupMember {
         return activeTasksPendingRevocation;
     }
 
+    /**
+     * @return The set of standby tasks awaiting revocation from the member.
+     */
+    public Map<String, Set<Integer>> standbyTasksPendingRevocation() {
+        return standbyTasksPendingRevocation;
+    }
+
+    /**
+     * @return The set of warmup tasks awaiting revocation from the member.
+     */
+    public Map<String, Set<Integer>> warmupTasksPendingRevocation() {
+        return warmupTasksPendingRevocation;
+    }
+
     /**
      * @param targetAssignment The target assignment of this member in the corresponding group.
      *
@@ -591,36 +657,41 @@ public class StreamsGroupMember {
             && Objects.equals(rackId, that.rackId)
             && Objects.equals(clientId, that.clientId)
             && Objects.equals(clientHost, that.clientHost)
-            && Objects.deepEquals(topologyId, that.topologyId)
+            && Objects.equals(topologyId, that.topologyId)
             && Objects.equals(processId, that.processId)
             && Objects.equals(userEndpoint, that.userEndpoint)
             && Objects.equals(clientTags, that.clientTags)
             && Objects.equals(assignedActiveTasks, that.assignedActiveTasks)
             && Objects.equals(assignedStandbyTasks, that.assignedStandbyTasks)
             && Objects.equals(assignedWarmupTasks, that.assignedWarmupTasks)
-            && Objects.equals(activeTasksPendingRevocation, that.activeTasksPendingRevocation);
+            && Objects.equals(activeTasksPendingRevocation, that.activeTasksPendingRevocation)
+            && Objects.equals(standbyTasksPendingRevocation, that.standbyTasksPendingRevocation)
+            && Objects.equals(warmupTasksPendingRevocation, that.warmupTasksPendingRevocation);
     }
 
     @Override
     public int hashCode() {
-        int result = memberId != null ? memberId.hashCode() : 0;
-        result = 31 * result + memberEpoch;
-        result = 31 * result + previousMemberEpoch;
-        result = 31 * result + Objects.hashCode(state);
-        result = 31 * result + Objects.hashCode(instanceId);
-        result = 31 * result + Objects.hashCode(rackId);
-        result = 31 * result + rebalanceTimeoutMs;
-        result = 31 * result + Objects.hashCode(clientId);
-        result = 31 * result + Objects.hashCode(clientHost);
-        result = 31 * result + Objects.hashCode(topologyId);
-        result = 31 * result + Objects.hashCode(processId);
-        result = 31 * result + Objects.hashCode(userEndpoint);
-        result = 31 * result + Objects.hashCode(clientTags);
-        result = 31 * result + Objects.hashCode(assignedActiveTasks);
-        result = 31 * result + Objects.hashCode(assignedStandbyTasks);
-        result = 31 * result + Objects.hashCode(assignedWarmupTasks);
-        result = 31 * result + Objects.hashCode(activeTasksPendingRevocation);
-        return result;
+        return Objects.hash(
+            memberId,
+            memberEpoch,
+            previousMemberEpoch,
+            state,
+            instanceId,
+            rackId,
+            rebalanceTimeoutMs,
+            clientId,
+            clientHost,
+            topologyId,
+            processId,
+            userEndpoint,
+            clientTags,
+            assignedActiveTasks,
+            assignedStandbyTasks,
+            assignedWarmupTasks,
+            activeTasksPendingRevocation,
+            standbyTasksPendingRevocation,
+            warmupTasksPendingRevocation
+        );
     }
 
     @Override
@@ -635,10 +706,16 @@ public class StreamsGroupMember {
             ", rebalanceTimeoutMs=" + rebalanceTimeoutMs +
             ", clientId='" + clientId + '\'' +
             ", clientHost='" + clientHost + '\'' +
+            ", topologyId='" + topologyId + '\'' +
+            ", processId='" + processId + '\'' +
+            ", userEndpoint=" + userEndpoint +
+            ", clientTags=" + clientTags +
             ", assignedActiveTasks=" + assignedActiveTasks +
             ", assignedStandbyTasks=" + assignedStandbyTasks +
             ", assignedWarmupTasks=" + assignedWarmupTasks +
             ", activeTasksPendingRevocation=" + activeTasksPendingRevocation +
+            ", standbyTasksPendingRevocation=" + standbyTasksPendingRevocation +
+            ", warmupTasksPendingRevocation=" + warmupTasksPendingRevocation +
             ')';
     }
 
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
index b1a8ea68aab..bcb0e6b6eed 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -33,7 +33,11 @@
     { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned warm-up tasks for this streams client." },
     { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskIds",
-      "about": "The active tasks that must be revoked by this member." }
+      "about": "The active tasks that must be revoked by this member." },
+    { "name": "StandbyTasksPendingRevocation", "versions": "0+", "type": "[]TaskIds",
+      "about": "The standby tasks that must be revoked by this member." },
+    { "name": "WarmupTasksPendingRevocation", "versions": "0+", "type": "[]TaskIds",
+      "about": "The warmup tasks that must be revoked by this member." }
   ],
   "commonStructs": [
     { "name": "TaskIds", "versions": "0+", "fields": [
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 58d3a4e5ecc..bf458507eac 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -463,7 +463,6 @@ public class GroupMetadataManagerTest {
                 1,
                 new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())
             )
-            .withCurrentActiveTaskEpoch((a, b) -> 1)
             .withOwnedActiveTasks(Collections.emptyList())
             .withOwnedStandbyTasks(Collections.emptyList())
             .withOwnedWarmupTasks(Collections.emptyList())
@@ -525,7 +524,6 @@ public class GroupMetadataManagerTest {
                 1,
                 new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())
             )
-            .withCurrentActiveTaskEpoch((a, b) -> 1)
             .withOwnedActiveTasks(Collections.emptyList())
             .withOwnedStandbyTasks(Collections.emptyList())
             .withOwnedWarmupTasks(Collections.emptyList())
@@ -596,7 +594,7 @@ public class GroupMetadataManagerTest {
             CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
                 groupId,
                 heartbeatResult.response().memberId(),
-                TaskAssignmentTestUtil.mkAssignment(TaskAssignmentTestUtil.mkTaskAssignment(subtopologyId, 0, 1, 2)),
+                TaskAssignmentTestUtil.mkTasksPerSubtopology(TaskAssignmentTestUtil.mkTasks(subtopologyId, 0, 1, 2)),
                 Collections.emptyMap(),
                 Collections.emptyMap()
             )
@@ -9312,7 +9310,7 @@ public class GroupMetadataManagerTest {
                 .setGroupId(streamsGroupIds.get(1))
                 .setMembers(Collections.singletonList(
                     memberBuilder.build().asStreamsGroupDescribeMember(
-                        new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())
+                        TaskAssignmentTestUtil.mkAssignment(Collections.emptyMap())
                     )
                 ))
                 .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
@@ -9382,8 +9380,8 @@ public class GroupMetadataManagerTest {
         describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
             .setGroupId(streamsGroupId)
             .setMembers(Arrays.asList(
-                memberBuilder1.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())),
-                memberBuilder2.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(assignmentMap, assignmentMap, assignmentMap))
+                memberBuilder1.build().asStreamsGroupDescribeMember(TaskAssignmentTestUtil.mkAssignment(Collections.emptyMap())),
+                memberBuilder2.build().asStreamsGroupDescribeMember(TaskAssignmentTestUtil.mkAssignment(assignmentMap, assignmentMap, assignmentMap))
             ))
             .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
             .setGroupEpoch(epoch + 2);
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
index ccec91a46db..57a48e2d365 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -26,8 +26,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasks;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasksPerSubtopology;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
@@ -42,14 +42,14 @@ public class AssignmentTest {
 
     @Test
     public void testAttributes() {
-        Map<String, Set<Integer>> activeTasks = mkAssignment(
-            mkTaskAssignment("subtopology1", 1, 2, 3)
+        Map<String, Set<Integer>> activeTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology1", 1, 2, 3)
         );
-        Map<String, Set<Integer>> standbyTasks = mkAssignment(
-            mkTaskAssignment("subtopology2", 9, 8, 7)
+        Map<String, Set<Integer>> standbyTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology2", 9, 8, 7)
         );
-        Map<String, Set<Integer>> warmupTasks = mkAssignment(
-            mkTaskAssignment("subtopology3", 4, 5, 6)
+        Map<String, Set<Integer>> warmupTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology3", 4, 5, 6)
         );
         Assignment assignment = new Assignment(activeTasks, standbyTasks, warmupTasks);
 
@@ -92,23 +92,23 @@ public class AssignmentTest {
         Assignment assignment = Assignment.fromRecord(record);
 
         assertEquals(
-            mkAssignment(
-                mkTaskAssignment(subtopology1, 1, 2, 3),
-                mkTaskAssignment(subtopology2, 4, 5, 6)
+            mkTasksPerSubtopology(
+                mkTasks(subtopology1, 1, 2, 3),
+                mkTasks(subtopology2, 4, 5, 6)
             ),
             assignment.activeTasks()
         );
         assertEquals(
-            mkAssignment(
-                mkTaskAssignment(subtopology1, 7, 8, 9),
-                mkTaskAssignment(subtopology2, 1, 2, 3)
+            mkTasksPerSubtopology(
+                mkTasks(subtopology1, 7, 8, 9),
+                mkTasks(subtopology2, 1, 2, 3)
             ),
             assignment.standbyTasks()
         );
         assertEquals(
-            mkAssignment(
-                mkTaskAssignment(subtopology1, 4, 5, 6),
-                mkTaskAssignment(subtopology2, 7, 8, 9)
+            mkTasksPerSubtopology(
+                mkTasks(subtopology1, 4, 5, 6),
+                mkTasks(subtopology2, 7, 8, 9)
             ),
             assignment.warmupTasks()
         );
@@ -116,14 +116,14 @@ public class AssignmentTest {
 
     @Test
     public void testEquals() {
-        Map<String, Set<Integer>> activeTasks = mkAssignment(
-            mkTaskAssignment("subtopology1", 1, 2, 3)
+        Map<String, Set<Integer>> activeTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology1", 1, 2, 3)
         );
-        Map<String, Set<Integer>> standbyTasks = mkAssignment(
-            mkTaskAssignment("subtopology2", 9, 8, 7)
+        Map<String, Set<Integer>> standbyTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology2", 9, 8, 7)
         );
-        Map<String, Set<Integer>> warmupTasks = mkAssignment(
-            mkTaskAssignment("subtopology3", 4, 5, 6)
+        Map<String, Set<Integer>> warmupTasks = mkTasksPerSubtopology(
+            mkTasks("subtopology3", 4, 5, 6)
         );
 
         assertEquals(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
index 3f1bf27b16d..93e40214dd8 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -19,362 +19,403 @@ package org.apache.kafka.coordinator.group.streams;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.FencedMemberEpochException;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.TaskRole;
 import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
 
 import java.util.Arrays;
 import java.util.Collections;
 
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasks;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 public class CurrentAssignmentBuilderTest {
 
-    @Test
-    public void testStableToStable() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testStableToStable(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
-        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
-            .setMemberEpoch(10)
-            .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
-            .build();
+        StreamsGroupMember member =
+            new StreamsGroupMember.Builder("member")
+                .setState(MemberState.STABLE)
+                .setProcessId("process")
+                .setMemberEpoch(10)
+                .setPreviousMemberEpoch(10)
+                .setAssignment(
+                    mkAssignment(
+                        taskRole,
+                        mkTasks(subtopologyId1, 1, 2),
+                        mkTasks(subtopologyId2, 3, 4)))
+                .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 4)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setState(MemberState.STABLE)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+                .setAssignment(mkAssignment(
+                    taskRole,
+                    mkTasks(subtopologyId1, 1, 2),
+                    mkTasks(subtopologyId2, 3, 4)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testStableToStableWithNewTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testStableToStableWithNewTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setState(MemberState.STABLE)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2, 4),
+                mkTasks(subtopologyId2, 3, 4, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setState(MemberState.STABLE)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
-                    mkTaskAssignment(subtopologyId2, 4, 5, 6, 7)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 1, 2, 4),
+                    mkTasks(subtopologyId2, 3, 4, 7)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testStableToUnrevokedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testStableToUnrevokedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setState(MemberState.STABLE)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 4, 5)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setState(MemberState.UNREVOKED_TASKS)
+                .setProcessId("process")
                 .setMemberEpoch(10)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 5, 6)))
-                .setActiveTasksPendingRevocation(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 1),
-                    mkTaskAssignment(subtopologyId2, 4)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2),
+                    mkTasks(subtopologyId2, 4)))
+                .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 1),
+                    mkTasks(subtopologyId2, 3)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testStableToUnreleasedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testStableToUnreleasedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setState(MemberState.STABLE)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2, 4),
+                mkTasks(subtopologyId2, 3, 4, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setState(MemberState.UNRELEASED_TASKS)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 1, 2),
+                    mkTasks(subtopologyId2, 3, 4)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testStableToUnreleasedTasksWithOwnedTasksNotHavingRevokedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testStableToUnreleasedTasksWithOwnedTasksNotHavingRevokedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+            .setState(MemberState.STABLE)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 4, 5, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, __) ->
-                subtopologyId2.equals(subtopologyId) ? 10 : -1
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1, 2),
+                mkTasks(subtopologyId2, 3, 5)))
+            .withCurrentActiveTaskProcessId((subtopologyId, __) ->
+                subtopologyId2.equals(subtopologyId) ? "process" : null
             )
-            .withOwnedActiveTasks(Collections.emptyList())
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
+            .withOwnedAssignment(mkAssignment(taskRole))
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setState(MemberState.UNRELEASED_TASKS)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 4, 5)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 1, 2),
+                    mkTasks(subtopologyId2, 3)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnrevokedTasksToStable() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnrevokedTasksToStable(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setState(MemberState.UNREVOKED_TASKS)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1),
-                mkTaskAssignment(subtopologyId2, 4)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1),
+                mkTasks(subtopologyId2, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
-            .withOwnedActiveTasks(Arrays.asList(
-                new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId1)
-                    .setPartitions(Arrays.asList(2, 3)),
-                new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId2)
-                    .setPartitions(Arrays.asList(5, 6))))
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
+            .withOwnedAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setState(MemberState.STABLE)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2, 3),
+                    mkTasks(subtopologyId2, 5, 6)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testRemainsInUnrevokedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testRemainsInUnrevokedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setState(MemberState.UNREVOKED_TASKS)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1),
-                mkTaskAssignment(subtopologyId2, 4)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1),
+                mkTasks(subtopologyId2, 4)))
             .build();
 
-        org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder currentAssignmentBuilder = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(
+        CurrentAssignmentBuilder currentAssignmentBuilder = new CurrentAssignmentBuilder(
             member)
-            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1);
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet());
 
         assertEquals(
             member,
             currentAssignmentBuilder
-                .withOwnedActiveTasks(null)
+                .withOwnedAssignment(null)
                 .build()
         );
 
         assertEquals(
             member,
             currentAssignmentBuilder
-                .withOwnedActiveTasks(Arrays.asList(
-                    new StreamsGroupHeartbeatRequestData.TaskIds()
-                        .setSubtopology(subtopologyId1)
-                        .setPartitions(Arrays.asList(1, 2, 3)),
-                    new StreamsGroupHeartbeatRequestData.TaskIds()
-                        .setSubtopology(subtopologyId2)
-                        .setPartitions(Arrays.asList(5, 6))))
+                .withOwnedAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 1, 2, 3),
+                    mkTasks(subtopologyId2, 5, 6)))
                 .build()
         );
 
         assertEquals(
             member,
             currentAssignmentBuilder
-                .withOwnedActiveTasks(Arrays.asList(
-                    new StreamsGroupHeartbeatRequestData.TaskIds()
-                        .setSubtopology(subtopologyId1)
-                        .setPartitions(Arrays.asList(2, 3)),
-                    new StreamsGroupHeartbeatRequestData.TaskIds()
-                        .setSubtopology(subtopologyId2)
-                        .setPartitions(Arrays.asList(4, 5, 6))))
+                .withOwnedAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2, 3),
+                    mkTasks(subtopologyId2, 4, 5, 6)))
                 .build()
         );
     }
 
-    @Test
-    public void testUnrevokedTasksToUnrevokedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnrevokedTasksToUnrevokedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setState(MemberState.UNREVOKED_TASKS)
+            .setProcessId("process")
             .setMemberEpoch(10)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 1),
-                mkTaskAssignment(subtopologyId2, 4)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 1),
+                mkTasks(subtopologyId2, 4)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
-            .withOwnedActiveTasks(Arrays.asList(
-                new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId1)
-                    .setPartitions(Arrays.asList(2, 3)),
-                new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId2)
-                    .setPartitions(Arrays.asList(5, 6))))
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withOwnedAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setState(MemberState.UNREVOKED_TASKS)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(10)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 3),
-                    mkTaskAssignment(subtopologyId2, 6)))
-                .setActiveTasksPendingRevocation(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2),
-                    mkTaskAssignment(subtopologyId2, 5)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 3),
+                    mkTasks(subtopologyId2, 6)))
+                .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2),
+                    mkTasks(subtopologyId2, 5)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnrevokedTasksToUnreleasedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnrevokedTasksToUnreleasedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+            .setState(MemberState.UNREVOKED_TASKS)
+            .setProcessId("process")
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3, 4),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .withOwnedActiveTasks(Arrays.asList(
                 new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
@@ -382,193 +423,304 @@ public class CurrentAssignmentBuilderTest {
                 new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId2)
                     .setPartitions(Arrays.asList(5, 6))))
+            .withOwnedStandbyTasks(Collections.emptyList())
+            .withOwnedWarmupTasks(Collections.emptyList())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+                .setState(MemberState.UNRELEASED_TASKS)
+                .setProcessId("process")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(11)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2, 3),
+                    mkTasks(subtopologyId2, 5, 6)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnreleasedTasksToStable() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnreleasedTasksToStable(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process1")
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.singleton("process"))
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) ->
+                Collections.singleton("process"))
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setState(MemberState.STABLE)
+                .setProcessId("process1")
                 .setMemberEpoch(12)
                 .setPreviousMemberEpoch(11)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2, 3),
-                    mkTaskAssignment(subtopologyId2, 5, 6)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2, 3),
+                    mkTasks(subtopologyId2, 5, 6)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnreleasedTasksToStableWithNewTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnreleasedTasksToStableWithNewTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process1")
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3, 4),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.STABLE)
+                .setState(MemberState.STABLE)
+                .setProcessId("process1")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(11)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2, 3, 4),
-                    mkTaskAssignment(subtopologyId2, 5, 6, 7)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2, 3, 4),
+                    mkTasks(subtopologyId2, 5, 6, 7)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnreleasedTasksToUnreleasedTasks() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnreleasedTasksToUnreleasedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process")
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3, 4),
-                mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3, 4),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.singleton("process"))
+            .withCurrentWarmupTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.singleton("process"))
+            .build();
+
+        assertEquals(member, updatedMember);
+    }
+
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnreleasedTasksToUnreleasedTasksOtherUnreleasedTaskRole(TaskRole taskRole) {
+        // The unreleased task is owned by a task of a different role on the same process.
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process")
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3, 4),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> (taskRole == TaskRole.STANDBY)
+                    ? Collections.emptySet() : Collections.singleton("process"))
+            .withCurrentWarmupTaskProcessIds(
+                (subtopologyId, partitionId) -> (taskRole == TaskRole.STANDBY)
+                    ? Collections.singleton("process") : Collections.emptySet())
             .build();
 
         assertEquals(member, updatedMember);
     }
 
     @Test
-    public void testUnreleasedTasksToUnrevokedTasks() {
+    public void testUnreleasedTasksToUnreleasedTasksAnyActiveOwner() {
+        // The unreleased task remains unreleased, because it is owned by any other instance in
+        // an active role, no matter the process.
+        // The task that is not unreleased can be assigned.
+        String subtopologyId1 = Uuid.randomUuid().toString();
+        String subtopologyId2 = Uuid.randomUuid().toString();
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process")
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignment(mkAssignment(TaskRole.ACTIVE,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
+            .build();
+
+        StreamsGroupMember expectedMember = new StreamsGroupMember.Builder("member")
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process")
+            .setMemberEpoch(11)
+            .setPreviousMemberEpoch(11)
+            .setAssignment(mkAssignment(TaskRole.ACTIVE,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .build();
+
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(11, mkAssignment(TaskRole.ACTIVE,
+                mkTasks(subtopologyId1, 2, 3, 4),
+                mkTasks(subtopologyId2, 5, 6, 7)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) ->
+                (subtopologyId.equals(subtopologyId1) && partitionId == 4) ? "anyOtherProcess"
+                    : null)
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .build();
+
+        assertEquals(expectedMember, updatedMember);
+    }
+
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnreleasedTasksToUnrevokedTasks(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNRELEASED_TASKS)
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setProcessId("process1")
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2, 3),
-                mkTaskAssignment(subtopologyId2, 5, 6)))
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2, 3),
+                mkTasks(subtopologyId2, 5, 6)))
             .build();
 
-        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
-                .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS)
+                .setState(MemberState.UNREVOKED_TASKS)
+                .setProcessId("process1")
                 .setMemberEpoch(11)
                 .setPreviousMemberEpoch(11)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 3),
-                    mkTaskAssignment(subtopologyId2, 6)))
-                .setActiveTasksPendingRevocation(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 2),
-                    mkTaskAssignment(subtopologyId2, 5)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 3),
+                    mkTasks(subtopologyId2, 6)))
+                .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 2),
+                    mkTasks(subtopologyId2, 5)))
                 .build(),
             updatedMember
         );
     }
 
-    @Test
-    public void testUnknownState() {
+    @ParameterizedTest
+    @EnumSource(TaskRole.class)
+    public void testUnknownState(TaskRole taskRole) {
         String subtopologyId1 = Uuid.randomUuid().toString();
         String subtopologyId2 = Uuid.randomUuid().toString();
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member")
-            .setState(org.apache.kafka.coordinator.group.streams.MemberState.UNKNOWN)
+            .setState(MemberState.UNKNOWN)
             .setMemberEpoch(11)
             .setPreviousMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 2),
-                mkTaskAssignment(subtopologyId2, 5)))
+            .setProcessId("process")
+            .setAssignment(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .setAssignmentPendingRevocation(mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 2),
+                mkTasks(subtopologyId2, 5)))
             .build();
 
         // When the member is in an unknown state, the member is first to force
         // a reset of the client side member state.
-        assertThrows(FencedMemberEpochException.class, () -> new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
-            .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
+        assertThrows(FencedMemberEpochException.class, () -> new CurrentAssignmentBuilder(member)
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
             .build());
 
         // Then the member rejoins with no owned tasks.
         StreamsGroupMember updatedMember = new CurrentAssignmentBuilder(member)
-            .withTargetAssignment(12, new Assignment(mkAssignment(
-                mkTaskAssignment(subtopologyId1, 3),
-                mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 11)
-            .withOwnedActiveTasks(Collections.emptyList())
+            .withTargetAssignment(12, mkAssignment(taskRole,
+                mkTasks(subtopologyId1, 3),
+                mkTasks(subtopologyId2, 6)))
+            .withCurrentActiveTaskProcessId((subtopologyId, partitionId) -> "process")
+            .withCurrentStandbyTaskProcessIds(
+                (subtopologyId, partitionId) -> Collections.emptySet())
+            .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
+            .withOwnedAssignment(mkAssignment(taskRole))
             .build();
 
         assertEquals(
             new StreamsGroupMember.Builder("member")
                 .setState(MemberState.STABLE)
+                .setProcessId("process")
                 .setMemberEpoch(12)
                 .setPreviousMemberEpoch(11)
-                .setAssignedActiveTasks(mkAssignment(
-                    mkTaskAssignment(subtopologyId1, 3),
-                    mkTaskAssignment(subtopologyId2, 6)))
+                .setAssignment(mkAssignment(taskRole,
+                    mkTasks(subtopologyId1, 3),
+                    mkTasks(subtopologyId2, 6)))
                 .build(),
             updatedMember
         );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
index ed5c93d4b86..8e39ae949da 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
@@ -20,7 +20,6 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import org.apache.kafka.coordinator.group.CoordinatorRecord;
 
 public class StreamsGroupBuilder {
@@ -49,9 +48,8 @@ public class StreamsGroupBuilder {
         return this;
     }
 
-    public StreamsGroupBuilder withAssignment(String memberId,
-        Map<String, Set<Integer>> assignment) {
-        this.assignments.put(memberId, new Assignment(assignment));
+    public StreamsGroupBuilder withAssignment(String memberId, Assignment assignment) {
+        this.assignments.put(memberId, assignment);
         return this;
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index 35ab964d1b6..0e5a0ffef07 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -16,9 +16,6 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
@@ -29,13 +26,16 @@ import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
 import java.util.Optional;
 import java.util.OptionalInt;
 
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasks;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasksPerSubtopology;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
 
@@ -58,10 +58,11 @@ public class StreamsGroupMemberTest {
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)))
             .build();
 
         assertEquals("member-id", member.memberId());
@@ -79,19 +80,19 @@ public class StreamsGroupMemberTest {
             member.clientTags()
         );
         assertEquals(
-            mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)),
             member.assignedActiveTasks()
         );
         assertEquals(
-            mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)),
             member.assignedStandbyTasks()
         );
         assertEquals(
-            mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)),
             member.assignedWarmupTasks()
         );
         assertEquals(
-            mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)),
             member.activeTasksPendingRevocation()
         );
     }
@@ -113,10 +114,11 @@ public class StreamsGroupMemberTest {
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)))
             .build();
 
         StreamsGroupMember member2 = new StreamsGroupMember.Builder("member-id")
@@ -131,10 +133,11 @@ public class StreamsGroupMemberTest {
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)))
             .build();
 
         StreamsGroupMember member3 = new StreamsGroupMember.Builder("member3-id")
@@ -149,10 +152,11 @@ public class StreamsGroupMemberTest {
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)))
             .build();
 
         assertEquals(member1, member2);
@@ -176,10 +180,11 @@ public class StreamsGroupMemberTest {
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
-            .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
-            .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
-            .setActiveTasksPendingRevocation(mkAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 2, 1)))
             .build();
 
         // This is a no-op.
@@ -244,19 +249,27 @@ public class StreamsGroupMemberTest {
             .setState((byte) 1)
             .setActiveTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId1)
-                .setPartitions(Arrays.asList(1, 2, 3)))
+                .setPartitions(Arrays.asList(1, 2)))
             )
             .setStandbyTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId2)
-                .setPartitions(Arrays.asList(6, 5, 4)))
+                .setPartitions(Arrays.asList(3, 4)))
             )
             .setWarmupTasks(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId1)
-                .setPartitions(Arrays.asList(7, 8, 9)))
+                .setPartitions(Arrays.asList(5, 6)))
             )
             .setActiveTasksPendingRevocation(Collections.singletonList(new TaskIds()
                 .setSubtopology(subtopologyId2)
-                .setPartitions(Arrays.asList(2, 3, 1)))
+                .setPartitions(Arrays.asList(7, 8)))
+            )
+            .setStandbyTasksPendingRevocation(Collections.singletonList(new TaskIds()
+                .setSubtopology(subtopologyId1)
+                .setPartitions(Arrays.asList(9, 10)))
+            )
+            .setWarmupTasksPendingRevocation(Collections.singletonList(new TaskIds()
+                .setSubtopology(subtopologyId2)
+                .setPartitions(Arrays.asList(11, 12)))
             );
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
@@ -266,10 +279,12 @@ public class StreamsGroupMemberTest {
         assertEquals(10, member.memberEpoch());
         assertEquals(9, member.previousMemberEpoch());
         assertEquals(MemberState.STABLE, member.state());
-        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)), member.assignedActiveTasks());
-        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)), member.assignedStandbyTasks());
-        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)), member.assignedWarmupTasks());
-        assertEquals(mkAssignment(mkTaskAssignment(subtopologyId2, 2, 3, 1)), member.activeTasksPendingRevocation());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId1, 1, 2)), member.assignedActiveTasks());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId2, 3, 4)), member.assignedStandbyTasks());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId1, 5, 6)), member.assignedWarmupTasks());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId2, 7, 8)), member.activeTasksPendingRevocation());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId1, 9, 10)), member.standbyTasksPendingRevocation());
+        assertEquals(mkTasksPerSubtopology(mkTasks(subtopologyId2, 11, 12)), member.warmupTasksPendingRevocation());
     }
 
     @Test
@@ -277,11 +292,9 @@ public class StreamsGroupMemberTest {
         String subTopology1 = Uuid.randomUuid().toString();
         String subTopology2 = Uuid.randomUuid().toString();
         String subTopology3 = Uuid.randomUuid().toString();
-        String subTopology4 = Uuid.randomUuid().toString();
         List<Integer> assignedTasks1 = Arrays.asList(0, 1, 2);
         List<Integer> assignedTasks2 = Arrays.asList(3, 4, 5);
         List<Integer> assignedTasks3 = Arrays.asList(6, 7, 8);
-        List<Integer> assignedTasks4 = Arrays.asList(5, 6, 7);
         int epoch = 10;
         StreamsGroupCurrentMemberAssignmentValue record = new StreamsGroupCurrentMemberAssignmentValue()
             .setMemberEpoch(epoch)
@@ -294,10 +307,7 @@ public class StreamsGroupMemberTest {
                 .setPartitions(assignedTasks2)))
             .setWarmupTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
                 .setSubtopology(subTopology3)
-                .setPartitions(assignedTasks3)))
-            .setActiveTasksPendingRevocation(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subTopology4)
-                .setPartitions(assignedTasks4)));
+                .setPartitions(assignedTasks3)));
         String memberId = Uuid.randomUuid().toString();
         String clientId = "clientId";
         String instanceId = "instanceId";
@@ -329,9 +339,6 @@ public class StreamsGroupMemberTest {
             .setAssignedWarmupTasks(
                 mkMap(mkEntry(subTopology3, new HashSet<>(assignedTasks3)))
             )
-            .setActiveTasksPendingRevocation(
-                mkMap(mkEntry(subTopology3, new HashSet<>(assignedTasks4)))
-            )
             .build();
 
         StreamsGroupDescribeResponseData.Member actual = member.asStreamsGroupDescribeMember(targetAssignment);
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 8d2a0bfa418..a7066ec7915 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -40,8 +40,8 @@ import java.util.OptionalLong;
 import static java.util.Collections.emptyMap;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasks;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasksPerSubtopology;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -153,7 +153,7 @@ public class StreamsGroupTest {
     }
 
     @Test
-    public void testUpdatingMemberUpdatesPartitionEpoch() {
+    public void testUpdatingMemberUpdatesProcessId() {
         String fooSubtopology = "foo-sub";
         String barSubtopology = "bar-sub";
         String zarSubtopology = "zar-sub";
@@ -162,87 +162,108 @@ public class StreamsGroupTest {
         StreamsGroupMember member;
 
         member = new StreamsGroupMember.Builder("member")
-            .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(fooSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(barSubtopology, 4, 5, 6)))
+            .setProcessId("process")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 1)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 2)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 3)))
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 4)))
+            .setStandbyTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 5)))
+            .setWarmupTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 6)))
             .build();
 
         streamsGroup.updateMember(member);
 
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 1));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 2));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 3));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 4));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 5));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 6));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 7));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 8));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 9));
+        assertEquals("process", streamsGroup.currentActiveTaskProcessId(fooSubtopology, 1));
+        assertEquals(Collections.singleton("process"),
+            streamsGroup.currentStandbyTaskProcessIds(fooSubtopology, 2));
+        assertEquals(Collections.singleton("process"),
+            streamsGroup.currentWarmupTaskProcessIds(fooSubtopology, 3));
+        assertEquals("process", streamsGroup.currentActiveTaskProcessId(barSubtopology, 4));
+        assertEquals(Collections.singleton("process"),
+            streamsGroup.currentStandbyTaskProcessIds(barSubtopology, 5));
+        assertEquals(Collections.singleton("process"),
+            streamsGroup.currentWarmupTaskProcessIds(barSubtopology, 6));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 7));
+        assertEquals(Collections.emptySet(),
+            streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 8));
+        assertEquals(Collections.emptySet(),
+            streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 9));
 
         member = new StreamsGroupMember.Builder(member)
-            .setMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(barSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(zarSubtopology, 4, 5, 6)))
+            .setProcessId("process1")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 1)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 2)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 3)))
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 4)))
+            .setStandbyTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 5)))
+            .setWarmupTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 6)))
             .build();
 
         streamsGroup.updateMember(member);
 
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 1));
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 2));
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 3));
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 4));
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 5));
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 6));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 7));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 8));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 9));
+        assertEquals("process1", streamsGroup.currentActiveTaskProcessId(fooSubtopology, 1));
+        assertEquals(Collections.singleton("process1"),
+            streamsGroup.currentStandbyTaskProcessIds(fooSubtopology, 2));
+        assertEquals(Collections.singleton("process1"),
+            streamsGroup.currentWarmupTaskProcessIds(fooSubtopology, 3));
+        assertEquals("process1", streamsGroup.currentActiveTaskProcessId(barSubtopology, 4));
+        assertEquals(Collections.singleton("process1"),
+            streamsGroup.currentStandbyTaskProcessIds(barSubtopology, 5));
+        assertEquals(Collections.singleton("process1"),
+            streamsGroup.currentWarmupTaskProcessIds(barSubtopology, 6));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 7));
+        assertEquals(Collections.emptySet(),
+            streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 8));
+        assertEquals(Collections.emptySet(),
+            streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 9));
     }
 
     @Test
-    public void testUpdatingMemberUpdatesPartitionEpochWhenPartitionIsReassignedBeforeBeingRevoked() {
+    public void testUpdatingMemberUpdatesTaskProcessIdWhenPartitionIsReassignedBeforeBeingRevoked() {
         String fooSubtopologyId = "foo-sub";
 
         StreamsGroup streamsGroup = createStreamsGroup("foo");
         StreamsGroupMember member;
 
         member = new StreamsGroupMember.Builder("member")
-            .setMemberEpoch(10)
+            .setProcessId("process")
             .setAssignedActiveTasks(emptyMap())
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1)))
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)))
+            .setStandbyTasksPendingRevocation(
+                mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 2)))
+            .setWarmupTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 3)))
             .build();
 
         streamsGroup.updateMember(member);
 
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopologyId, 1));
+        assertEquals("process", streamsGroup.currentActiveTaskProcessId(fooSubtopologyId, 1));
 
         member = new StreamsGroupMember.Builder(member)
-            .setMemberEpoch(11)
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
-            .setAssignedStandbyTasks(emptyMap())
-            .setAssignedWarmupTasks(emptyMap())
+            .setProcessId("process1")
+            .setAssignedActiveTasks(
+                mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)))
+            .setAssignedStandbyTasks(
+                mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 2)))
+            .setAssignedWarmupTasks(
+                mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 3)))
             .setActiveTasksPendingRevocation(emptyMap())
             .build();
 
         streamsGroup.updateMember(member);
 
-        assertEquals(11, streamsGroup.currentActiveTaskEpoch(fooSubtopologyId, 1));
+        assertEquals("process1", streamsGroup.currentActiveTaskProcessId(fooSubtopologyId, 1));
     }
 
     @Test
-    public void testUpdatingMemberUpdatesPartitionEpochWhenPartitionIsNotReleased() {
+    public void testUpdatingMemberUpdatesTaskProcessIdWhenPartitionIsNotReleased() {
         String fooSubtopologyId = "foo-sub";
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
         StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
-            .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setProcessId("process")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)))
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
             .build();
@@ -250,8 +271,8 @@ public class StreamsGroupTest {
         streamsGroup.updateMember(m1);
 
         StreamsGroupMember m2 = new StreamsGroupMember.Builder("m2")
-            .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setProcessId("process")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)))
             .setAssignedStandbyTasks(emptyMap())
             .setAssignedWarmupTasks(emptyMap())
             .build();
@@ -262,54 +283,54 @@ public class StreamsGroupTest {
     }
 
     @Test
-    public void testRemoveTaskEpochs() {
+    public void testRemoveActiveTaskProcessIds() {
         String fooSubtopologyId = "foo-sub";
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
         // Removing should fail because there is no epoch set.
-        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
-            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
-            10
+        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskProcessIds(
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)),
+            "process"
         ));
 
         StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
-            .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setProcessId("process")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)))
             .build();
 
         streamsGroup.updateMember(m1);
 
         // Removing should fail because the expected epoch is incorrect.
-        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
-            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
-            11
+        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskProcessIds(
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)),
+            "process1"
         ));
     }
 
     @Test
-    public void testAddPartitionEpochs() {
+    public void testAddTaskProcessIds() {
         String fooSubtopologyId = "foo-sub";
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
-        streamsGroup.addTaskEpochs(
-            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
-            emptyMap(),
-            emptyMap(),
-            10
+        streamsGroup.addTaskProcessId(
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)),
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 2)),
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 3)),
+            "process"
         );
 
         // Changing the epoch should fail because the owner of the partition
         // should remove it first.
-        assertThrows(IllegalStateException.class, () -> streamsGroup.addTaskEpochs(
-            mkAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
-            emptyMap(),
-            emptyMap(),
-            11
+        assertThrows(IllegalStateException.class, () -> streamsGroup.addTaskProcessId(
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 1)),
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 2)),
+            mkTasksPerSubtopology(mkTasks(fooSubtopologyId, 3)),
+            "process"
         ));
     }
 
     @Test
-    public void testDeletingMemberRemovesPartitionEpoch() {
+    public void testDeletingMemberRemovesProcessId() {
         String fooSubtopology = "foo-sub";
         String barSubtopology = "bar-sub";
         String zarSubtopology = "zar-sub";
@@ -318,40 +339,42 @@ public class StreamsGroupTest {
         StreamsGroupMember member;
 
         member = new StreamsGroupMember.Builder("member")
-            .setMemberEpoch(10)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(fooSubtopology, 1, 2, 3)))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(barSubtopology, 4, 5, 6)))
+            .setProcessId("process")
+            .setAssignedActiveTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 1)))
+            .setAssignedStandbyTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 2)))
+            .setAssignedWarmupTasks(mkTasksPerSubtopology(mkTasks(fooSubtopology, 3)))
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 4)))
+            .setStandbyTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 5)))
+            .setWarmupTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(barSubtopology, 6)))
             .build();
 
         streamsGroup.updateMember(member);
 
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 1));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 2));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 3));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 4));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 5));
-        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 6));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 7));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 8));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 9));
+        assertEquals("process", streamsGroup.currentActiveTaskProcessId(fooSubtopology, 1));
+        assertEquals(Collections.singleton("process"), streamsGroup.currentStandbyTaskProcessIds(fooSubtopology, 2));
+        assertEquals(Collections.singleton("process"), streamsGroup.currentWarmupTaskProcessIds(fooSubtopology, 3));
+        assertEquals("process", streamsGroup.currentActiveTaskProcessId(barSubtopology, 4));
+        assertEquals(Collections.singleton("process"), streamsGroup.currentStandbyTaskProcessIds(barSubtopology, 5));
+        assertEquals(Collections.singleton("process"), streamsGroup.currentWarmupTaskProcessIds(barSubtopology, 6));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 7));
+        assertEquals(Collections.emptySet(), streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 8));
+        assertEquals(Collections.emptySet(), streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 9));
 
         streamsGroup.removeMember(member.memberId());
 
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 1));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 2));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 3));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 4));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 5));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 6));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 7));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 8));
-        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 9));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 1));
+        assertEquals(Collections.emptySet(), streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 2));
+        assertEquals(Collections.emptySet(), streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 3));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 3));
+        assertEquals(Collections.emptySet(), streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 4));
+        assertEquals(Collections.emptySet(), streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 5));
+        assertNull(streamsGroup.currentActiveTaskProcessId(zarSubtopology, 7));
+        assertEquals(Collections.emptySet(), streamsGroup.currentStandbyTaskProcessIds(zarSubtopology, 8));
+        assertEquals(Collections.emptySet(), streamsGroup.currentWarmupTaskProcessIds(zarSubtopology, 9));
     }
 
     @Test
-    public void testWaitingOnUnreleasedTask() {
+    public void testWaitingOnUnreleasedActiveTask() {
         String fooSubtopology = "foo-sub";
         String barSubtopology = "bar-sub";
         String zarSubtopology = "zar-sub";
@@ -361,9 +384,9 @@ public class StreamsGroupTest {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
         streamsGroup.updateTargetAssignment(memberId1,
             new Assignment(
-                mkAssignment(
-                    mkTaskAssignment(fooSubtopology, 1, 2, 3),
-                    mkTaskAssignment(zarSubtopology, 7, 8, 9)
+                mkTasksPerSubtopology(
+                    mkTasks(fooSubtopology, 1, 2, 3),
+                    mkTasks(zarSubtopology, 7, 8, 9)
                 ),
                 emptyMap(),
                 emptyMap())
@@ -371,12 +394,13 @@ public class StreamsGroupTest {
 
         StreamsGroupMember member1 = new StreamsGroupMember.Builder(memberId1)
             .setMemberEpoch(10)
+            .setProcessId("process")
             .setState(MemberState.UNRELEASED_TASKS)
-            .setAssignedActiveTasks(mkAssignment(
-                mkTaskAssignment(fooSubtopology, 1, 2, 3)
+            .setAssignedActiveTasks(mkTasksPerSubtopology(
+                mkTasks(fooSubtopology, 1, 2, 3)
             ))
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(barSubtopology, 4, 5, 6)
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(
+                mkTasks(barSubtopology, 4, 5, 6)
             ))
             .build();
         streamsGroup.updateMember(member1);
@@ -385,8 +409,8 @@ public class StreamsGroupTest {
 
         StreamsGroupMember member2 = new StreamsGroupMember.Builder(memberId2)
             .setMemberEpoch(10)
-            .setActiveTasksPendingRevocation(mkAssignment(
-                mkTaskAssignment(zarSubtopology, 7)))
+            .setProcessId("process")
+            .setActiveTasksPendingRevocation(mkTasksPerSubtopology(mkTasks(zarSubtopology, 7)))
             .build();
         streamsGroup.updateMember(member2);
 
@@ -482,7 +506,7 @@ public class StreamsGroupTest {
 
         // Initial assignment for member1
         Assignment initialAssignment = new Assignment(
-            mkAssignment(mkTaskAssignment(subtopologyId, 0)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId, 0)),
             emptyMap(),
             emptyMap()
         );
@@ -498,7 +522,7 @@ public class StreamsGroupTest {
 
         // New assignment for member1
         Assignment newAssignment = new Assignment(
-            mkAssignment(mkTaskAssignment(subtopologyId, 1)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId, 1)),
             emptyMap(),
             emptyMap()
         );
@@ -514,7 +538,7 @@ public class StreamsGroupTest {
 
         // New assignment for member2 to add partition 1
         Assignment newAssignment2 = new Assignment(
-            mkAssignment(mkTaskAssignment(subtopologyId, 1)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId, 1)),
             emptyMap(),
             emptyMap()
         );
@@ -530,7 +554,7 @@ public class StreamsGroupTest {
 
         // New assignment for member1 to revoke partition 1 and assign partition 0
         Assignment newAssignment1 = new Assignment(
-            mkAssignment(mkTaskAssignment(subtopologyId, 0)),
+            mkTasksPerSubtopology(mkTasks(subtopologyId, 0)),
             emptyMap(),
             emptyMap()
         );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index 230e63b9058..dfc263c8710 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -44,7 +44,8 @@ import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecor
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
-import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasks;
+import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTasksPerSubtopology;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
@@ -63,7 +64,7 @@ public class TargetAssignmentBuilderTest {
         private final Map<String, StreamsGroupMember> members = new HashMap<>();
         private final Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = new HashMap<>();
         private final Map<String, StreamsGroupMember> updatedMembers = new HashMap<>();
-        private final Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment = new HashMap<>();
+        private final Map<String, Assignment> targetAssignment = new HashMap<>();
         private final Map<String, MemberAssignment> memberAssignments = new HashMap<>();
         private final Map<String, String> staticMembers = new HashMap<>();
         private MetadataImageBuilder topicsImageBuilder = new MetadataImageBuilder();
@@ -98,7 +99,7 @@ public class TargetAssignmentBuilderTest {
                 staticMembers.put(instanceId, memberId);
             }
             members.put(memberId, memberBuilder.build());
-            targetAssignment.put(memberId, new org.apache.kafka.coordinator.group.streams.Assignment(targetTasks));
+            targetAssignment.put(memberId, mkAssignment(targetTasks));
         }
 
         public String addSubtopologyWithSingleSourceTopic(
@@ -175,7 +176,7 @@ public class TargetAssignmentBuilderTest {
             members.forEach((memberId, member) ->
                 memberSpecs.put(memberId, createAssignmentMemberSpec(
                         member,
-                        targetAssignment.getOrDefault(memberId, org.apache.kafka.coordinator.group.streams.Assignment.EMPTY)
+                        targetAssignment.getOrDefault(memberId, Assignment.EMPTY)
                     )
                 ));
 
@@ -185,15 +186,15 @@ public class TargetAssignmentBuilderTest {
                 if (updatedMemberOrNull == null) {
                     memberSpecs.remove(memberId);
                 } else {
-                    org.apache.kafka.coordinator.group.streams.Assignment assignment = targetAssignment.getOrDefault(memberId,
-                        org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+                    Assignment assignment = targetAssignment.getOrDefault(memberId,
+                        Assignment.EMPTY);
 
                     // A new static member joins and needs to replace an existing departed one.
                     if (updatedMemberOrNull.instanceId() != null) {
                         String previousMemberId = staticMembers.get(updatedMemberOrNull.instanceId());
                         if (previousMemberId != null && !previousMemberId.equals(memberId)) {
                             assignment = targetAssignment.getOrDefault(previousMemberId,
-                                org.apache.kafka.coordinator.group.streams.Assignment.EMPTY);
+                                Assignment.EMPTY);
                         }
                     }
 
@@ -268,10 +269,10 @@ public class TargetAssignmentBuilderTest {
             .setClientTags(clientTags)
             .build();
 
-        org.apache.kafka.coordinator.group.streams.Assignment assignment = new org.apache.kafka.coordinator.group.streams.Assignment(
-            mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        Assignment assignment = mkAssignment(
+            mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 1, 2, 3),
+                mkTasks(barSubtopologyId, 1, 2, 3)
             ));
 
         AssignmentMemberSpec assignmentMemberSpec = createAssignmentMemberSpec(
@@ -316,24 +317,24 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -343,14 +344,14 @@ public class TargetAssignmentBuilderTest {
             20
         )), result.records());
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -366,24 +367,24 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -391,13 +392,13 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-                mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 4, 5, 6),
+                mkTasks(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 1, 2, 3),
+                mkTasks(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
@@ -406,14 +407,14 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(2));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         )));
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -429,31 +430,31 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
         context.updateMemberSubscription("member-3");
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.prepareMemberAssignment("member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.prepareMemberAssignment("member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -461,17 +462,17 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1, 2),
-                mkTaskAssignment(barSubtopologyId, 1, 2)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 1, 2),
+                mkTasks(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 3, 4),
-                mkTaskAssignment(barSubtopologyId, 3, 4)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 3, 4),
+                mkTasks(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 5, 6),
-                mkTaskAssignment(barSubtopologyId, 5, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 5, 6),
+                mkTasks(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
@@ -480,18 +481,18 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(3));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         )));
-        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        expectedAssignment.put("member-3", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -507,18 +508,18 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.addGroupMember("member-3", mkAssignment(
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.addGroupMember("member-3", mkTasksPerSubtopology(
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         context.updateMemberSubscription(
@@ -527,19 +528,19 @@ public class TargetAssignmentBuilderTest {
             Optional.of("rack-0")
         );
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.prepareMemberAssignment("member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.prepareMemberAssignment("member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -547,17 +548,17 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1, 2),
-                mkTaskAssignment(barSubtopologyId, 1, 2)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 1, 2),
+                mkTasks(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 3, 4),
-                mkTaskAssignment(barSubtopologyId, 3, 4)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 3, 4),
+                mkTasks(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 5, 6),
-                mkTaskAssignment(barSubtopologyId, 5, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 5, 6),
+                mkTasks(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
@@ -566,18 +567,18 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(3));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         )));
-        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        expectedAssignment.put("member-3", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -593,34 +594,34 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, mkMapOfPartitionRacks(6));
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, mkMapOfPartitionRacks(6));
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.addGroupMember("member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.addGroupMember("member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
-            mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4, 5),
+            mkTasks(barSubtopologyId, 3, 4, 5)
         ));
 
-        context.prepareMemberAssignment("member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 6),
-            mkTaskAssignment(barSubtopologyId, 6)
+        context.prepareMemberAssignment("member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 6),
+            mkTasks(barSubtopologyId, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -629,13 +630,13 @@ public class TargetAssignmentBuilderTest {
 
         // Member 1 has no record because its assignment did not change.
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
-                mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 3, 4, 5),
+                mkTasks(barSubtopologyId, 3, 4, 5)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 6),
-                mkTaskAssignment(barSubtopologyId, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 6),
+                mkTasks(barSubtopologyId, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
@@ -644,18 +645,18 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(2));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
-            mkTaskAssignment(barSubtopologyId, 3, 4, 5)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4, 5),
+            mkTasks(barSubtopologyId, 3, 4, 5)
         )));
-        expectedAssignment.put("member-3", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 6),
-            mkTaskAssignment(barSubtopologyId, 6)
+        expectedAssignment.put("member-3", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 6),
+            mkTasks(barSubtopologyId, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -671,31 +672,31 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.addGroupMember("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.addGroupMember("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.addGroupMember("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.addGroupMember("member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.addGroupMember("member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         context.removeMemberSubscription("member-3");
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         ));
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -703,13 +704,13 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-                mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 1, 2, 3),
+                mkTasks(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-                mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 4, 5, 6),
+                mkTasks(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
@@ -718,14 +719,14 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(2));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
-            mkTaskAssignment(barSubtopologyId, 1, 2, 3)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2, 3),
+            mkTasks(barSubtopologyId, 1, 2, 3)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 4, 5, 6)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 4, 5, 6),
+            mkTasks(barSubtopologyId, 4, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
@@ -741,19 +742,19 @@ public class TargetAssignmentBuilderTest {
         String fooSubtopologyId = context.addSubtopologyWithSingleSourceTopic("foo", 6, Collections.emptyMap());
         String barSubtopologyId = context.addSubtopologyWithSingleSourceTopic("bar", 6, Collections.emptyMap());
 
-        context.addGroupMember("member-1", "instance-member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.addGroupMember("member-1", "instance-member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.addGroupMember("member-2", "instance-member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.addGroupMember("member-2", "instance-member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.addGroupMember("member-3", "instance-member-3", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.addGroupMember("member-3", "instance-member-3", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         // Static member 3 leaves
@@ -763,19 +764,19 @@ public class TargetAssignmentBuilderTest {
         context.updateMemberSubscription("member-3-a", Optional.of("instance-member-3"),
             Optional.empty());
 
-        context.prepareMemberAssignment("member-1", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        context.prepareMemberAssignment("member-1", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         ));
 
-        context.prepareMemberAssignment("member-2", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        context.prepareMemberAssignment("member-2", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         ));
 
-        context.prepareMemberAssignment("member-3-a", mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        context.prepareMemberAssignment("member-3-a", mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         ));
 
         TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
@@ -783,9 +784,9 @@ public class TargetAssignmentBuilderTest {
         assertEquals(2, result.records().size());
 
         assertUnorderedListEquals(Collections.singletonList(
-            newStreamsGroupTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
-                mkTaskAssignment(fooSubtopologyId, 5, 6),
-                mkTaskAssignment(barSubtopologyId, 5, 6)
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3-a", mkTasksPerSubtopology(
+                mkTasks(fooSubtopologyId, 5, 6),
+                mkTasks(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 1));
 
@@ -794,19 +795,19 @@ public class TargetAssignmentBuilderTest {
             20
         ), result.records().get(1));
 
-        Map<String, org.apache.kafka.coordinator.group.streams.Assignment> expectedAssignment = new HashMap<>();
-        expectedAssignment.put("member-1", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 1, 2),
-            mkTaskAssignment(barSubtopologyId, 1, 2)
+        Map<String, Assignment> expectedAssignment = new HashMap<>();
+        expectedAssignment.put("member-1", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 1, 2),
+            mkTasks(barSubtopologyId, 1, 2)
         )));
-        expectedAssignment.put("member-2", new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 3, 4),
-            mkTaskAssignment(barSubtopologyId, 3, 4)
+        expectedAssignment.put("member-2", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 3, 4),
+            mkTasks(barSubtopologyId, 3, 4)
         )));
 
-        expectedAssignment.put("member-3-a", new Assignment(mkAssignment(
-            mkTaskAssignment(fooSubtopologyId, 5, 6),
-            mkTaskAssignment(barSubtopologyId, 5, 6)
+        expectedAssignment.put("member-3-a", mkAssignment(mkTasksPerSubtopology(
+            mkTasks(fooSubtopologyId, 5, 6),
+            mkTasks(barSubtopologyId, 5, 6)
         )));
 
         assertEquals(expectedAssignment, result.targetAssignment());
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
index d53398238f7..24a0b42eec8 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
@@ -17,61 +17,68 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
-import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
 
 import java.util.AbstractMap;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.LinkedHashMap;
+import java.util.Objects;
 import java.util.Map;
 import java.util.Set;
-import java.util.TreeSet;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
 
 public class TaskAssignmentTestUtil {
 
-    public static Map.Entry<String, Set<Integer>> mkTaskAssignment(
-        String subtopologyId,
-        Integer... tasks
-    ) {
-        return new AbstractMap.SimpleEntry<>(
-            subtopologyId,
-            new HashSet<>(Arrays.asList(tasks))
+    public enum TaskRole {
+        ACTIVE,
+        STANDBY,
+        WARMUP
+    }
+    public static Assignment mkAssignment(final Map<String, Set<Integer>> activeTasks,
+                                          final Map<String, Set<Integer>> standbyTasks,
+                                          final Map<String, Set<Integer>> warmupTasks) {
+        return new Assignment(
+            Collections.unmodifiableMap(Objects.requireNonNull(activeTasks)),
+            Collections.unmodifiableMap(Objects.requireNonNull(standbyTasks)),
+            Collections.unmodifiableMap(Objects.requireNonNull(warmupTasks))
         );
     }
 
-    public static Map.Entry<String, Set<Integer>> mkSortedTaskAssignment(
-        String subtopologyId,
-        Integer... tasks
-    ) {
-        return new AbstractMap.SimpleEntry<>(
-            subtopologyId,
-            new TreeSet<>(Arrays.asList(tasks))
+    // TODO: Tests using this util probably should be extended to cover standby tasks
+    public static Assignment mkAssignment(final Map<String, Set<Integer>> activeTasks) {
+        return new Assignment(
+            Collections.unmodifiableMap(Objects.requireNonNull(activeTasks)),
+            Collections.emptyMap(),
+            Collections.emptyMap()
         );
     }
 
     @SafeVarargs
-    public static Map<String, Set<Integer>> mkAssignment(Map.Entry<String, Set<Integer>>... entries) {
-        Map<String, Set<Integer>> assignment = new HashMap<>();
-        for (Map.Entry<String, Set<Integer>> entry : entries) {
-            assignment.put(entry.getKey(), entry.getValue());
+    public static Assignment mkAssignment(TaskRole taskRole, Map.Entry<String, Set<Integer>>... entries) {
+        switch (taskRole) {
+            case ACTIVE:
+                return new Assignment(mkTasksPerSubtopology(entries), new HashMap<>(), new HashMap<>());
+            case STANDBY:
+                return new Assignment(new HashMap<>(), mkTasksPerSubtopology(entries), new HashMap<>());
+            case WARMUP:
+                return new Assignment(new HashMap<>(), new HashMap<>(), mkTasksPerSubtopology(entries));
+            default:
+                throw new IllegalArgumentException("Unknown task role: " + taskRole);
         }
-        return assignment;
     }
 
-    @SafeVarargs
-    public static Map<String, Set<Integer>> mkSortedAssignment(Map.Entry<String, Set<Integer>>... entries) {
-        Map<String, Set<Integer>> assignment = new LinkedHashMap<>();
-        for (Map.Entry<String, Set<Integer>> entry : entries) {
-            assignment.put(entry.getKey(), entry.getValue());
-        }
-        return assignment;
+    public static Map.Entry<String, Set<Integer>> mkTasks(
+        String subtopologyId,
+        Integer... tasks
+    ) {
+        return new AbstractMap.SimpleEntry<>(
+            subtopologyId,
+            new HashSet<>(Arrays.asList(tasks))
+        );
     }
 
     @SafeVarargs
-    public static Map<String, Set<Integer>> mkStreamsAssignment(Map.Entry<String, Set<Integer>>... entries) {
+    public static Map<String, Set<Integer>> mkTasksPerSubtopology(Map.Entry<String, Set<Integer>>... entries) {
         Map<String, Set<Integer>> assignment = new HashMap<>();
         for (Map.Entry<String, Set<Integer>> entry : entries) {
             assignment.put(entry.getKey(), entry.getValue());
@@ -79,20 +86,6 @@ public class TaskAssignmentTestUtil {
         return assignment;
     }
 
-    /**
-     * Verifies that the expected assignment is equal to the computed assignment for every member in the group.
-     */
-    public static void assertAssignment(
-        Map<String, Map<String, Set<Integer>>> expectedAssignment,
-        GroupAssignment computedGroupAssignment
-    ) {
-        assertEquals(expectedAssignment.size(), computedGroupAssignment.members().size());
-        computedGroupAssignment.members().forEach((memberId, memberAssignment) -> {
-            Map<String, Set<Integer>> computedAssignmentForMember = memberAssignment.activeTasks();
-            assertEquals(expectedAssignment.get(memberId), computedAssignmentForMember);
-        });
-    }
-
     /**
      * Generate a reverse look up map of partition to member target assignments from the given member spec.
      *


(kafka) 24/42: Rename streamsHeartbeatX and streamsInitializeX to streamsGroupX

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 93b72dba05cc682f849fb00110f15c1413fee563
Author: Bruno Cadonna <ca...@apache.org>
AuthorDate: Fri Aug 30 11:14:10 2024 +0200

    Rename streamsHeartbeatX and streamsInitializeX to streamsGroupX
---
 .../consumer/internals/RequestManagers.java        | 28 +++++------
 .../StreamsGroupHeartbeatRequestManager.java       | 38 +++++++--------
 ...a => StreamsGroupInitializeRequestManager.java} | 14 +++---
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  6 +--
 .../StreamsGroupInitializeRequestManagerTest.java  | 16 +++----
 .../group/GroupCoordinatorAdapter.scala            |  4 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   | 38 +++++++--------
 .../group/GroupCoordinatorAdapterTest.scala        |  8 ++--
 .../scala/unit/kafka/server/KafkaApisTest.scala    |  8 ++--
 .../kafka/coordinator/group/GroupCoordinator.java  |  8 ++--
 .../coordinator/group/GroupCoordinatorService.java | 12 ++---
 .../coordinator/group/GroupCoordinatorShard.java   | 21 ++++-----
 .../coordinator/group/GroupMetadataManager.java    | 54 +++++++++++-----------
 .../group/streams/CurrentAssignmentBuilder.java    | 14 +++---
 .../group/GroupCoordinatorServiceTest.java         | 32 ++++++-------
 .../group/GroupCoordinatorShardTest.java           | 12 ++---
 .../group/GroupMetadataManagerTest.java            | 38 +++++++--------
 .../group/GroupMetadataManagerTestContext.java     |  8 ++--
 18 files changed, 179 insertions(+), 180 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 7cf4a3e67f6..4f3ec1b2398 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -58,8 +58,8 @@ public class RequestManagers implements Closeable {
     public final TopicMetadataRequestManager topicMetadataRequestManager;
     public final FetchRequestManager fetchRequestManager;
     public final Optional<ShareConsumeRequestManager> shareConsumeRequestManager;
-    public final Optional<StreamsGroupHeartbeatRequestManager> streamsHeartbeatRequestManager;
-    public final Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager;
+    public final Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager;
+    public final Optional<StreamsGroupInitializeRequestManager> streamsGroupInitializeRequestManager;
     private final List<Optional<? extends RequestManager>> entries;
     private final IdempotentCloser closer = new IdempotentCloser();
 
@@ -71,8 +71,8 @@ public class RequestManagers implements Closeable {
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
                            Optional<ConsumerMembershipManager> membershipManager,
-                           Optional<StreamsGroupHeartbeatRequestManager> streamsHeartbeatRequestManager,
-                           Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager) {
+                           Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager,
+                           Optional<StreamsGroupInitializeRequestManager> streamsGroupInitializeRequestManager) {
         this.log = logContext.logger(RequestManagers.class);
         this.offsetsRequestManager = requireNonNull(offsetsRequestManager, "OffsetsRequestManager cannot be null");
         this.coordinatorRequestManager = coordinatorRequestManager;
@@ -84,8 +84,8 @@ public class RequestManagers implements Closeable {
         this.shareHeartbeatRequestManager = Optional.empty();
         this.consumerMembershipManager = membershipManager;
         this.shareMembershipManager = Optional.empty();
-        this.streamsHeartbeatRequestManager = streamsHeartbeatRequestManager;
-        this.streamsInitializeRequestManager = streamsInitializeRequestManager;
+        this.streamsGroupHeartbeatRequestManager = streamsGroupHeartbeatRequestManager;
+        this.streamsGroupInitializeRequestManager = streamsGroupInitializeRequestManager;
 
         List<Optional<? extends RequestManager>> list = new ArrayList<>();
         list.add(coordinatorRequestManager);
@@ -95,8 +95,8 @@ public class RequestManagers implements Closeable {
         list.add(Optional.of(offsetsRequestManager));
         list.add(Optional.of(topicMetadataRequestManager));
         list.add(Optional.of(fetchRequestManager));
-        list.add(streamsHeartbeatRequestManager);
-        list.add(streamsInitializeRequestManager);
+        list.add(streamsGroupHeartbeatRequestManager);
+        list.add(streamsGroupInitializeRequestManager);
         entries = Collections.unmodifiableList(list);
     }
 
@@ -113,8 +113,8 @@ public class RequestManagers implements Closeable {
         this.shareHeartbeatRequestManager = shareHeartbeatRequestManager;
         this.consumerMembershipManager = Optional.empty();
         this.shareMembershipManager = shareMembershipManager;
-        this.streamsHeartbeatRequestManager = Optional.empty();
-        this.streamsInitializeRequestManager = Optional.empty();
+        this.streamsGroupHeartbeatRequestManager = Optional.empty();
+        this.streamsGroupInitializeRequestManager = Optional.empty();
         this.offsetsRequestManager = null;
         this.topicMetadataRequestManager = null;
         this.fetchRequestManager = null;
@@ -199,7 +199,7 @@ public class RequestManagers implements Closeable {
                 CoordinatorRequestManager coordinator = null;
                 CommitRequestManager commitRequestManager = null;
                 StreamsGroupHeartbeatRequestManager streamsGroupHeartbeatRequestManager = null;
-                StreamsInitializeRequestManager streamsInitializeRequestManager = null;
+                StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = null;
 
                 if (groupRebalanceConfig != null && groupRebalanceConfig.groupId != null) {
                     Optional<String> serverAssignor = Optional.ofNullable(config.getString(ConsumerConfig.GROUP_REMOTE_ASSIGNOR_CONFIG));
@@ -245,7 +245,7 @@ public class RequestManagers implements Closeable {
                     membershipManager.registerStateListener(applicationThreadMemberStateListener);
 
                     if (streamsInstanceMetadata.isPresent()) {
-                        streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+                        streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
                             logContext,
                             groupRebalanceConfig.groupId,
                             streamsInstanceMetadata.get(),
@@ -255,7 +255,7 @@ public class RequestManagers implements Closeable {
                             time,
                             config,
                             coordinator,
-                            streamsInitializeRequestManager,
+                            streamsGroupInitializeRequestManager,
                             membershipManager,
                             backgroundEventHandler,
                             metrics,
@@ -297,7 +297,7 @@ public class RequestManagers implements Closeable {
                         Optional.ofNullable(heartbeatRequestManager),
                         Optional.ofNullable(membershipManager),
                         Optional.ofNullable(streamsGroupHeartbeatRequestManager),
-                        Optional.ofNullable(streamsInitializeRequestManager)
+                        Optional.ofNullable(streamsGroupInitializeRequestManager)
                 );
             }
         };
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 2b3b7c8f248..ba0a289f187 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -63,7 +63,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final ConsumerMembershipManager membershipManager;
 
-    private final StreamsInitializeRequestManager streamsInitializeRequestManager;
+    private final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager;
 
     private final BackgroundEventHandler backgroundEventHandler;
 
@@ -82,7 +82,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         final Time time,
         final ConsumerConfig config,
         final CoordinatorRequestManager coordinatorRequestManager,
-        final StreamsInitializeRequestManager streamsInitializeRequestManager,
+        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager,
         final ConsumerMembershipManager membershipManager,
         final BackgroundEventHandler backgroundEventHandler,
         final Metrics metrics,
@@ -92,7 +92,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         this.coordinatorRequestManager = coordinatorRequestManager;
         this.logger = logContext.logger(getClass());
         this.membershipManager = membershipManager;
-        this.streamsInitializeRequestManager = streamsInitializeRequestManager;
+        this.streamsGroupInitializeRequestManager = streamsGroupInitializeRequestManager;
         this.backgroundEventHandler = backgroundEventHandler;
         int maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
         long retryBackoffMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG);
@@ -189,12 +189,12 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 Errors error =
                     Errors.forCode(((StreamsGroupHeartbeatResponse) response.responseBody()).data().errorCode());
                 if (error == Errors.NONE) {
-                    logger.debug("StreamsHeartbeat responded successfully: {}", response);
+                    logger.debug("StreamsGroupHeartbeat responded successfully: {}", response);
                 } else {
-                    logger.error("StreamsHeartbeat failed because of {}: {}", error, response);
+                    logger.error("StreamsGroupHeartbeat failed because of {}: {}", error, response);
                 }
             } else {
-                logger.error("StreamsHeartbeat failed because of unexpected exception.", exception);
+                logger.error("StreamsGroupHeartbeat failed because of unexpected exception.", exception);
             }
         });
     }
@@ -203,13 +203,13 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         this.heartbeatRequestState.onFailedAttempt(responseTimeMs);
         this.heartbeatState.reset();
         if (exception instanceof RetriableException) {
-            String message = String.format("StreamsHeartbeatRequest failed because of the retriable exception. " +
+            String message = String.format("StreamsGroupHeartbeatRequest failed because of the retriable exception. " +
                     "Will retry in %s ms: %s",
                 heartbeatRequestState.remainingBackoffMs(responseTimeMs),
                 exception.getMessage());
             logger.debug(message);
         } else {
-            logger.error("StreamsHeartbeatRequest failed due to fatal error", exception);
+            logger.error("StreamsGroupHeartbeatRequest failed due to fatal error", exception);
             handleFatalFailure(exception);
         }
     }
@@ -230,7 +230,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         heartbeatRequestState.resetTimer();
 
         if (data.shouldInitializeTopology()) {
-            streamsInitializeRequestManager.initialize();
+            streamsGroupInitializeRequestManager.initialize();
         }
         if (data.partitionsByUserEndpoint() != null) {
             streamsInterface.partitionsByHost.set(convertHostInfoMap(data));
@@ -340,7 +340,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         switch (error) {
             case NOT_COORDINATOR:
                 // the manager should retry immediately when the coordinator node becomes available again
-                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is incorrect. " +
+                message = String.format("StreamsGroupHeartbeatRequest failed because the group coordinator %s is incorrect. " +
                         "Will attempt to find the coordinator again and retry",
                     coordinatorRequestManager.coordinator());
                 logInfo(message, response, currentTimeMs);
@@ -350,7 +350,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 break;
 
             case COORDINATOR_NOT_AVAILABLE:
-                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is not available. " +
+                message = String.format("StreamsGroupHeartbeatRequest failed because the group coordinator %s is not available. " +
                         "Will attempt to find the coordinator again and retry",
                     coordinatorRequestManager.coordinator());
                 logInfo(message, response, currentTimeMs);
@@ -361,7 +361,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
             case COORDINATOR_LOAD_IN_PROGRESS:
                 // the manager will backoff and retry
-                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is still loading." +
+                message = String.format("StreamsGroupHeartbeatRequest failed because the group coordinator %s is still loading." +
                         "Will retry",
                     coordinatorRequestManager.coordinator());
                 logInfo(message, response, currentTimeMs);
@@ -370,12 +370,12 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             case GROUP_AUTHORIZATION_FAILED:
                 GroupAuthorizationException exception =
                     GroupAuthorizationException.forGroupId(membershipManager.groupId());
-                logger.error("StreamsHeartbeatRequest failed due to group authorization failure: {}", exception.getMessage());
+                logger.error("StreamsGroupHeartbeatRequest failed due to group authorization failure: {}", exception.getMessage());
                 handleFatalFailure(error.exception(exception.getMessage()));
                 break;
 
             case UNRELEASED_INSTANCE_ID:
-                logger.error("StreamsHeartbeatRequest failed due to the instance id {} was not released: {}",
+                logger.error("StreamsGroupHeartbeatRequest failed due to the instance id {} was not released: {}",
                     membershipManager.groupInstanceId().orElse("null"), errorMessage);
                 handleFatalFailure(Errors.UNRELEASED_INSTANCE_ID.exception(errorMessage));
                 break;
@@ -384,12 +384,12 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             case GROUP_MAX_SIZE_REACHED:
             case UNSUPPORTED_ASSIGNOR:
             case UNSUPPORTED_VERSION:
-                logger.error("StreamsHeartbeatRequest failed due to error: {}", error);
+                logger.error("StreamsGroupHeartbeatRequest failed due to error: {}", error);
                 handleFatalFailure(error.exception(errorMessage));
                 break;
 
             case FENCED_MEMBER_EPOCH:
-                message = String.format("StreamsHeartbeatRequest failed for member %s because epoch %s is fenced.",
+                message = String.format("StreamsGroupHeartbeatRequest failed for member %s because epoch %s is fenced.",
                     membershipManager.memberId(), membershipManager.memberEpoch());
                 logInfo(message, response, currentTimeMs);
                 membershipManager.transitionToFenced();
@@ -398,7 +398,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 break;
 
             case UNKNOWN_MEMBER_ID:
-                message = String.format("StreamsHeartbeatRequest failed because member %s is unknown.",
+                message = String.format("StreamsGroupHeartbeatRequest failed because member %s is unknown.",
                     membershipManager.memberId());
                 logInfo(message, response, currentTimeMs);
                 membershipManager.transitionToFenced();
@@ -408,7 +408,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
             default:
                 // If the manager receives an unknown error - there could be a bug in the code or a new error code
-                logger.error("StreamsHeartbeatRequest failed due to unexpected error: {}", error);
+                logger.error("StreamsGroupHeartbeatRequest failed due to unexpected error: {}", error);
                 handleFatalFailure(error.exception(errorMessage));
                 break;
         }
@@ -604,7 +604,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 .collect(Collectors.toList());
         }
 
-        // Fields of StreamsHeartbeatRequest sent in the most recent request
+        // Fields of StreamsGroupHeartbeatRequest sent in the most recent request
         static class SentFields {
 
             private int rebalanceTimeoutMs = -1;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
similarity index 92%
rename from clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
rename to clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
index c0d2d9f9124..e7f763bd969 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
@@ -30,7 +30,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 
-public class StreamsInitializeRequestManager implements RequestManager {
+public class StreamsGroupInitializeRequestManager implements RequestManager {
 
     private final Logger logger;
     private final String groupId;
@@ -40,10 +40,10 @@ public class StreamsInitializeRequestManager implements RequestManager {
     private Optional<NetworkClientDelegate.UnsentRequest> unsentRequest = Optional.empty();
 
 
-    StreamsInitializeRequestManager(final LogContext logContext,
-                                    final String groupId,
-                                    final StreamsAssignmentInterface streamsAssignmentInterface,
-                                    final CoordinatorRequestManager coordinatorRequestManager) {
+    StreamsGroupInitializeRequestManager(final LogContext logContext,
+                                         final String groupId,
+                                         final StreamsAssignmentInterface streamsAssignmentInterface,
+                                         final CoordinatorRequestManager coordinatorRequestManager) {
         this.logger = logContext.logger(getClass());
         this.groupId = groupId;
         this.streamsAssignmentInterface = streamsAssignmentInterface;
@@ -70,11 +70,11 @@ public class StreamsInitializeRequestManager implements RequestManager {
         streamsGroupInitializeRequestData.setGroupId(groupId);
         final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
         streamsGroupInitializeRequestData.setTopology(topology);
-        final StreamsGroupInitializeRequest.Builder streamsInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
+        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
             streamsGroupInitializeRequestData
         );
         return new NetworkClientDelegate.UnsentRequest(
-            streamsInitializeRequestBuilder,
+            streamsGroupInitializeRequestBuilder,
             coordinatorRequestManager.coordinator()
         );
     }
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index aed1b4dafd7..b9fdb4c7722 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -86,7 +86,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
     private CoordinatorRequestManager coordinatorRequestManager;
 
     @Mock
-    private StreamsInitializeRequestManager streamsInitializeRequestManager;
+    private StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager;
 
     @Mock
     private ConsumerMembershipManager membershipManager;
@@ -141,7 +141,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
             time,
             config,
             coordinatorRequestManager,
-            streamsInitializeRequestManager,
+            streamsGroupInitializeRequestManager,
             membershipManager,
             backgroundEventHandler,
             metrics,
@@ -333,7 +333,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
 
         mockResponse(data);
 
-        verify(streamsInitializeRequestManager).initialize();
+        verify(streamsGroupInitializeRequestManager).initialize();
     }
 
     private void mockResponse(final StreamsGroupHeartbeatResponseData data) {
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index dd708c8d79a..48108204474 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -51,20 +51,20 @@ class StreamsGroupInitializeRequestManagerTest {
     public void shouldPollEmptyResult() {
         final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
         final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
-        final StreamsInitializeRequestManager streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
             logContext,
             groupId,
             streamsAssignmentInterface,
             coordinatorRequestManager
         );
 
-        final NetworkClientDelegate.PollResult pollResult = streamsInitializeRequestManager.poll(0);
+        final NetworkClientDelegate.PollResult pollResult = streamsGroupInitializeRequestManager.poll(0);
 
         assertEquals(NetworkClientDelegate.PollResult.EMPTY, pollResult);
     }
 
     @Test
-    public void shouldPollStreamsInitializeRequest() {
+    public void shouldPollStreamsGroupInitializeRequest() {
         final Node node = mock(Node.class);
         final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
         when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(node));
@@ -90,23 +90,23 @@ class StreamsGroupInitializeRequestManagerTest {
         when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
             mkMap(mkEntry(subtopologyName1, subtopology1))
         );
-        final StreamsInitializeRequestManager streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
             logContext,
             groupId,
             streamsAssignmentInterface,
             coordinatorRequestManager
         );
 
-        streamsInitializeRequestManager.initialize();
-        final NetworkClientDelegate.PollResult pollResult = streamsInitializeRequestManager.poll(0);
+        streamsGroupInitializeRequestManager.initialize();
+        final NetworkClientDelegate.PollResult pollResult = streamsGroupInitializeRequestManager.poll(0);
 
         assertEquals(1, pollResult.unsentRequests.size());
         final NetworkClientDelegate.UnsentRequest unsentRequest = pollResult.unsentRequests.get(0);
         assertTrue(unsentRequest.node().isPresent());
         assertEquals(node, unsentRequest.node().get());
         assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE, unsentRequest.requestBuilder().apiKey());
-        final StreamsGroupInitializeRequest.Builder streamsInitializeRequestBuilder = (StreamsGroupInitializeRequest.Builder) unsentRequest.requestBuilder();
-        final StreamsGroupInitializeRequest streamsGroupInitializeRequest = streamsInitializeRequestBuilder.build();
+        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = (StreamsGroupInitializeRequest.Builder) unsentRequest.requestBuilder();
+        final StreamsGroupInitializeRequest streamsGroupInitializeRequest = streamsGroupInitializeRequestBuilder.build();
         final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = streamsGroupInitializeRequest.data();
         assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE.id, streamsGroupInitializeRequestData.apiKey());
         assertEquals(groupId, streamsGroupInitializeRequestData.groupId());
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index a48b2c6ffc8..ce8bde14493 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -77,7 +77,7 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
-  override def streamsInitialize(
+  override def streamsGroupInitialize(
                                    context: RequestContext,
                                    request: StreamsGroupInitializeRequestData
                                  ): CompletableFuture[StreamsGroupInitializeResponseData] = {
@@ -86,7 +86,7 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
-  override def streamsHeartbeat(
+  override def streamsGroupHeartbeat(
                                  context: RequestContext,
                                  request: StreamsGroupHeartbeatRequestData
                                ): CompletableFuture[StreamsGroupHeartbeatResponseData] = {
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index d3bfd420ace..5e2abe450c2 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -277,8 +277,8 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
         case ApiKeys.STREAMS_GROUP_DESCRIBE => handleStreamsGroupDescribe(request).exceptionally(handleError)
-        case ApiKeys.STREAMS_GROUP_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
-        case ApiKeys.STREAMS_GROUP_HEARTBEAT => handleStreamsHeartbeat(request).exceptionally(handleError)
+        case ApiKeys.STREAMS_GROUP_INITIALIZE => handleStreamsGroupInitialize(request).exceptionally(handleError)
+        case ApiKeys.STREAMS_GROUP_HEARTBEAT => handleStreamsGroupHeartbeat(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
       }
     } catch {
@@ -3889,27 +3889,27 @@ class KafkaApis(val requestChannel: RequestChannel,
   private def isStreamsGroupProtocolEnabled(): Boolean = {
     config.groupCoordinatorRebalanceProtocols.contains(Group.GroupType.STREAMS)
   }
-  
-  def handleStreamsInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    val streamsInitializeRequest = request.body[StreamsGroupInitializeRequest]
+
+  def handleStreamsGroupInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsGroupInitializeRequest = request.body[StreamsGroupInitializeRequest]
 
     // TODO: Check ACLs on CREATE TOPIC & DESCRIBE_CONFIGS
 
     if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
-      requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
       CompletableFuture.completedFuture[Unit](())
-    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsInitializeRequest.data.groupId)) {
-      requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
+    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsGroupInitializeRequest.data.groupId)) {
+      requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
       CompletableFuture.completedFuture[Unit](())
     } else {
-      groupCoordinator.streamsInitialize(
+      groupCoordinator.streamsGroupInitialize(
         request.context,
-        streamsInitializeRequest.data,
+        streamsGroupInitializeRequest.data,
       ).handle[Unit] { (response, exception) =>
         if (exception != null) {
-          requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(exception))
+          requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(exception))
         } else {
           requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(response))
         }
@@ -3917,24 +3917,24 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
   }
 
-  def handleStreamsHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    val streamsHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
+  def handleStreamsGroupHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsGroupHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
 
     if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
-      requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
       CompletableFuture.completedFuture[Unit](())
-    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsHeartbeatRequest.data.groupId)) {
-      requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
+    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsGroupHeartbeatRequest.data.groupId)) {
+      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
       CompletableFuture.completedFuture[Unit](())
     } else {
-      groupCoordinator.streamsHeartbeat(
+      groupCoordinator.streamsGroupHeartbeat(
         request.context,
-        streamsHeartbeatRequest.data,
+        streamsGroupHeartbeatRequest.data,
       ).handle[Unit] { (response, exception) =>
         if (exception != null) {
-          requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(exception))
+          requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(exception))
         } else {
           requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(response))
         }
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index d2c2a2ac487..68959acc23a 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -79,7 +79,7 @@ class GroupCoordinatorAdapterTest {
   }
 
   @Test
-  def testStreamsInitialize(): Unit = {
+  def testStreamsGroupInitialize(): Unit = {
     val groupCoordinator = mock(classOf[GroupCoordinator])
     val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
 
@@ -87,7 +87,7 @@ class GroupCoordinatorAdapterTest {
     val request = new StreamsGroupInitializeRequestData()
       .setGroupId("group")
 
-    val future = adapter.streamsInitialize(ctx, request)
+    val future = adapter.streamsGroupInitialize(ctx, request)
 
     assertTrue(future.isDone)
     assertTrue(future.isCompletedExceptionally)
@@ -95,7 +95,7 @@ class GroupCoordinatorAdapterTest {
   }
 
   @Test
-  def testStreamsHeartbeat(): Unit = {
+  def testStreamsGroupHeartbeat(): Unit = {
     val groupCoordinator = mock(classOf[GroupCoordinator])
     val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
 
@@ -103,7 +103,7 @@ class GroupCoordinatorAdapterTest {
     val request = new StreamsGroupHeartbeatRequestData()
       .setGroupId("group")
 
-    val future = adapter.streamsHeartbeat(ctx, request)
+    val future = adapter.streamsGroupHeartbeat(ctx, request)
 
     assertTrue(future.isDone)
     assertTrue(future.isCompletedExceptionally)
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 202149fe747..1241287965f 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11243,7 +11243,7 @@ class KafkaApisTest extends Logging {
     val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
-    when(groupCoordinator.streamsInitialize(
+    when(groupCoordinator.streamsGroupInitialize(
       requestChannelRequest.context,
       streamsGroupInitializeRequest
     )).thenReturn(future)
@@ -11269,7 +11269,7 @@ class KafkaApisTest extends Logging {
     val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
-    when(groupCoordinator.streamsInitialize(
+    when(groupCoordinator.streamsGroupInitialize(
       requestChannelRequest.context,
       streamsGroupInitializeRequest
     )).thenReturn(future)
@@ -11316,7 +11316,7 @@ class KafkaApisTest extends Logging {
     val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
-    when(groupCoordinator.streamsHeartbeat(
+    when(groupCoordinator.streamsGroupHeartbeat(
       requestChannelRequest.context,
       streamsGroupHeartbeatRequest
     )).thenReturn(future)
@@ -11343,7 +11343,7 @@ class KafkaApisTest extends Logging {
     val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
-    when(groupCoordinator.streamsHeartbeat(
+    when(groupCoordinator.streamsGroupHeartbeat(
       requestChannelRequest.context,
       streamsGroupHeartbeatRequest
     )).thenReturn(future)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index cea5da08608..7c78db21761 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -91,12 +91,12 @@ public interface GroupCoordinator {
      * Initialize a Streams Group.
      *
      * @param context           The request context.
-     * @param request           The StreamsHeartbeatRequest data.
+     * @param request           The StreamsGroupInitializeRequest data.
      *
      * @return  A future yielding the response.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsGroupInitializeResponseData> streamsInitialize(
+    CompletableFuture<StreamsGroupInitializeResponseData> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     );
@@ -105,12 +105,12 @@ public interface GroupCoordinator {
      * Heartbeat to a Streams Group.
      *
      * @param context           The request context.
-     * @param request           The StreamsHeartbeatResponseData data.
+     * @param request           The StreamsGroupHeartbeatResponseData data.
      *
      * @return  A future yielding the response.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsGroupHeartbeatResponseData> streamsHeartbeat(
+    CompletableFuture<StreamsGroupHeartbeatResponseData> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 5d632528961..c6631945add 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -351,10 +351,10 @@ public class GroupCoordinatorService implements GroupCoordinator {
     }
 
     /**
-     * See {@link GroupCoordinator#streamsInitialize(RequestContext, org.apache.kafka.common.message.StreamsGroupInitializeRequestData)}.
+     * See {@link GroupCoordinator#streamsGroupInitialize(RequestContext, org.apache.kafka.common.message.StreamsGroupInitializeRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsGroupInitializeResponseData> streamsInitialize(
+    public CompletableFuture<StreamsGroupInitializeResponseData> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) {
@@ -368,7 +368,7 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-group-initialize",
             topicPartitionFor(request.groupId()),
             Duration.ofMillis(config.offsetCommitTimeoutMs()),
-            coordinator -> coordinator.streamsInitialize(context, request)
+            coordinator -> coordinator.streamsGroupInitialize(context, request)
         ).exceptionally(exception -> handleOperationException(
             "streams-group-initialize",
             request,
@@ -380,10 +380,10 @@ public class GroupCoordinatorService implements GroupCoordinator {
     }
 
     /**
-     * See {@link GroupCoordinator#streamsHeartbeat(RequestContext, org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData)}.
+     * See {@link GroupCoordinator#streamsGroupHeartbeat(RequestContext, org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsGroupHeartbeatResponseData> streamsHeartbeat(
+    public CompletableFuture<StreamsGroupHeartbeatResponseData> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) {
@@ -397,7 +397,7 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-heartbeat",
             topicPartitionFor(request.groupId()),
             Duration.ofMillis(config.offsetCommitTimeoutMs()),
-            coordinator -> coordinator.streamsHeartbeat(context, request)
+            coordinator -> coordinator.streamsGroupHeartbeat(context, request)
         ).exceptionally(exception -> handleOperationException(
             "streams-heartbeat",
             request,
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index cb2833f7029..225b56f58e1 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -107,7 +107,6 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
-import org.apache.kafka.coordinator.group.taskassignor.MockAssignor;
 import org.apache.kafka.coordinator.group.taskassignor.StickyTaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
@@ -391,35 +390,35 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
     }
 
     /**
-     * Handles a StreamsInitialize request.
+     * Handles a StreamsGroupInitialize request.
      *
      * @param context The request context.
-     * @param request The actual StreamsInitialize request.
+     * @param request The actual StreamsGroupInitialize request.
      *
-     * @return A Result containing the StreamsInitialize response and
+     * @return A Result containing the StreamsGroupInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) {
-        return groupMetadataManager.streamsInitialize(context, request);
+        return groupMetadataManager.streamsGroupInitialize(context, request);
     }
 
     /**
-     * Handles a StreamsHeartbeat request.
+     * Handles a StreamsGroupHeartbeat request.
      *
      * @param context The request context.
-     * @param request The actual StreamsHeartbeat request.
+     * @param request The actual StreamsGroupHeartbeat request.
      *
-     * @return A Result containing the StreamsHeartbeat response and
+     * @return A Result containing the StreamsGroupHeartbeat response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) {
-        return groupMetadataManager.streamsHeartbeat(context, request);
+        return groupMetadataManager.streamsGroupHeartbeat(context, request);
     }
 
     /**
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 3e51e4b798a..40c9e652a1b 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -1672,7 +1672,7 @@ public class GroupMetadataManager {
      * @throws InvalidRequestException if the request is not valid.
      * @throws UnsupportedAssignorException if the assignor is not supported.
      */
-    private void throwIfStreamsInitializeRequestIsInvalid(
+    private void throwIfStreamsGroupInitializeRequestIsInvalid(
         StreamsGroupInitializeRequestData request
     ) throws InvalidRequestException, UnsupportedAssignorException {
         throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
@@ -1694,7 +1694,7 @@ public class GroupMetadataManager {
      * @throws InvalidRequestException if the request is not valid.
      * @throws UnsupportedAssignorException if the assignor is not supported.
      */
-    private void throwIfStreamsHeartbeatRequestIsInvalid(
+    private void throwIfStreamsGroupHeartbeatRequestIsInvalid(
         StreamsGroupHeartbeatRequestData request
     ) throws InvalidRequestException, UnsupportedAssignorException {
         throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
@@ -2243,9 +2243,9 @@ public class GroupMetadataManager {
      * @param ownedWarmupTasks   The list of owned warmup tasks from the request or null.
      * @param userEndpoint
      * @param clientTags
-     * @return A Result containing the StreamsHeartbeat response and a list of records to update the state machine.
+     * @return A Result containing the StreamsGroupHeartbeat response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
         String groupId,
         String memberId,
         int memberEpoch,
@@ -2422,15 +2422,15 @@ public class GroupMetadataManager {
             || hasAssignedStandbyTasksChanged(member, updatedMember)
             || hasAssignedWarmupTasksChanged(member, updatedMember)
         ) {
-            response.setActiveTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedActiveTasks()));
-            response.setStandbyTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedStandbyTasks()));
-            response.setWarmupTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedWarmupTasks()));
+            response.setActiveTasks(createStreamsGroupHeartbeatResponseTaskIds(updatedMember.assignedActiveTasks()));
+            response.setStandbyTasks(createStreamsGroupHeartbeatResponseTaskIds(updatedMember.assignedStandbyTasks()));
+            response.setWarmupTasks(createStreamsGroupHeartbeatResponseTaskIds(updatedMember.assignedWarmupTasks()));
         }
 
         return new CoordinatorResult<>(records, response);
     }
 
-    private List<StreamsGroupHeartbeatResponseData.TaskIds> createStreamsHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
+    private List<StreamsGroupHeartbeatResponseData.TaskIds> createStreamsGroupHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
         return taskIds.entrySet().stream()
             .map(entry -> new StreamsGroupHeartbeatResponseData.TaskIds()
                 .setSubtopology(entry.getKey())
@@ -2655,10 +2655,10 @@ public class GroupMetadataManager {
      *
      * @param groupId       The group id from the request.
      * @param subtopologies The list of subtopologies
-     * @return A Result containing the StreamsInitialize response and a list of records to update the state machine.
+     * @return A Result containing the StreamsGroupInitialize response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(String groupId,
-                                                                                                       List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
+    private CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(String groupId,
+                                                                                                            List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
         throws ApiException {
         final List<CoordinatorRecord> records = new ArrayList<>();
 
@@ -3656,13 +3656,13 @@ public class GroupMetadataManager {
      * @param targetAssignmentEpoch The target assignment epoch.
      * @param targetAssignment      The target assignment.
      * @param ownedActiveTasks      The list of active tasks owned by the member. This
-     *                              is reported in the StreamsHeartbeat API and
+     *                              is reported in the StreamsGroupHeartbeat API and
      *                              it could be null if not provided.
      * @param ownedStandbyTasks     The list of standby owned by the member. This
-     *                              is reported in the StreamsHeartbeat API and
+     *                              is reported in the StreamsGroupHeartbeat API and
      *                              it could be null if not provided.
      * @param ownedWarmupTasks      The list of warmup tasks owned by the member. This
-     *                              is reported in the StreamsHeartbeat API and
+     *                              is reported in the StreamsGroupHeartbeat API and
      *                              it could be null if not provided.
      * @param records               The list to accumulate any new records.
      * @return The received member if no changes have been made; or a new
@@ -3950,7 +3950,7 @@ public class GroupMetadataManager {
      * @param memberId      The member id from the request.
      * @param memberEpoch   The member epoch from the request.
      *
-     * @return A Result containing the StreamsHeartbeat response and
+     * @return A Result containing the StreamsGroupHeartbeat response and
      *         a list of records to update the state machine.
      */
     private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupLeave(
@@ -4777,40 +4777,40 @@ public class GroupMetadataManager {
     }
 
     /**
-     * Handles a StreamsInitialize request.
+     * Handles a StreamsGroupInitialize request.
      *
      * @param context The request context.
-     * @param request The actual StreamsInitialize request.
+     * @param request The actual StreamsGroupInitialize request.
      *
-     * @return A Result containing the StreamsInitialize response and
+     * @return A Result containing the StreamsGroupInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) throws ApiException {
-        throwIfStreamsInitializeRequestIsInvalid(request);
+        throwIfStreamsGroupInitializeRequestIsInvalid(request);
 
-        return streamsInitialize(
+        return streamsGroupInitialize(
             request.groupId(),
             request.topology()
         );
     }
 
     /**
-     * Handles a StreamsHeartbeat request.
+     * Handles a StreamsGroupHeartbeat request.
      *
      * @param context The request context.
-     * @param request The actual StreamsHeartbeat request.
+     * @param request The actual StreamsGroupHeartbeat request.
      *
-     * @return A Result containing the StreamsHeartbeat response and
+     * @return A Result containing the StreamsGroupHeartbeat response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) throws ApiException {
-        throwIfStreamsHeartbeatRequestIsInvalid(request);
+        throwIfStreamsGroupHeartbeatRequestIsInvalid(request);
 
         if (request.memberEpoch() == LEAVE_GROUP_MEMBER_EPOCH || request.memberEpoch() == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
             // -2 means that a static member wants to leave the group.
@@ -4821,7 +4821,7 @@ public class GroupMetadataManager {
                 request.memberEpoch()
             );
         } else {
-            return streamsHeartbeat(
+            return streamsGroupHeartbeat(
                 request.groupId(),
                 request.memberId(),
                 request.memberEpoch(),
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index f7690381708..4ff347c66b7 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -56,17 +56,17 @@ public class CurrentAssignmentBuilder {
     private BiFunction<String, Integer, Integer> currentTaskEpoch;
 
     /**
-     * The active tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     * The active tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks;
 
     /**
-     * The standby tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     * The standby tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks;
 
     /**
-     * The warmup tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
+     * The warmup tasks owned by the streams. This is directly provided by the member in the StreamsGroupHeartbeat request.
      */
     private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks;
 
@@ -110,7 +110,7 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Sets the active tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * Sets the active tasks currently owned by the member. This comes directly from the last StreamsGroupHeartbeat request. This is used to
      * determine if the member has revoked the necessary tasks.
      *
      * @param ownedActiveTasks A list of topic-tasks.
@@ -124,7 +124,7 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Sets the standby tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * Sets the standby tasks currently owned by the member. This comes directly from the last StreamsGroupHeartbeat request. This is used to
      * determine if the member has revoked the necessary tasks.
      *
      * @param ownedStandbyTasks A list of topic-tasks.
@@ -138,7 +138,7 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Sets the warmup tasks currently owned by the member. This comes directly from the last StreamsHeartbeat request. This is used to
+     * Sets the warmup tasks currently owned by the member. This comes directly from the last StreamsGroupHeartbeat request. This is used to
      * determine if the member has revoked the necessary tasks.
      *
      * @param ownedWarmupTasks A list of topic-tasks.
@@ -178,7 +178,7 @@ public class CurrentAssignmentBuilder {
                 // When the member is in the UNREVOKED_TASKS state, we wait
                 // until the member has revoked the necessary tasks. They are
                 // considered revoked when they are not anymore reported in the
-                // owned tasks set in the StreamsHeartbeat API.
+                // owned tasks set in the StreamsGroupHeartbeat API.
 
                 // If the member provides its owned tasks. We verify if it still
                 // owns any of the revoked tasks. If it does, we cannot progress.
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index dfd898c225c..7505aa8c791 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -267,7 +267,7 @@ public class GroupCoordinatorServiceTest {
     }
 
     @Test
-    public void testStreamsInitializeWhenNotStarted() throws ExecutionException, InterruptedException {
+    public void testStreamsGroupInitializeWhenNotStarted() throws ExecutionException, InterruptedException {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
         GroupCoordinatorService service = new GroupCoordinatorService(
             new LogContext(),
@@ -280,7 +280,7 @@ public class GroupCoordinatorServiceTest {
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
@@ -293,7 +293,7 @@ public class GroupCoordinatorServiceTest {
     }
 
     @Test
-    public void testStreamsInitialize() throws ExecutionException, InterruptedException, TimeoutException {
+    public void testStreamsGroupInitialize() throws ExecutionException, InterruptedException, TimeoutException {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
         GroupCoordinatorService service = new GroupCoordinatorService(
             new LogContext(),
@@ -317,7 +317,7 @@ public class GroupCoordinatorServiceTest {
             new StreamsGroupInitializeResponseData()
         ));
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
@@ -325,7 +325,7 @@ public class GroupCoordinatorServiceTest {
         assertEquals(new StreamsGroupInitializeResponseData(), future.get(5, TimeUnit.SECONDS));
     }
 
-    private static Stream<Arguments> testStreamsInitializeWithExceptionSource() {
+    private static Stream<Arguments> testStreamsGroupInitializeWithExceptionSource() {
         return Stream.of(
             Arguments.arguments(new UnknownTopicOrPartitionException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
             Arguments.arguments(new NotEnoughReplicasException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
@@ -341,8 +341,8 @@ public class GroupCoordinatorServiceTest {
     }
 
     @ParameterizedTest
-    @MethodSource("testStreamsInitializeWithExceptionSource")
-    public void testStreamsInitializeWithException(
+    @MethodSource("testStreamsGroupInitializeWithExceptionSource")
+    public void testStreamsGroupInitializeWithException(
         Throwable exception,
         short expectedErrorCode,
         String expectedErrorMessage
@@ -368,7 +368,7 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
@@ -382,7 +382,7 @@ public class GroupCoordinatorServiceTest {
     }
 
     @Test
-    public void testStreamsHeartbeatWhenNotStarted() throws ExecutionException, InterruptedException {
+    public void testStreamsGroupHeartbeatWhenNotStarted() throws ExecutionException, InterruptedException {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
         GroupCoordinatorService service = new GroupCoordinatorService(
             new LogContext(),
@@ -395,7 +395,7 @@ public class GroupCoordinatorServiceTest {
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
@@ -408,7 +408,7 @@ public class GroupCoordinatorServiceTest {
     }
 
     @Test
-    public void testStreamsHeartbeat() throws ExecutionException, InterruptedException, TimeoutException {
+    public void testStreamsGroupHeartbeat() throws ExecutionException, InterruptedException, TimeoutException {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
         GroupCoordinatorService service = new GroupCoordinatorService(
             new LogContext(),
@@ -432,7 +432,7 @@ public class GroupCoordinatorServiceTest {
             new StreamsGroupHeartbeatResponseData()
         ));
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
@@ -440,7 +440,7 @@ public class GroupCoordinatorServiceTest {
         assertEquals(new StreamsGroupHeartbeatResponseData(), future.get(5, TimeUnit.SECONDS));
     }
 
-    private static Stream<Arguments> testStreamsHeartbeatWithExceptionSource() {
+    private static Stream<Arguments> testStreamsGroupHeartbeatWithExceptionSource() {
         return Stream.of(
             Arguments.arguments(new UnknownTopicOrPartitionException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
             Arguments.arguments(new NotEnoughReplicasException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
@@ -455,8 +455,8 @@ public class GroupCoordinatorServiceTest {
     }
 
     @ParameterizedTest
-    @MethodSource("testStreamsHeartbeatWithExceptionSource")
-    public void testStreamsHeartbeatWithException(
+    @MethodSource("testStreamsGroupHeartbeatWithExceptionSource")
+    public void testStreamsGroupHeartbeatWithException(
         Throwable exception,
         short expectedErrorCode,
         String expectedErrorMessage
@@ -482,7 +482,7 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index e7fffb90c8c..263b2ab76ea 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -136,7 +136,7 @@ public class GroupCoordinatorShardTest {
     }
 
     @Test
-    public void testStreamsInitialize() {
+    public void testStreamsGroupInitialize() {
         GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
         OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
         CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
@@ -159,16 +159,16 @@ public class GroupCoordinatorShardTest {
             new StreamsGroupInitializeResponseData()
         );
 
-        when(groupMetadataManager.streamsInitialize(
+        when(groupMetadataManager.streamsGroupInitialize(
             context,
             request
         )).thenReturn(result);
 
-        assertEquals(result, coordinator.streamsInitialize(context, request));
+        assertEquals(result, coordinator.streamsGroupInitialize(context, request));
     }
 
     @Test
-    public void testStreamsHeartbeat() {
+    public void testStreamsGroupHeartbeat() {
         GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
         OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
         CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
@@ -191,12 +191,12 @@ public class GroupCoordinatorShardTest {
             new StreamsGroupHeartbeatResponseData()
         );
 
-        when(groupMetadataManager.streamsHeartbeat(
+        when(groupMetadataManager.streamsGroupHeartbeat(
             context,
             request
         )).thenReturn(result);
 
-        assertEquals(result, coordinator.streamsHeartbeat(context, request));
+        assertEquals(result, coordinator.streamsGroupHeartbeat(context, request));
     }
     
     @Test
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index bbbfe346539..05a94ea49a6 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -272,25 +272,25 @@ public class GroupMetadataManagerTest {
         Exception ex;
 
         // GroupId must be present in all requests.
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()));
         assertEquals("GroupId can't be empty.", ex.getMessage());
 
         // GroupId can't be all whitespaces.
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("   ")));
         assertEquals("GroupId can't be empty.", ex.getMessage());
 
         // RebalanceTimeoutMs must be present in the first request (epoch == 0).
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)));
         assertEquals("RebalanceTimeoutMs must be provided in first request.", ex.getMessage());
 
         // ActiveTasks must be present and empty in the first request (epoch == 0).
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
@@ -300,7 +300,7 @@ public class GroupMetadataManagerTest {
         assertEquals("ActiveTasks must be empty when (re-)joining.", ex.getMessage());
 
         // StandbyTasks must be present and empty in the first request (epoch == 0).
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
@@ -310,7 +310,7 @@ public class GroupMetadataManagerTest {
         assertEquals("StandbyTasks must be empty when (re-)joining.", ex.getMessage());
 
         // WarmupTasks must be present and empty in the first request (epoch == 0).
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
@@ -321,14 +321,14 @@ public class GroupMetadataManagerTest {
 
         // MemberId must be non-empty in all requests except for the first one where it
         // could be empty (epoch != 0).
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(1)));
         assertEquals("MemberId can't be empty.", ex.getMessage());
 
         // InstanceId must be non-empty if provided in all requests.
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberId(Uuid.randomUuid().toString())
@@ -337,7 +337,7 @@ public class GroupMetadataManagerTest {
         assertEquals("InstanceId can't be empty.", ex.getMessage());
 
         // RackId must be non-empty if provided in all requests.
-        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsGroupHeartbeat(
             new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberId(Uuid.randomUuid().toString())
@@ -346,8 +346,8 @@ public class GroupMetadataManagerTest {
         assertEquals("RackId can't be empty.", ex.getMessage());
 
 //       TODO: // ServerAssignor must exist if provided in all requests.
-//        ex = assertThrows(UnsupportedAssignorException.class, () -> context.streamsHeartbeat(
-//            new StreamsHeartbeatRequestData()
+//        ex = assertThrows(UnsupportedAssignorException.class, () -> context.streamsGroupHeartbeat(
+//            new StreamsGroupHeartbeatRequestData()
 //                .setGroupId("foo")
 //                .setMemberId(Uuid.randomUuid().toString())
 //                .setMemberEpoch(1)
@@ -16016,15 +16016,15 @@ public class GroupMetadataManagerTest {
 //                    )
 //                )
 //        );
-//        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
-//            context.streamsInitialize(
-//                new StreamsInitializeRequestData()
+//        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
+//            context.streamsGroupInitialize(
+//                new streamsGroupInitializeRequestData()
 //                    .setGroupId(groupId)
 //                    .setTopology(topology)
 //            );
 //
 //        assertEquals(
-//            new StreamsInitializeResponseData(),
+//            new StreamsGroupInitializeResponseData(),
 //            result.response()
 //        );
 //
@@ -16086,15 +16086,15 @@ public class GroupMetadataManagerTest {
 //                    )
 //                )
 //        );
-//        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
-//            context.streamsInitialize(
-//                new StreamsInitializeRequestData()
+//        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
+//            context.streamsGroupInitialize(
+//                new streamsGroupInitializeRequestData()
 //                    .setGroupId(groupId)
 //                    .setTopology(topology)
 //            );
 //
 //        assertEquals(
-//            new StreamsInitializeResponseData()
+//            new StreamsGroupInitializeResponseData()
 //                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
 //                .setErrorMessage("Internal topics changelog do not exist."),
 //            result.response()
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 45654736316..d77f5414ee9 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -727,7 +727,7 @@ public class GroupMetadataManagerTestContext {
     }
 
 
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
         StreamsGroupInitializeRequestData request
     ) {
         RequestContext context = new RequestContext(
@@ -746,7 +746,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsInitialize(
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsGroupInitialize(
             context,
             request
         );
@@ -757,7 +757,7 @@ public class GroupMetadataManagerTestContext {
         return result;
     }
 
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
         StreamsGroupHeartbeatRequestData request
     ) {
         RequestContext context = new RequestContext(
@@ -776,7 +776,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsHeartbeat(
+        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsGroupHeartbeat(
             context,
             request
         );


(kafka) 01/42: Very initial (compiling) streams RPCs.

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 5eb61c087cae561f115098b2c6fe0738c41853b2
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Wed Apr 17 17:28:38 2024 +0200

    Very initial (compiling) streams RPCs.
    
    Basic initial RPCS.
    
    See https://github.com/lucasbru/kafka/pull/6
---
 .../common/message/StreamsHeartbeatRequest.json    | 87 ++++++++++++++++++++
 .../common/message/StreamsHeartbeatResponse.json   | 96 ++++++++++++++++++++++
 2 files changed, 183 insertions(+)

diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
new file mode 100644
index 00000000000..a5f52e262f2
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -0,0 +1,87 @@
+// 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.
+
+{
+  "apiKey": 76,
+  "type": "request",
+  "listeners": ["zkBroker", "broker"],
+  "name": "StreamsHeartbeatRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+      "about": "The group identifier." },
+    { "name": "MemberId", "type": "string", "versions": "0+",
+      "about": "The member id generated by the coordinator. The member id must be kept during the entire lifetime of the member." },
+    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+      "about": "The current member epoch; 0 to join the group; -1 to leave the group; -2 to indicate that the static member will rejoin." },
+    { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "null if not provided or if it didn't change since the last heartbeat; the instance Id otherwise." },
+    { "name": "RackId", "type": "string", "versions": "0+",  "nullableVersions": "0+", "default": "null",
+      "about": "null if not provided or if it didn't change since the last heartbeat; the rack ID of consumer otherwise." },
+    { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
+      "about": "-1 if it didn't change since the last heartbeat; the maximum time in milliseconds that the coordinator will wait on the member to revoke its partitions otherwise." },
+
+    // If the topology hash does not match the server's topology hash, return INVALID_TOPOLOGY and send ShouldInitializeTopology to one consumer
+    { "name": "TopologyHash", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": null,
+      "about": "The hash of the topology. Only sent when memberEpoch = 0. Null otherwise. Used to check if topology corresponds to server-topology. " },
+
+    // The coordinator knows which partitions to fetch from given this information
+    { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
+    { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
+    { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
+
+    { "name": "ProcessId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Identity of the streams instance that may have multiple consumers. Null if unchanged since last heartbeat." },
+    { "name": "UserEndPoint", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "End-point a user can use for IQ. Null if unchanged since last heartbeat." },
+    { "name": "ClientTags", "type": "[]string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
+
+    { "name": "TaskLagUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
+      "about": "Reason for updating task lag. 0 if no update, 1 if task lag is updated due to warm up being ready, 2 if warm up failed" },
+    { "name": "TaskLag", "type": "[]TaskLag", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Cumulative lags for standby tasks. Only updatable when TaskLagUpdateReason is not zero. Null if unchanged since last heartbeat.",
+      "fields": [
+        { "name": "TaskId", "type": "TaskId", "versions": "0+",
+          "about": "The task ID" },
+        { "name": "Lag", "type": "int64", "versions": "0+",
+          "about": "The cumulative lag for the task" }
+      ]
+    },
+    { "name": "AssignmentConfigs", "type": "[]AssignmentConfig", "versions": "0+","nullableVersions": "0+", "default": "null",
+      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat.",
+      "fields": [
+        { "name": "Key", "type": "string", "versions": "0+",
+          "about": "key of the config" },
+        { "name": "Value", "type": "string", "versions": "0+",
+          "about": "value of the config" }
+      ]
+    }
+  ],
+  "commonStructs": [
+    { "name": "TaskId", "versions": "0+", "fields": [
+      // We are using strings here, to avoid fixing a structure on task IDs which will
+      // allow introducing stable naming for subtopologies in the future.
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "subtopology ID" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]}
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
new file mode 100644
index 00000000000..0ab1b0f0ea0
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
@@ -0,0 +1,96 @@
+// 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.
+
+{
+  "apiKey": 76,
+  "type": "response",
+  "name": "StreamsHeartbeatResponse",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  // Supported errors:
+  // - GROUP_AUTHORIZATION_FAILED (version 0+)
+  // - NOT_COORDINATOR (version 0+)
+  // - COORDINATOR_NOT_AVAILABLE (version 0+)
+  // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
+  // - INVALID_REQUEST (version 0+)
+  // - UNKNOWN_MEMBER_ID (version 0+)
+  // - FENCED_MEMBER_EPOCH (version 0+)
+  // - UNSUPPORTED_ASSIGNOR (version 0+)
+  // - UNRELEASED_INSTANCE_ID (version 0+)
+  // - GROUP_MAX_SIZE_REACHED (version 0+)
+
+  // Streams-specific errors:
+  // - INCONSISTENT_TOPOLOGY (version 0+)
+  // - MISSING_SOURCE_TOPICS (version 0+)
+  // - MISSING_INTERNAL_TOPICS (version 0+)
+  "fields": [
+    // Same as consumer group heart beat
+    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
+      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
+    { "name": "ErrorCode", "type": "int16", "versions": "0+",
+      "about": "The top-level error code, or 0 if there was no error" },
+    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The top-level error message, or null if there was no error." },
+    { "name": "MemberId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The member id generated by the coordinator. Only provided when the member joins with MemberEpoch == 0." },
+    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+      "about": "The member epoch." },
+    { "name": "HeartbeatIntervalMs", "type": "int32", "versions": "0+",
+      "about": "The heartbeat interval in milliseconds." },
+
+    // Assigning specific roles to the consumer
+    { "name": "ShouldComputeAssignment", "type":  "bool", "versions":  "0+", "default": false,
+      "about": "true if this streams application should compute the next assignment." },
+    { "name": "ShouldInitializeTopology", "type":  "bool", "versions":  "0+", "default": false,
+      "about": "true if this streams application should initialize the topology on the broker" },
+
+    // The streams app knows which partitions to fetch from given this information
+    { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
+    { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
+    { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
+
+    // IQ-related information
+    { "name": "PartitionsByHost", "type": "[]HostInfo", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Global assignment information used for IQ. Null if unchanged since last heartbeat." ,
+      "fields": [
+        { "name": "Host", "type": "string", "versions": "0+",
+          "about": "Hostname of the node" },
+        { "name": "Port", "type": "int32", "versions": "0+",
+          "about": "Port of the node" },
+        { "name": "Partitions", "type": "[]TopicPartition", "versions": "0+",
+          "about": "All partitions available on the node" }
+      ]
+    }
+  ],
+  "commonStructs": [
+    { "name": "TopicPartition", "versions": "0+", "fields": [
+      { "name": "Topic", "type": "string", "versions": "0+",
+        "about": "topic name" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]},
+    { "name": "TaskId", "versions": "0+", "fields": [
+      // We are using strings here, to avoid fixing a structure on task IDs which will
+      // allow introducing stable naming for subtopologies in the future.
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "subtopology ID" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]}
+  ]
+}


(kafka) 37/42: Resolve conflicts from 11/15 trunk rebase - Initialize topologies as part of heartbeat (#17695)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 6b98ec67ee34e283f50957728784d0103699e4dc
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Wed Nov 6 15:49:06 2024 +0100

    Resolve conflicts from 11/15 trunk rebase - Initialize topologies as part of heartbeat (#17695)
    
    We merge the initialization of the Streams group into the heartbeat of the Streams group.
    As a result the first heartbeat of a member (member epoch is zero) contains the topology
    metadata required for initialization.
---
 .../consumer/internals/RequestManagers.java        |  17 +-
 .../internals/StreamsAssignmentInterface.java      |   8 +-
 .../StreamsGroupHeartbeatRequestManager.java       | 116 +++++-
 .../StreamsGroupInitializeRequestManager.java      | 210 ----------
 .../org/apache/kafka/common/protocol/ApiKeys.java  |   1 -
 .../kafka/common/requests/AbstractRequest.java     |   2 -
 .../kafka/common/requests/AbstractResponse.java    |   2 -
 .../requests/StreamsGroupHeartbeatResponse.java    |   1 +
 .../requests/StreamsGroupInitializeRequest.java    |  77 ----
 .../requests/StreamsGroupInitializeResponse.java   |  71 ----
 .../message/StreamsGroupDescribeRequest.json       |   2 +-
 .../message/StreamsGroupDescribeResponse.json      |   6 +-
 .../message/StreamsGroupHeartbeatRequest.json      |  65 ++-
 .../message/StreamsGroupHeartbeatResponse.json     |  15 +-
 .../message/StreamsGroupInitializeRequest.json     |  77 ----
 .../message/StreamsGroupInitializeResponse.json    |  42 --
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  84 +++-
 .../StreamsGroupInitializeRequestManagerTest.java  | 152 -------
 .../events/ApplicationEventProcessorTest.java      |   1 -
 .../kafka/common/requests/RequestResponseTest.java |  12 -
 .../group/GroupCoordinatorAdapter.scala            |  15 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   | 131 +++---
 .../group/GroupCoordinatorAdapterTest.scala        |  18 +-
 .../scala/unit/kafka/server/KafkaApisTest.scala    | 194 +++++++--
 .../scala/unit/kafka/server/RequestQuotaTest.scala |   3 -
 .../kafka/coordinator/group/GroupCoordinator.java  |  22 +-
 .../coordinator/group/GroupCoordinatorService.java |  49 +--
 .../coordinator/group/GroupCoordinatorShard.java   |  25 +-
 .../coordinator/group/GroupMetadataManager.java    | 318 ++++-----------
 .../metrics/GroupCoordinatorMetricsShard.java      |   8 +-
 .../streams/CoordinatorStreamsRecordHelpers.java   |  18 +-
 ...opology.java => StreamsConfiguredTopology.java} |  80 ++--
 .../coordinator/group/streams/StreamsGroup.java    | 119 ++++--
 ...esult.java => StreamsGroupHeartbeatResult.java} |  16 +-
 .../coordinator/group/streams/StreamsTopology.java |  48 +--
 .../group/streams/TargetAssignmentBuilder.java     |   8 +-
 .../group/streams/topics/InternalTopicManager.java |  31 +-
 .../group/GroupCoordinatorServiceTest.java         | 146 +------
 .../group/GroupCoordinatorShardTest.java           |  40 +-
 .../group/GroupMetadataManagerTest.java            | 439 ++++++++-------------
 .../group/GroupMetadataManagerTestContext.java     |  39 +-
 .../CoordinatorStreamsRecordHelpersTest.java       |  18 +-
 .../streams/StreamsConfiguredTopologyTest.java     |  93 +++++
 .../group/streams/StreamsGroupTest.java            |  43 +-
 .../group/streams/StreamsTopologyTest.java         |  75 +---
 .../group/streams/TargetAssignmentBuilderTest.java |   2 +-
 .../streams/topics/InternalTopicManagerTest.java   |  45 +--
 .../apache/kafka/network/RequestConvertToJson.java |  16 +
 streams/src/test/resources/log4j.properties        |   1 -
 49 files changed, 1057 insertions(+), 1964 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 9128ee7889b..4058bd72725 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -59,7 +59,6 @@ public class RequestManagers implements Closeable {
     public final FetchRequestManager fetchRequestManager;
     public final Optional<ShareConsumeRequestManager> shareConsumeRequestManager;
     public final Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager;
-    public final Optional<StreamsGroupInitializeRequestManager> streamsGroupInitializeRequestManager;
     private final List<Optional<? extends RequestManager>> entries;
     private final IdempotentCloser closer = new IdempotentCloser();
 
@@ -71,8 +70,7 @@ public class RequestManagers implements Closeable {
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
                            Optional<ConsumerMembershipManager> membershipManager,
-                           Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager,
-                           Optional<StreamsGroupInitializeRequestManager> streamsGroupInitializeRequestManager) {
+                           Optional<StreamsGroupHeartbeatRequestManager> streamsGroupHeartbeatRequestManager) {
         this.log = logContext.logger(RequestManagers.class);
         this.offsetsRequestManager = requireNonNull(offsetsRequestManager, "OffsetsRequestManager cannot be null");
         this.coordinatorRequestManager = coordinatorRequestManager;
@@ -85,7 +83,6 @@ public class RequestManagers implements Closeable {
         this.consumerMembershipManager = membershipManager;
         this.shareMembershipManager = Optional.empty();
         this.streamsGroupHeartbeatRequestManager = streamsGroupHeartbeatRequestManager;
-        this.streamsGroupInitializeRequestManager = streamsGroupInitializeRequestManager;
 
         List<Optional<? extends RequestManager>> list = new ArrayList<>();
         list.add(coordinatorRequestManager);
@@ -96,7 +93,6 @@ public class RequestManagers implements Closeable {
         list.add(Optional.of(topicMetadataRequestManager));
         list.add(Optional.of(fetchRequestManager));
         list.add(streamsGroupHeartbeatRequestManager);
-        list.add(streamsGroupInitializeRequestManager);
         entries = Collections.unmodifiableList(list);
     }
 
@@ -114,7 +110,6 @@ public class RequestManagers implements Closeable {
         this.consumerMembershipManager = Optional.empty();
         this.shareMembershipManager = shareMembershipManager;
         this.streamsGroupHeartbeatRequestManager = Optional.empty();
-        this.streamsGroupInitializeRequestManager = Optional.empty();
         this.offsetsRequestManager = null;
         this.topicMetadataRequestManager = null;
         this.fetchRequestManager = null;
@@ -199,7 +194,6 @@ public class RequestManagers implements Closeable {
                 CoordinatorRequestManager coordinator = null;
                 CommitRequestManager commitRequestManager = null;
                 StreamsGroupHeartbeatRequestManager streamsGroupHeartbeatRequestManager = null;
-                StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = null;
 
                 if (groupRebalanceConfig != null && groupRebalanceConfig.groupId != null) {
                     Optional<String> serverAssignor = Optional.ofNullable(config.getString(ConsumerConfig.GROUP_REMOTE_ASSIGNOR_CONFIG));
@@ -245,17 +239,11 @@ public class RequestManagers implements Closeable {
                     membershipManager.registerStateListener(applicationThreadMemberStateListener);
 
                     if (streamsInstanceMetadata.isPresent()) {
-                        streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
-                            logContext,
-                            groupRebalanceConfig.groupId,
-                            streamsInstanceMetadata.get(),
-                            coordinator);
                         streamsGroupHeartbeatRequestManager = new StreamsGroupHeartbeatRequestManager(
                             logContext,
                             time,
                             config,
                             coordinator,
-                            streamsGroupInitializeRequestManager,
                             membershipManager,
                             backgroundEventHandler,
                             metrics,
@@ -296,8 +284,7 @@ public class RequestManagers implements Closeable {
                         Optional.ofNullable(commitRequestManager),
                         Optional.ofNullable(heartbeatRequestManager),
                         Optional.ofNullable(membershipManager),
-                        Optional.ofNullable(streamsGroupHeartbeatRequestManager),
-                        Optional.ofNullable(streamsGroupInitializeRequestManager)
+                        Optional.ofNullable(streamsGroupHeartbeatRequestManager)
                 );
             }
         };
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index 650edaa2de2..de6cb9e2098 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -251,19 +251,19 @@ public class StreamsAssignmentInterface {
     public static class Subtopology {
 
         public final Set<String> sourceTopics;
-        public final Set<String> sinkTopics;
+        public final Set<String> repartitionSinkTopics;
         public final Map<String, TopicInfo> stateChangelogTopics;
         public final Map<String, TopicInfo> repartitionSourceTopics;
         public final Collection<Set<String>> copartitionGroups;
 
         public Subtopology(final Set<String> sourceTopics,
-                           final Set<String> sinkTopics,
+                           final Set<String> repartitionSinkTopics,
                            final Map<String, TopicInfo> repartitionSourceTopics,
                            final Map<String, TopicInfo> stateChangelogTopics,
                            final Collection<Set<String>> copartitionGroups
         ) {
             this.sourceTopics = sourceTopics;
-            this.sinkTopics = sinkTopics;
+            this.repartitionSinkTopics = repartitionSinkTopics;
             this.stateChangelogTopics = stateChangelogTopics;
             this.repartitionSourceTopics = repartitionSourceTopics;
             this.copartitionGroups = copartitionGroups;
@@ -273,7 +273,7 @@ public class StreamsAssignmentInterface {
         public String toString() {
             return "Subtopology{" +
                 "sourceTopics=" + sourceTopics +
-                ", sinkTopics=" + sinkTopics +
+                ", repartitionSinkTopics=" + repartitionSinkTopics +
                 ", stateChangelogTopics=" + stateChangelogTopics +
                 ", repartitionSourceTopics=" + repartitionSourceTopics +
                 ", copartitionGroups=" + copartitionGroups +
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 5fc15b7e436..7506a497939 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -29,6 +29,7 @@ import org.apache.kafka.common.errors.RetriableException;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.CopartitionGroup;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskIds;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData.Endpoint;
@@ -44,13 +45,16 @@ import org.apache.kafka.common.utils.Timer;
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
+import java.util.stream.IntStream;
 import java.util.stream.Stream;
 
 public class StreamsGroupHeartbeatRequestManager implements RequestManager {
@@ -67,8 +71,6 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final ConsumerMembershipManager membershipManager;
 
-    private final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager;
-
     private final BackgroundEventHandler backgroundEventHandler;
 
     private final Timer pollTimer;
@@ -86,7 +88,6 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         final Time time,
         final ConsumerConfig config,
         final CoordinatorRequestManager coordinatorRequestManager,
-        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager,
         final ConsumerMembershipManager membershipManager,
         final BackgroundEventHandler backgroundEventHandler,
         final Metrics metrics,
@@ -96,7 +97,6 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         this.coordinatorRequestManager = coordinatorRequestManager;
         this.logger = logContext.logger(getClass());
         this.membershipManager = membershipManager;
-        this.streamsGroupInitializeRequestManager = streamsGroupInitializeRequestManager;
         this.backgroundEventHandler = backgroundEventHandler;
         this.maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
         long retryBackoffMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG);
@@ -248,9 +248,6 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         heartbeatRequestState.onSuccessfulAttempt(currentTimeMs);
         heartbeatRequestState.resetTimer();
 
-        if (data.shouldInitializeTopology()) {
-            streamsGroupInitializeRequestManager.initialize();
-        }
         if (data.partitionsByUserEndpoint() != null) {
             streamsInterface.partitionsByHost.set(convertHostInfoMap(data));
         }
@@ -286,7 +283,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         membershipManager.onHeartbeatSuccess(new ConsumerGroupHeartbeatResponse(cgData));
     }
 
-    private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
+    private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data,
+                                                     final ConsumerGroupHeartbeatResponseData cgData) {
         Map<String, TopicPartitions> tps = new HashMap<>();
         data.activeTasks().forEach(taskId -> Stream.concat(
                 streamsInterface.subtopologyMap().get(taskId.subtopologyId()).sourceTopics.stream(),
@@ -321,7 +319,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         streamsInterface.targetAssignment.set(targetAssignment);
     }
 
-    private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(final StreamsGroupHeartbeatResponseData data) {
+    private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(
+        final StreamsGroupHeartbeatResponseData data) {
         Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> partitionsByHost = new HashMap<>();
         data.partitionsByUserEndpoint().forEach(endpoint -> {
             List<TopicPartition> topicPartitions = endpoint.partitions().stream()
@@ -470,7 +469,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             final long retryBackoffMs,
             final long retryBackoffMaxMs,
             final double jitter) {
-            super(logContext, StreamsGroupHeartbeatRequestManager.HeartbeatRequestState.class.getName(), retryBackoffMs, 2, retryBackoffMaxMs,
+            super(logContext, StreamsGroupHeartbeatRequestManager.HeartbeatRequestState.class.getName(), retryBackoffMs, 2,
+                retryBackoffMaxMs,
                 jitter);
             this.heartbeatIntervalMs = heartbeatIntervalMs;
             this.heartbeatTimer = time.timer(heartbeatIntervalMs);
@@ -574,6 +574,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
             // Immutable -- only sent when joining
             if (joining) {
+                // Topology -- sent when joining
+                data.setTopology(getTopologyFromStreams());
                 data.setProcessId(streamsInterface.processId().toString());
                 data.setActiveTasks(Collections.emptyList());
                 data.setStandbyTasks(Collections.emptyList());
@@ -627,6 +629,100 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 .collect(Collectors.toList());
         }
 
+        private List<StreamsGroupHeartbeatRequestData.Subtopology> getTopologyFromStreams() {
+            final Map<String, StreamsAssignmentInterface.Subtopology> subTopologyMap = streamsInterface.subtopologyMap();
+            final List<StreamsGroupHeartbeatRequestData.Subtopology> subtopologies = new ArrayList<>(subTopologyMap.size());
+            for (final Map.Entry<String, StreamsAssignmentInterface.Subtopology> subtopology : subTopologyMap.entrySet()) {
+                subtopologies.add(getSubtopologyFromStreams(subtopology.getKey(), subtopology.getValue()));
+            }
+            subtopologies.sort(Comparator.comparing(StreamsGroupHeartbeatRequestData.Subtopology::subtopologyId));
+            return subtopologies;
+        }
+
+        private static StreamsGroupHeartbeatRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
+                                                                                              final StreamsAssignmentInterface.Subtopology subtopology) {
+            final StreamsGroupHeartbeatRequestData.Subtopology subtopologyData = new StreamsGroupHeartbeatRequestData.Subtopology();
+            subtopologyData.setSubtopologyId(subtopologyName);
+            ArrayList<String> sortedSourceTopics = new ArrayList<>(subtopology.sourceTopics);
+            Collections.sort(sortedSourceTopics);
+            subtopologyData.setSourceTopics(sortedSourceTopics);
+            ArrayList<String> sortedSinkTopics = new ArrayList<>(subtopology.repartitionSinkTopics);
+            Collections.sort(sortedSinkTopics);
+            subtopologyData.setRepartitionSinkTopics(sortedSinkTopics);
+            subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
+            subtopologyData.setStateChangelogTopics(getChangelogTopicsInfoFromStreams(subtopology));
+            subtopologyData.setCopartitionGroups(
+                getCopartitionGroupsFromStreams(subtopology.copartitionGroups, subtopologyData));
+            return subtopologyData;
+        }
+
+        private static List<CopartitionGroup> getCopartitionGroupsFromStreams(final Collection<Set<String>> copartitionGroups,
+                                                                              final StreamsGroupHeartbeatRequestData.Subtopology subtopologyData) {
+
+            final Map<String, Short> sourceTopicsMap =
+                IntStream.range(0, subtopologyData.sourceTopics().size())
+                    .boxed()
+                    .collect(Collectors.toMap(subtopologyData.sourceTopics()::get, Integer::shortValue));
+
+            final Map<String, Short> repartitionSourceTopics =
+                IntStream.range(0, subtopologyData.repartitionSourceTopics().size())
+                    .boxed()
+                    .collect(
+                        Collectors.toMap(x -> subtopologyData.repartitionSourceTopics().get(x).name(),
+                            Integer::shortValue));
+
+            return copartitionGroups.stream()
+                .map(x -> getCopartitionGroupFromStreams(x, sourceTopicsMap, repartitionSourceTopics))
+                .collect(Collectors.toList());
+        }
+
+        private static CopartitionGroup getCopartitionGroupFromStreams(final Set<String> topicNames,
+                                                                       final Map<String, Short> sourceTopicsMap,
+                                                                       final Map<String, Short> repartitionSourceTopics) {
+            CopartitionGroup copartitionGroup = new CopartitionGroup();
+
+            topicNames.forEach(topicName -> {
+                if (sourceTopicsMap.containsKey(topicName)) {
+                    copartitionGroup.sourceTopics().add(sourceTopicsMap.get(topicName));
+                } else if (repartitionSourceTopics.containsKey(topicName)) {
+                    copartitionGroup.repartitionSourceTopics()
+                        .add(repartitionSourceTopics.get(topicName));
+                } else {
+                    throw new IllegalStateException(
+                        "Source topic not found in subtopology: " + topicName);
+                }
+            });
+
+            return copartitionGroup;
+        }
+
+        private static List<StreamsGroupHeartbeatRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(
+            final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
+            final List<StreamsGroupHeartbeatRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
+            for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
+                final StreamsGroupHeartbeatRequestData.TopicInfo repartitionTopicInfo = new StreamsGroupHeartbeatRequestData.TopicInfo();
+                repartitionTopicInfo.setName(repartitionTopic.getKey());
+                repartitionTopic.getValue().numPartitions.ifPresent(repartitionTopicInfo::setPartitions);
+                repartitionTopic.getValue().replicationFactor.ifPresent(repartitionTopicInfo::setReplicationFactor);
+                repartitionTopicsInfo.add(repartitionTopicInfo);
+            }
+            repartitionTopicsInfo.sort(Comparator.comparing(StreamsGroupHeartbeatRequestData.TopicInfo::name));
+            return repartitionTopicsInfo;
+        }
+
+        private static List<StreamsGroupHeartbeatRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(
+            final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
+            final List<StreamsGroupHeartbeatRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
+            for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
+                final StreamsGroupHeartbeatRequestData.TopicInfo changelogTopicInfo = new StreamsGroupHeartbeatRequestData.TopicInfo();
+                changelogTopicInfo.setName(changelogTopic.getKey());
+                changelogTopic.getValue().replicationFactor.ifPresent(changelogTopicInfo::setReplicationFactor);
+                changelogTopicsInfo.add(changelogTopicInfo);
+            }
+            changelogTopicsInfo.sort(Comparator.comparing(StreamsGroupHeartbeatRequestData.TopicInfo::name));
+            return changelogTopicsInfo;
+        }
+
         // Fields of StreamsGroupHeartbeatRequest sent in the most recent request
         static class SentFields {
 
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
deleted file mode 100644
index 8c7671efe67..00000000000
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * 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 org.apache.kafka.clients.consumer.internals;
-
-import org.apache.kafka.clients.ClientResponse;
-import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData.CopartitionGroup;
-import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
-import org.apache.kafka.common.requests.StreamsGroupInitializeResponse;
-import org.apache.kafka.common.utils.LogContext;
-
-import org.slf4j.Logger;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-public class StreamsGroupInitializeRequestManager implements RequestManager {
-
-    private final Logger logger;
-    private final String groupId;
-    private final StreamsAssignmentInterface streamsAssignmentInterface;
-    private final CoordinatorRequestManager coordinatorRequestManager;
-
-    private Optional<NetworkClientDelegate.UnsentRequest> unsentRequest = Optional.empty();
-
-
-    StreamsGroupInitializeRequestManager(final LogContext logContext,
-                                         final String groupId,
-                                         final StreamsAssignmentInterface streamsAssignmentInterface,
-                                         final CoordinatorRequestManager coordinatorRequestManager) {
-        this.logger = logContext.logger(getClass());
-        this.groupId = groupId;
-        this.streamsAssignmentInterface = streamsAssignmentInterface;
-        this.coordinatorRequestManager = coordinatorRequestManager;
-    }
-
-    @Override
-    public PollResult poll(final long currentTimeMs) {
-        final PollResult pollResult = unsentRequest.map(PollResult::new).orElse(PollResult.EMPTY);
-        unsentRequest = Optional.empty();
-        return pollResult;
-    }
-
-    public void initialize() {
-        final NetworkClientDelegate.UnsentRequest unsentRequest = makeRequest();
-
-        unsentRequest.whenComplete(this::onResponse);
-
-        this.unsentRequest = Optional.of(unsentRequest);
-    }
-
-    private NetworkClientDelegate.UnsentRequest makeRequest() {
-        final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = new StreamsGroupInitializeRequestData();
-        streamsGroupInitializeRequestData.setGroupId(groupId);
-        streamsGroupInitializeRequestData.setTopologyId(streamsAssignmentInterface.topologyId());
-        final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
-        streamsGroupInitializeRequestData.setTopology(topology);
-        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder =
-            new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequestData);
-        return new NetworkClientDelegate.UnsentRequest(
-            streamsGroupInitializeRequestBuilder,
-            coordinatorRequestManager.coordinator()
-        );
-    }
-
-    private List<StreamsGroupInitializeRequestData.Subtopology> getTopologyFromStreams() {
-        final Map<String, StreamsAssignmentInterface.Subtopology> subTopologyMap = streamsAssignmentInterface.subtopologyMap();
-        final List<StreamsGroupInitializeRequestData.Subtopology> topology = new ArrayList<>(subTopologyMap.size());
-        for (final Map.Entry<String, StreamsAssignmentInterface.Subtopology> subtopology : subTopologyMap.entrySet()) {
-            topology.add(getSubtopologyFromStreams(subtopology.getKey(), subtopology.getValue()));
-        }
-        return topology;
-    }
-
-    private static StreamsGroupInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
-                                                                                           final StreamsAssignmentInterface.Subtopology subtopology) {
-        final StreamsGroupInitializeRequestData.Subtopology subtopologyData = new StreamsGroupInitializeRequestData.Subtopology();
-        subtopologyData.setSubtopologyId(subtopologyName);
-        ArrayList<String> sortedSourceTopics = new ArrayList<>(subtopology.sourceTopics);
-        Collections.sort(sortedSourceTopics);
-        subtopologyData.setSourceTopics(sortedSourceTopics);
-        // TODO: We should only encode the repartition sink topics here.
-        ArrayList<String> sortedSinkTopics = new ArrayList<>(subtopology.sinkTopics);
-        Collections.sort(sortedSinkTopics);
-        subtopologyData.setRepartitionSinkTopics(sortedSinkTopics);
-        subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
-        subtopologyData.setStateChangelogTopics(getChangelogTopicsInfoFromStreams(subtopology));
-        subtopologyData.setCopartitionGroups(
-            getCopartitionGroupsFromStreams(subtopology.copartitionGroups, subtopologyData));
-        return subtopologyData;
-    }
-
-    private static List<CopartitionGroup> getCopartitionGroupsFromStreams(
-        final Collection<Set<String>> copartitionGroups,
-        final StreamsGroupInitializeRequestData.Subtopology subtopologyData) {
-
-        final Map<String, Short> sourceTopicsMap =
-            IntStream.range(0, subtopologyData.sourceTopics().size())
-                .boxed()
-                .collect(Collectors.toMap(subtopologyData.sourceTopics()::get, Integer::shortValue));
-
-        final Map<String, Short> repartitionSourceTopics =
-            IntStream.range(0, subtopologyData.repartitionSourceTopics().size())
-                .boxed()
-                .collect(
-                    Collectors.toMap(x -> subtopologyData.repartitionSourceTopics().get(x).name(),
-                        Integer::shortValue));
-
-        return copartitionGroups.stream()
-            .map(x -> getCopartitionGroupFromStreams(x, sourceTopicsMap, repartitionSourceTopics))
-            .collect(Collectors.toList());
-    }
-
-    private static CopartitionGroup getCopartitionGroupFromStreams(
-        final Set<String> topicNames,
-        final Map<String, Short> sourceTopicsMap,
-        final Map<String, Short> repartitionSourceTopics) {
-        CopartitionGroup copartitionGroup = new CopartitionGroup();
-
-        topicNames.forEach(topicName -> {
-            if (sourceTopicsMap.containsKey(topicName)) {
-                copartitionGroup.sourceTopics().add(sourceTopicsMap.get(topicName));
-            } else if (repartitionSourceTopics.containsKey(topicName)) {
-                copartitionGroup.repartitionSourceTopics()
-                    .add(repartitionSourceTopics.get(topicName));
-            } else {
-                throw new IllegalStateException(
-                    "Source topic not found in subtopology: " + topicName);
-            }
-        });
-
-        return copartitionGroup;
-    }
-
-    private static List<StreamsGroupInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
-        final List<StreamsGroupInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
-        for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
-            final StreamsGroupInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
-            repartitionTopicInfo.setName(repartitionTopic.getKey());
-            repartitionTopic.getValue().numPartitions.ifPresent(repartitionTopicInfo::setPartitions);
-            repartitionTopic.getValue().replicationFactor.ifPresent(repartitionTopicInfo::setReplicationFactor);
-            repartitionTopicsInfo.add(repartitionTopicInfo);
-        }
-        repartitionTopicsInfo.sort(Comparator.comparing(StreamsGroupInitializeRequestData.TopicInfo::name));
-        return repartitionTopicsInfo;
-    }
-
-    private static List<StreamsGroupInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
-        final List<StreamsGroupInitializeRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
-        for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
-            final StreamsGroupInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
-            changelogTopicInfo.setName(changelogTopic.getKey());
-            changelogTopic.getValue().replicationFactor.ifPresent(changelogTopicInfo::setReplicationFactor);
-            changelogTopicsInfo.add(changelogTopicInfo);
-        }
-        changelogTopicsInfo.sort(Comparator.comparing(StreamsGroupInitializeRequestData.TopicInfo::name));
-        return changelogTopicsInfo;
-    }
-
-    private void onResponse(final ClientResponse response, final Throwable exception) {
-        if (exception != null) {
-            // todo: handle error
-            logger.error("Error during Streams initialization: ", exception);
-        } else {
-            onResponse((StreamsGroupInitializeResponse) response.responseBody());
-        }
-    }
-
-    private void onResponse(final StreamsGroupInitializeResponse response) {
-        if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
-            onSuccessResponse(response);
-        } else {
-            onErrorResponse(response);
-        }
-    }
-
-    private void onErrorResponse(final StreamsGroupInitializeResponse response) {
-        // todo: handle error
-        logger.error("Error during Streams initialization: {}", response);
-    }
-
-    private void onSuccessResponse(final StreamsGroupInitializeResponse response) {
-        // todo: handle success
-        logger.info("Streams initialization successful {}", response);
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index 345b9b808a8..35e225b8956 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -131,7 +131,6 @@ public enum ApiKeys {
     WRITE_SHARE_GROUP_STATE(ApiMessageType.WRITE_SHARE_GROUP_STATE, true),
     DELETE_SHARE_GROUP_STATE(ApiMessageType.DELETE_SHARE_GROUP_STATE, true),
     READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
-    STREAMS_GROUP_INITIALIZE(ApiMessageType.STREAMS_GROUP_INITIALIZE),
     STREAMS_GROUP_HEARTBEAT(ApiMessageType.STREAMS_GROUP_HEARTBEAT),
     STREAMS_GROUP_DESCRIBE(ApiMessageType.STREAMS_GROUP_DESCRIBE);
     
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
index 4e5d21251f8..c16c71903d6 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
@@ -352,8 +352,6 @@ public abstract class AbstractRequest implements AbstractRequestResponse {
                 return ReadShareGroupStateSummaryRequest.parse(buffer, apiVersion);
             case STREAMS_GROUP_HEARTBEAT:
                 return StreamsGroupHeartbeatRequest.parse(buffer, apiVersion);
-            case STREAMS_GROUP_INITIALIZE:
-                return StreamsGroupInitializeRequest.parse(buffer, apiVersion);
             case STREAMS_GROUP_DESCRIBE:
                 return StreamsGroupDescribeRequest.parse(buffer, apiVersion);
             default:
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
index 25f3afe0d5b..8f7b12d4fa4 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
@@ -289,8 +289,6 @@ public abstract class AbstractResponse implements AbstractRequestResponse {
                 return ReadShareGroupStateSummaryResponse.parse(responseBuffer, version);
             case STREAMS_GROUP_HEARTBEAT:
                 return StreamsGroupHeartbeatResponse.parse(responseBuffer, version);
-            case STREAMS_GROUP_INITIALIZE:
-                return StreamsGroupInitializeResponse.parse(responseBuffer, version);
             case STREAMS_GROUP_DESCRIBE:
                 return StreamsGroupDescribeResponse.parse(responseBuffer, version);
             default:
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
index 2785bef35f7..153a2257f18 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
@@ -38,6 +38,7 @@ import java.util.Map;
  * - {@link Errors#UNSUPPORTED_ASSIGNOR}
  * - {@link Errors#UNRELEASED_INSTANCE_ID}
  * - {@link Errors#GROUP_MAX_SIZE_REACHED}
+ * - {@link Errors#STREAMS_INVALID_TOPOLOGY}
  * - {@link Errors#STREAMS_SHUTDOWN_APPLICATION}
  * - {@link Errors#STREAMS_INCONSISTENT_TOPOLOGY}
  * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java
deleted file mode 100644
index bebcf103cf9..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-
-public class StreamsGroupInitializeRequest extends AbstractRequest {
-
-    public static class Builder extends AbstractRequest.Builder<StreamsGroupInitializeRequest> {
-        private final StreamsGroupInitializeRequestData data;
-
-        public Builder(StreamsGroupInitializeRequestData data) {
-            this(data, false);
-        }
-
-        public Builder(StreamsGroupInitializeRequestData data, boolean enableUnstableLastVersion) {
-            super(ApiKeys.STREAMS_GROUP_INITIALIZE, enableUnstableLastVersion);
-            this.data = data;
-        }
-
-        @Override
-        public StreamsGroupInitializeRequest build(short version) {
-            return new StreamsGroupInitializeRequest(data, version);
-        }
-
-        @Override
-        public String toString() {
-            return data.toString();
-        }
-    }
-
-    private final StreamsGroupInitializeRequestData data;
-
-    public StreamsGroupInitializeRequest(StreamsGroupInitializeRequestData data, short version) {
-        super(ApiKeys.STREAMS_GROUP_INITIALIZE, version);
-        this.data = data;
-    }
-
-    @Override
-    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
-        return new StreamsGroupInitializeResponse(
-            new StreamsGroupInitializeResponseData()
-                .setThrottleTimeMs(throttleTimeMs)
-                .setErrorCode(Errors.forException(e).code())
-        );
-    }
-
-    @Override
-    public StreamsGroupInitializeRequestData data() {
-        return data;
-    }
-
-    public static StreamsGroupInitializeRequest parse(ByteBuffer buffer, short version) {
-        return new StreamsGroupInitializeRequest(new StreamsGroupInitializeRequestData(
-            new ByteBufferAccessor(buffer), version), version);
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java
deleted file mode 100644
index cb224b3c6d7..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-import java.util.Collections;
-import java.util.Map;
-
-/**
- * Possible error codes.
- *
- * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
- * - {@link Errors#NOT_COORDINATOR}
- * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
- * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
- * - {@link Errors#INVALID_REQUEST}
- * - {@link Errors#STREAMS_INVALID_TOPOLOGY}
- */
-public class StreamsGroupInitializeResponse extends AbstractResponse {
-
-    private final StreamsGroupInitializeResponseData data;
-
-    public StreamsGroupInitializeResponse(StreamsGroupInitializeResponseData data) {
-        super(ApiKeys.STREAMS_GROUP_INITIALIZE);
-        this.data = data;
-    }
-
-    @Override
-    public StreamsGroupInitializeResponseData data() {
-        return data;
-    }
-
-    @Override
-    public Map<Errors, Integer> errorCounts() {
-        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
-    }
-
-    @Override
-    public int throttleTimeMs() {
-        return data.throttleTimeMs();
-    }
-
-    @Override
-    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
-        data.setThrottleTimeMs(throttleTimeMs);
-    }
-
-    public static StreamsGroupInitializeResponse parse(ByteBuffer buffer, short version) {
-        return new StreamsGroupInitializeResponse(new StreamsGroupInitializeResponseData(
-            new ByteBufferAccessor(buffer), version));
-    }
-}
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
index b7047141e8a..722ac7fc053 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 90,
+  "apiKey": 89,
   "type": "request",
   "listeners": ["broker", "zkBroker"],
   "name": "StreamsGroupDescribeRequest",
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index 71d74eee831..36526b241db 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 90,
+  "apiKey": 89,
   "type": "response",
   "name": "StreamsGroupDescribeResponse",
   "validVersions": "0",
@@ -46,7 +46,7 @@
         { "name": "AssignmentEpoch", "type": "int32", "versions": "0+",
           "about": "The assignment epoch." },
         { "name":  "Topology", "type": "[]Subtopology", "versions": "0+", "nullableVersions": "0+", "default": "null",
-          "about": "The sub-topologies of the streams application. Null if uninitialized.",
+          "about": "The resolved sub-topologies of the streams application. This contains the configured sub-topologies, where the number of partitions are set and any regular expressions are resolved to actual topics. Null if the group is uninitialized, source topics are missing or inconsistent.",
           "fields": [
             { "name": "SubtopologyId", "type": "string", "versions": "0+",
               "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
@@ -54,8 +54,6 @@
               "about": "The topics the topology reads from." },
             { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
               "about": "The repartition topics the topology writes to." },
-            { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
-              "about": "Regular expressions identifying topics the subtopology reads from." },
             { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
               "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
             { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
index ec28c2766fb..d4ae5df26c2 100644
--- a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 89,
+  "apiKey": 88,
   "type": "request",
   "listeners": ["broker", "zkBroker"],
   "name": "StreamsGroupHeartbeatRequest",
@@ -24,18 +24,44 @@
     { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
       "about": "The group identifier." },
     { "name": "MemberId", "type": "string", "versions": "0+",
-      "about": "The member id generated by the coordinator. The member id must be kept during the entire lifetime of the member." },
+      "about": "The member ID generated by the coordinator. The member ID must be kept during the entire lifetime of the member." },
     { "name": "MemberEpoch", "type": "int32", "versions": "0+",
       "about": "The current member epoch; 0 to join the group; -1 to leave the group; -2 to indicate that the static member will rejoin." },
     { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "null if not provided or if it didn't change since the last heartbeat; the instance Id otherwise." },
+      "about": "null if not provided or if it didn't change since the last heartbeat; the instance ID for static membership otherwise." },
     { "name": "RackId", "type": "string", "versions": "0+",  "nullableVersions": "0+", "default": "null",
       "about": "null if not provided or if it didn't change since the last heartbeat; the rack ID of consumer otherwise." },
     { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
       "about": "-1 if it didn't change since the last heartbeat; the maximum time in milliseconds that the coordinator will wait on the member to revoke its partitions otherwise." },
 
-    { "name": "TopologyId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
-      "about": "The ID of the topology. Only sent when memberEpoch = 0, must be non-empty. Null otherwise. Used to check if topology corresponds to server-topology. " },
+    { "name": "TopologyId", "type": "string", "versions": "0+",
+      "about": "The ID of the topology. Used to check if the topology corresponds to the topology initialized on the brokers." },
+    { "name": "Topology", "type": "[]Subtopology", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The topology data of the streams application. Used to initialize the topology of the group. Can only sent when memberEpoch = 0, must then be non-empty. Null otherwise.",
+      "fields": [
+        { "name": "SubtopologyId", "type": "string", "versions": "0+",
+          "about": "String to uniquely identify the sub-topology. Deterministically generated from the topology" },
+        { "name": "SourceTopics", "type": "[]string", "versions": "0+",
+          "about": "The topics the topology reads from." },
+        { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
+          "about": "The regular expressions identifying topics the sub-topology reads from." },
+        { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
+          "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
+        { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
+          "about": "The repartition topics the sub-topology writes to." },
+        { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
+          "about": "The set of source topics that are internally created repartition topics. Created automatically." },
+        { "name": "CopartitionGroups", "type": "[]CopartitionGroup", "versions": "0+",
+          "about": "A subset of source topics that must be copartitioned.",
+          "fields": [
+            { "name": "SourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The topics the topology reads from. Index into the array on the subtopology level." },
+            { "name": "SourceTopicRegex", "type": "[]int16", "versions": "0+",
+              "about": "Regular expressions identifying topics the subtopology reads from. Index into the array on the subtopology level." },
+            { "name": "RepartitionSourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The set of source topics that are internally created repartition topics. Index into the array on the subtopology level." }
+          ]}
+      ]},
 
     { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Currently owned active tasks for this client. Null if unchanged since last heartbeat." },
@@ -52,25 +78,36 @@
       "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
 
     { "name": "TaskOffsets", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Cumulative offsets for tasks. Only updated when a warm up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
+      "about": "Cumulative changelog offsets for tasks. Only updated when a warm-up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
     { "name": "TaskEndOffsets", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Cumulative end-offsets for tasks. Only updated when a warm up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
+      "about": "Cumulative changelog end-offsets for tasks. Only updated when a warm-up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
     { "name": "ShutdownApplication", "type": "bool", "versions": "0+", "default": false,
-      "about": "Whether all Streams clients in the group should shut down. Can only be defined if memberEpoch = -1" }
+      "about": "Whether all Streams clients in the group should shut down." }
   ],
   "commonStructs": [
-    { "name": "Endpoint", "versions": "0+", "fields": [
-      { "name": "Host", "type": "string", "versions": "0+",
-        "about": "host of the endpoint" },
-      { "name": "Port", "type": "uint16", "versions": "0+",
-        "about": "port of the endpoint" }
-    ]},
     { "name": "KeyValue", "versions": "0+", "fields": [
       { "name": "Key", "type": "string", "versions": "0+",
         "about": "key of the config" },
       { "name": "Value", "type": "string", "versions": "0+",
         "about": "value of the config" }
     ]},
+    { "name": "TopicInfo", "versions": "0+", "fields": [
+      { "name": "Name", "type": "string", "versions": "0+",
+        "about": "The name of the topic." },
+      { "name": "Partitions", "type": "int32", "versions": "0+",
+        "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
+      { "name": "ReplicationFactor", "type": "int16", "versions": "0+",
+        "about": "The replication factor of the topic. Can be 0 if the default replication factor should be used." },
+      { "name": "TopicConfigs", "type": "[]KeyValue", "versions": "0+",
+        "about": "Topic-level configurations as key-value pairs."
+      }
+    ]},
+    { "name": "Endpoint", "versions": "0+", "fields": [
+      { "name": "Host", "type": "string", "versions": "0+",
+        "about": "host of the endpoint" },
+      { "name": "Port", "type": "int32", "versions": "0+",
+        "about": "port of the endpoint" }
+    ]},
     { "name": "TaskOffset", "versions": "0+", "fields": [
       { "name": "SubtopologyId", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
index 40e134dc407..7b254a17de6 100644
--- a/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
@@ -14,13 +14,14 @@
 // limitations under the License.
 
 {
-  "apiKey": 89,
+  "apiKey": 88,
   "type": "response",
   "name": "StreamsGroupHeartbeatResponse",
   "validVersions": "0",
   "flexibleVersions": "0+",
   // Supported errors:
   // - GROUP_AUTHORIZATION_FAILED (version 0+)
+  // - GROUP_ID_NOT_FOUND (version 0+)
   // - NOT_COORDINATOR (version 0+)
   // - COORDINATOR_NOT_AVAILABLE (version 0+)
   // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
@@ -29,6 +30,11 @@
   // - FENCED_MEMBER_EPOCH (version 0+)
   // - UNRELEASED_INSTANCE_ID (version 0+)
   // - GROUP_MAX_SIZE_REACHED (version 0+)
+  // - TOPIC_AUTHORIZATION_FAILED (version 0+)
+  // - CLUSTER_AUTHORIZATION_FAILED (version 0+)
+  // - STREAMS_INVALID_TOPOLOGY (version 0+)
+  // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
+  // - STREAMS_INCONSISTENT_INTERNAL_TOPICS (version 0+)
   "fields": [
     // Same as consumer group heart beat
     { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
@@ -46,13 +52,12 @@
     { "name": "AcceptableRecoveryLag", "type": "int32", "versions": "0+",
       "about": "The maximal lag a warm-up task can have to be considered caught-up." },
     { "name": "TaskOffsetIntervalMs", "type": "int32", "versions": "0+",
-      "about": "The interval in which the changelog task offsets on a client are updated on the broker. The offsets are sent with the next heartbeat after this time has passed." },
+      "about": "The interval in which the task changelog offsets on a client are updated on the broker. The offsets are sent with the next heartbeat after this time has passed." },
 
     // Topology updating
-    { "name": "ShouldInitializeTopology", "type":  "bool", "versions":  "0+", "default": false,
-      "about": "true if this streams application should initialize the topology on the broker" },
     { "name": "GroupTopologyId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
-      "about": "The current ID of the topology for the group. Null if unchanged since last heartbeat, empty if group is unitialized." },
+      "about": "The current ID of the topology for the group. Null if unchanged since last heartbeat." },
+
 
     { "name": "Status", "type":  "[]Status", "versions":  "0+",  "nullableVersions": "0+", "default": "null",
       "about": "Indicate zero or more status for the group.  Null if unchanged since last heartbeat." },
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
deleted file mode 100644
index aa68fde6bf5..00000000000
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
+++ /dev/null
@@ -1,77 +0,0 @@
-// 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.
-
-{
-  "apiKey": 88,
-  "type": "request",
-  "listeners": ["broker", "zkBroker"],
-  "name": "StreamsGroupInitializeRequest",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  "fields": [
-    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
-      "about": "The group identifier." },
-    { "name": "TopologyId", "type": "string", "versions": "0+",
-      "about": "The ID of the topology." },
-    { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
-      "about": "The sub-topologies of the streams application.",
-      "fields": [
-        { "name": "SubtopologyId", "type": "string", "versions": "0+",
-          "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
-        { "name": "SourceTopics", "type": "[]string", "versions": "0+",
-          "about": "The topics the topology reads from." },
-        { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
-          "about": "Regular expressions identifying topics the subtopology reads from." },
-        { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
-        { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
-          "about": "The repartition topics the subtopology writes to." },
-        { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of source topics that are internally created repartition topics. Created automatically." },
-        { "name": "CopartitionGroups", "type": "[]CopartitionGroup", "versions": "0+",
-          "about": "A subset of source topics that must be copartitioned.",
-          "fields": [
-            { "name": "SourceTopics", "type": "[]int16", "versions": "0+",
-              "about": "The topics the topology reads from. Index into the array on the subtopology level." },
-            { "name": "SourceTopicRegex", "type": "[]int16", "versions": "0+",
-              "about": "Regular expressions identifying topics the subtopology reads from. Index into the array on the subtopology level." },
-            { "name": "RepartitionSourceTopics", "type": "[]int16", "versions": "0+",
-              "about": "The set of source topics that are internally created repartition topics. Index into the array on the subtopology level." }
-          ]
-        }
-      ]
-    }
-  ],
-  "commonStructs": [
-    { "name": "TopicConfig", "versions": "0+", "fields": [
-        { "name": "key", "type": "string", "versions": "0+",
-          "about": "The key of the topic-level configuration." },
-        { "name": "value", "type": "string", "versions": "0+",
-          "about": "The value of the topic-level configuration," }
-      ]
-    },
-    { "name": "TopicInfo", "versions": "0+", "fields": [
-      { "name": "Name", "type": "string", "versions": "0+",
-        "about": "The name of the topic." },
-      { "name": "Partitions", "type": "int32", "versions": "0+",
-        "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
-      { "name": "ReplicationFactor", "type": "int16", "versions": "0+",
-        "about": "The replication factor of the topic. Can be 0 if the default replication factor should be used." },
-      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+",
-        "about": "Topic-level configurations as key-value pairs."
-      }
-    ]}
-  ]
-}
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json b/clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json
deleted file mode 100644
index 327548577ea..00000000000
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json
+++ /dev/null
@@ -1,42 +0,0 @@
-// 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.
-
-{
-  "apiKey": 88,
-  "type": "response",
-  "name": "StreamsGroupInitializeResponse",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  // Supported errors:
-  // - GROUP_AUTHORIZATION_FAILED (version 0+)
-  // - GROUP_ID_NOT_FOUND (version 0+)
-  // - NOT_COORDINATOR (version 0+)
-  // - COORDINATOR_NOT_AVAILABLE (version 0+)
-  // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
-  // - INVALID_REQUEST (version 0+)
-  // - TOPIC_AUTHORIZATION_FAILED (version 0+)
-  // - CLUSTER_AUTHORIZATION_FAILED (version 0+)
-  // - STREAMS_INVALID_TOPOLOGY (version 0+)
-  // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
-  // - STREAMS_INCONSISTENT_INTERNAL_TOPICS (version 0+)
-  "fields": [
-    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
-      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
-    { "name": "ErrorCode", "type": "int16", "versions": "0+",
-      "about": "The top-level error code, or 0 if there was no error" },
-    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "The top-level error message, or null if there was no error." }
-  ]
-}
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index bec93f98f22..9e88e2c7569 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -28,6 +28,7 @@ import org.apache.kafka.common.Node;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.metrics.Sensor;
@@ -48,6 +49,8 @@ import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
@@ -61,7 +64,9 @@ import java.util.stream.Collectors;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
@@ -87,9 +92,6 @@ class StreamsGroupHeartbeatRequestManagerTest {
     @Mock
     private CoordinatorRequestManager coordinatorRequestManager;
 
-    @Mock
-    private StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager;
-
     @Mock
     private ConsumerMembershipManager membershipManager;
 
@@ -136,7 +138,6 @@ class StreamsGroupHeartbeatRequestManagerTest {
             time,
             config,
             coordinatorRequestManager,
-            streamsGroupInitializeRequestManager,
             membershipManager,
             backgroundEventHandler,
             metrics,
@@ -188,16 +189,44 @@ class StreamsGroupHeartbeatRequestManagerTest {
         assertEquals(TEST_MEMBER_ID, request.data().memberId());
         assertEquals(TEST_MEMBER_EPOCH, request.data().memberEpoch());
         assertEquals(TEST_INSTANCE_ID, request.data().instanceId());
+        assertEquals(streamsAssignmentInterface.topologyId(), request.data().topologyId());
 
         // Static information is null
         assertNull(request.data().processId());
         assertNull(request.data().userEndpoint());
         assertNull(request.data().clientTags());
+        assertNull(request.data().topology());
     }
 
     @Test
     void testFullStaticInformationWhenJoining() {
         mockJoiningState();
+
+        final Set<String> sourceTopics = Set.of("sourceTopic1", "sourceTopic2");
+        final Set<String> repartitionSinkTopics = Set.of("repartitionSinkTopic1", "repartitionSinkTopic2", "repartitionSinkTopic3");
+        final Map<String, StreamsAssignmentInterface.TopicInfo> repartitionSourceTopics = mkMap(
+            mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Optional.of((short) 1), Collections.emptyMap())),
+            mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Optional.of((short) 3), Collections.emptyMap()))
+        );
+        final Map<String, StreamsAssignmentInterface.TopicInfo> changelogTopics = mkMap(
+            mkEntry("changelogTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 1), Collections.emptyMap())),
+            mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 2), Collections.emptyMap())),
+            mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 3), Collections.emptyMap()))
+        );
+        final Collection<Set<String>> copartitionGroup = Set.of(
+            Set.of("sourceTopic1", "repartitionTopic2"),
+            Set.of("sourceTopic2", "repartitionTopic1")
+        );
+        final StreamsAssignmentInterface.Subtopology subtopology1 = new StreamsAssignmentInterface.Subtopology(
+            sourceTopics,
+            repartitionSinkTopics,
+            repartitionSourceTopics,
+            changelogTopics,
+            copartitionGroup
+        );
+        final String subtopologyName1 = "subtopology1";
+        subtopologyMap.put(subtopologyName1, subtopology1);
+
         clientTags.put("clientTag1", "value2");
 
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
@@ -213,6 +242,38 @@ class StreamsGroupHeartbeatRequestManagerTest {
         assertEquals(1, request.data().clientTags().size());
         assertEquals("clientTag1", request.data().clientTags().get(0).key());
         assertEquals("value2", request.data().clientTags().get(0).value());
+        assertEquals(streamsAssignmentInterface.topologyId(), request.data().topologyId());
+        assertNotNull(request.data().topology());
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> subtopologies = request.data().topology();
+        assertEquals(1, subtopologies.size());
+        final StreamsGroupHeartbeatRequestData.Subtopology subtopology = subtopologies.get(0);
+        assertEquals(subtopologyName1, subtopology.subtopologyId());
+        assertEquals(Arrays.asList("sourceTopic1", "sourceTopic2"), subtopology.sourceTopics());
+        assertEquals(Arrays.asList("repartitionSinkTopic1", "repartitionSinkTopic2", "repartitionSinkTopic3"), subtopology.repartitionSinkTopics());
+        assertEquals(repartitionSourceTopics.size(), subtopology.repartitionSourceTopics().size());
+        subtopology.repartitionSourceTopics().forEach(topicInfo -> {
+            final StreamsAssignmentInterface.TopicInfo repartitionTopic = repartitionSourceTopics.get(topicInfo.name());
+            assertEquals(repartitionTopic.numPartitions.get(), topicInfo.partitions());
+            assertEquals(repartitionTopic.replicationFactor.get(), topicInfo.replicationFactor());
+        });
+        assertEquals(changelogTopics.size(), subtopology.stateChangelogTopics().size());
+        subtopology.stateChangelogTopics().forEach(topicInfo -> {
+            assertTrue(changelogTopics.containsKey(topicInfo.name()));
+            assertEquals(0, topicInfo.partitions());
+            final StreamsAssignmentInterface.TopicInfo changelogTopic = changelogTopics.get(topicInfo.name());
+            assertEquals(changelogTopic.replicationFactor.get(), topicInfo.replicationFactor());
+        });
+        assertEquals(2, subtopology.copartitionGroups().size());
+        final StreamsGroupHeartbeatRequestData.CopartitionGroup expectedCopartitionGroupData1 =
+            new StreamsGroupHeartbeatRequestData.CopartitionGroup()
+                .setRepartitionSourceTopics(Collections.singletonList((short) 0))
+                .setSourceTopics(Collections.singletonList((short) 1));
+        final StreamsGroupHeartbeatRequestData.CopartitionGroup expectedCopartitionGroupData2 =
+            new StreamsGroupHeartbeatRequestData.CopartitionGroup()
+                .setRepartitionSourceTopics(Collections.singletonList((short) 1))
+                .setSourceTopics(Collections.singletonList((short) 0));
+        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData1));
+        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData2));
     }
 
     @Test
@@ -318,21 +379,6 @@ class StreamsGroupHeartbeatRequestManagerTest {
 
     }
 
-    @Test
-    void testInitializeTopology() {
-        mockJoiningState();
-
-        StreamsGroupHeartbeatResponseData data = new StreamsGroupHeartbeatResponseData()
-            .setErrorCode(Errors.NONE.code())
-            .setThrottleTimeMs(0)
-            .setMemberEpoch(TEST_MEMBER_EPOCH)
-            .setShouldInitializeTopology(true);
-
-        mockResponse(data);
-
-        verify(streamsGroupInitializeRequestManager).initialize();
-    }
-
     private void mockResponse(final StreamsGroupHeartbeatResponseData data) {
 
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
deleted file mode 100644
index 35eeaaf4baf..00000000000
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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 org.apache.kafka.clients.consumer.internals;
-
-import org.apache.kafka.common.Node;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
-import org.apache.kafka.common.utils.LogContext;
-
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
-import org.mockito.junit.jupiter.MockitoExtension;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-
-import static org.apache.kafka.common.utils.Utils.mkEntry;
-import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-@ExtendWith(MockitoExtension.class)
-class StreamsGroupInitializeRequestManagerTest {
-
-    private final String groupId = "groupId";
-    private final LogContext logContext = new LogContext("test");
-
-    @Test
-    public void shouldPollEmptyResult() {
-        final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
-        final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
-        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
-            logContext,
-            groupId,
-            streamsAssignmentInterface,
-            coordinatorRequestManager
-        );
-
-        final NetworkClientDelegate.PollResult pollResult = streamsGroupInitializeRequestManager.poll(0);
-
-        assertEquals(NetworkClientDelegate.PollResult.EMPTY, pollResult);
-    }
-
-    @Test
-    public void shouldPollStreamsGroupInitializeRequest() {
-        final Node node = mock(Node.class);
-        final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
-        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(node));
-        final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
-        final Set<String> sourceTopics = Set.of("sourceTopic1", "sourceTopic2");
-        final Set<String> sinkTopics = Set.of("sinkTopic1", "sinkTopic2", "sinkTopic3");
-        final Map<String, StreamsAssignmentInterface.TopicInfo> repartitionTopics = mkMap(
-            mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Optional.of((short) 1), Collections.emptyMap())),
-            mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Optional.of((short) 3), Collections.emptyMap()))
-        );
-        final Map<String, StreamsAssignmentInterface.TopicInfo> changelogTopics = mkMap(
-            mkEntry("changelogTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 1), Collections.emptyMap())),
-            mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 2), Collections.emptyMap())),
-            mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 3), Collections.emptyMap()))
-        );
-        final Collection<Set<String>> copartitionGroup = Set.of(
-            Set.of("sourceTopic1", "repartitionTopic2"),
-            Set.of("sourceTopic2", "repartitionTopic1")
-        );
-        final StreamsAssignmentInterface.Subtopology subtopology1 = new StreamsAssignmentInterface.Subtopology(
-            sourceTopics,
-            sinkTopics,
-            repartitionTopics,
-            changelogTopics,
-            copartitionGroup
-        );
-        final String subtopologyName1 = "subtopology1";
-        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
-            mkMap(mkEntry(subtopologyName1, subtopology1))
-        );
-        final StreamsGroupInitializeRequestManager streamsGroupInitializeRequestManager = new StreamsGroupInitializeRequestManager(
-            logContext,
-            groupId,
-            streamsAssignmentInterface,
-            coordinatorRequestManager
-        );
-
-        streamsGroupInitializeRequestManager.initialize();
-        final NetworkClientDelegate.PollResult pollResult = streamsGroupInitializeRequestManager.poll(0);
-
-        assertEquals(1, pollResult.unsentRequests.size());
-        final NetworkClientDelegate.UnsentRequest unsentRequest = pollResult.unsentRequests.get(0);
-        assertTrue(unsentRequest.node().isPresent());
-        assertEquals(node, unsentRequest.node().get());
-        assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE, unsentRequest.requestBuilder().apiKey());
-        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = (StreamsGroupInitializeRequest.Builder) unsentRequest.requestBuilder();
-        final StreamsGroupInitializeRequest streamsGroupInitializeRequest = streamsGroupInitializeRequestBuilder.build();
-        final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = streamsGroupInitializeRequest.data();
-        assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE.id, streamsGroupInitializeRequestData.apiKey());
-        assertEquals(groupId, streamsGroupInitializeRequestData.groupId());
-        assertNotNull(streamsGroupInitializeRequestData.topology());
-        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = streamsGroupInitializeRequestData.topology();
-        assertEquals(1, subtopologies.size());
-        final StreamsGroupInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
-        assertEquals(subtopologyName1, subtopology.subtopologyId());
-        assertEquals(Arrays.asList("sourceTopic1", "sourceTopic2"), subtopology.sourceTopics());
-        assertEquals(Arrays.asList("sinkTopic1", "sinkTopic2", "sinkTopic3"), subtopology.repartitionSinkTopics());
-        assertEquals(repartitionTopics.size(), subtopology.repartitionSourceTopics().size());
-        subtopology.repartitionSourceTopics().forEach(topicInfo -> {
-            final StreamsAssignmentInterface.TopicInfo repartitionTopic = repartitionTopics.get(topicInfo.name());
-            assertEquals(repartitionTopic.numPartitions.get(), topicInfo.partitions());
-            assertEquals(repartitionTopic.replicationFactor.get(), topicInfo.replicationFactor());
-        });
-        assertEquals(changelogTopics.size(), subtopology.stateChangelogTopics().size());
-        subtopology.stateChangelogTopics().forEach(topicInfo -> {
-            assertTrue(changelogTopics.containsKey(topicInfo.name()));
-            assertEquals(0, topicInfo.partitions());
-            final StreamsAssignmentInterface.TopicInfo changelogTopic = changelogTopics.get(topicInfo.name());
-            assertEquals(changelogTopic.replicationFactor.get(), topicInfo.replicationFactor());
-        });
-
-        assertEquals(2, subtopology.copartitionGroups().size());
-        final StreamsGroupInitializeRequestData.CopartitionGroup expectedCopartitionGroupData1 =
-            new StreamsGroupInitializeRequestData.CopartitionGroup()
-                .setRepartitionSourceTopics(Collections.singletonList((short) 0))
-                .setSourceTopics(Collections.singletonList((short) 1));
-        final StreamsGroupInitializeRequestData.CopartitionGroup expectedCopartitionGroupData2 =
-            new StreamsGroupInitializeRequestData.CopartitionGroup()
-                .setRepartitionSourceTopics(Collections.singletonList((short) 1))
-                .setSourceTopics(Collections.singletonList((short) 0));
-        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData1));
-        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData2));
-    }
-}
\ No newline at end of file
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
index c56bef00c9f..25e41a88257 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
@@ -96,7 +96,6 @@ public class ApplicationEventProcessorTest {
                 withGroupId ? Optional.of(commitRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(heartbeatRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(membershipManager) : Optional.empty(),
-                Optional.empty(),
                 Optional.empty()
         );
 
diff --git a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
index 1e5a1c4c864..4e07487a222 100644
--- a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
@@ -238,8 +238,6 @@ import org.apache.kafka.common.message.StreamsGroupDescribeRequestData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -1130,7 +1128,6 @@ public class RequestResponseTest {
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateRequest(version);
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryRequest(version);
             case STREAMS_GROUP_HEARTBEAT: return createStreamsGroupHeartbeatRequest(version);
-            case STREAMS_GROUP_INITIALIZE: return createStreamsGroupInitializeRequest(version);
             case STREAMS_GROUP_DESCRIBE: return createStreamsGroupDescribeRequest(version);
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
@@ -1227,7 +1224,6 @@ public class RequestResponseTest {
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateResponse();
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryResponse();
             case STREAMS_GROUP_HEARTBEAT: return createStreamsGroupHeartbeatResponse();
-            case STREAMS_GROUP_INITIALIZE: return createStreamsGroupInitializeResponse();
             case STREAMS_GROUP_DESCRIBE: return createStreamsGroupDescribeResponse();
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
@@ -4033,10 +4029,6 @@ public class RequestResponseTest {
             .setIncludeAuthorizedOperations(false)).build(version);
     }
 
-    private AbstractRequest createStreamsGroupInitializeRequest(final short version) {
-        return new StreamsGroupInitializeRequest.Builder(new StreamsGroupInitializeRequestData()).build(version);
-    }
-
     private AbstractRequest createStreamsGroupHeartbeatRequest(final short version) {
         return new StreamsGroupHeartbeatRequest.Builder(new StreamsGroupHeartbeatRequestData()).build(version);
     }
@@ -4058,10 +4050,6 @@ public class RequestResponseTest {
         return new StreamsGroupDescribeResponse(data);
     }
 
-    private AbstractResponse createStreamsGroupInitializeResponse() {
-        return new StreamsGroupInitializeResponse(new StreamsGroupInitializeResponseData());
-    }
-
     private AbstractResponse createStreamsGroupHeartbeatResponse() {
         return new StreamsGroupHeartbeatResponse(new StreamsGroupHeartbeatResponseData());
     }
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index ed4322fe67a..58b1ac4ddf7 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,15 +18,15 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
 import org.apache.kafka.common.requests.{OffsetCommitRequest, RequestContext, TransactionResult}
 import org.apache.kafka.common.utils.{BufferSupplier, Time}
 import org.apache.kafka.coordinator.group
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult
 import org.apache.kafka.coordinator.group.OffsetAndMetadata
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult
 import org.apache.kafka.image.{MetadataDelta, MetadataImage}
 import org.apache.kafka.server.common.RequestLocal
 import org.apache.kafka.server.util.FutureUtils
@@ -78,19 +78,10 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
-  override def streamsGroupInitialize(
-                                   context: RequestContext,
-                                   request: StreamsGroupInitializeRequestData
-                                 ): CompletableFuture[StreamsGroupInitializeResult] = {
-    FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
-      s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_INITIALIZE.name} API."
-    ))
-  }
-
   override def streamsGroupHeartbeat(
                                  context: RequestContext,
                                  request: StreamsGroupHeartbeatRequestData
-                               ): CompletableFuture[StreamsGroupHeartbeatResponseData] = {
+                               ): CompletableFuture[StreamsGroupHeartbeatResult] = {
     FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
       s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_HEARTBEAT.name} API."
     ))
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 31c5aaeeccf..dc45b3e3233 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -277,7 +277,6 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
         case ApiKeys.STREAMS_GROUP_DESCRIBE => handleStreamsGroupDescribe(request).exceptionally(handleError)
-        case ApiKeys.STREAMS_GROUP_INITIALIZE => handleStreamsGroupInitialize(request).exceptionally(handleError)
         case ApiKeys.STREAMS_GROUP_HEARTBEAT => handleStreamsGroupHeartbeat(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
       }
@@ -3890,103 +3889,87 @@ class KafkaApis(val requestChannel: RequestChannel,
     config.groupCoordinatorRebalanceProtocols.contains(Group.GroupType.STREAMS)
   }
 
-  def handleStreamsGroupInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    // TODO: The unit tests for this method are insufficient. Once we merge initialize with group heartbeat, we have to extend the tests to cover ACLs and internal topic creation
-    val streamsGroupInitializeRequest = request.body[StreamsGroupInitializeRequest]
+  def handleStreamsGroupHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsGroupHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
 
     if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
-      requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
       CompletableFuture.completedFuture[Unit](())
-    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsGroupInitializeRequest.data.groupId)) {
-      requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
+    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsGroupHeartbeatRequest.data.groupId)) {
+      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
       CompletableFuture.completedFuture[Unit](())
     } else {
       val requestContext = request.context
 
-      val internalTopics: Map[String, StreamsGroupInitializeRequestData.TopicInfo] = {
-        streamsGroupInitializeRequest.data().topology().asScala.flatMap(subtopology =>
-          subtopology.repartitionSourceTopics().iterator().asScala ++ subtopology.stateChangelogTopics().iterator().asScala
-        ).map(x => x.name() -> x).toMap
-      }
-
-      val prohibitedInternalTopics = internalTopics.keys.filter(Topic.isInternal)
-      if (prohibitedInternalTopics.nonEmpty) {
-        val errorResponse = new StreamsGroupInitializeResponseData()
-        errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
-        errorResponse.setErrorMessage(f"Use of Kafka internal topics ${prohibitedInternalTopics.mkString(",")} as Kafka Streams internal topics is prohibited.")
-        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
-        return CompletableFuture.completedFuture[Unit](())
-      }
+      if (streamsGroupHeartbeatRequest.data().topology() != null) {
+        val requiredTopics: Seq[String] =
+          streamsGroupHeartbeatRequest.data().topology().iterator().asScala.flatMap(subtopology =>
+            (subtopology.sourceTopics().iterator().asScala:Iterator[String])
+              ++ (subtopology.repartitionSinkTopics().iterator().asScala:Iterator[String])
+              ++ (subtopology.repartitionSourceTopics().iterator().asScala.map(_.name()):Iterator[String])
+              ++ (subtopology.stateChangelogTopics().iterator().asScala.map(_.name()):Iterator[String])
+          ).toSeq
+
+        // While correctness of the heartbeat request is checked inside the group coordinator,
+        // we are checking early that topics in the topology have valid names and are not internal
+        // kafka topics, since we need to pass it to the authorization helper before passing the
+        // request to the group coordinator.
+
+        val prohibitedTopics = requiredTopics.filter(Topic.isInternal)
+        if (prohibitedTopics.nonEmpty) {
+          val errorResponse = new StreamsGroupHeartbeatResponseData()
+          errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
+          errorResponse.setErrorMessage(f"Use of Kafka internal topics ${prohibitedTopics.mkString(",")} in a Kafka Streams topology is prohibited.")
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(errorResponse))
+          return CompletableFuture.completedFuture[Unit](())
+        }
 
-      val invalidTopics = internalTopics.keys.filterNot(Topic.isValid)
-      if (invalidTopics.nonEmpty) {
-        val errorResponse = new StreamsGroupInitializeResponseData()
-        errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
-        errorResponse.setErrorMessage(f"Internal topic names ${invalidTopics.mkString(",")} are not valid topic names.")
-        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
-        return CompletableFuture.completedFuture[Unit](())
-      }
+        val invalidTopics = requiredTopics.filterNot(Topic.isValid)
+        if (invalidTopics.nonEmpty) {
+          val errorResponse = new StreamsGroupHeartbeatResponseData()
+          errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
+          errorResponse.setErrorMessage(f"Topic names ${invalidTopics.mkString(",")} are not valid topic names.")
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(errorResponse))
+          return CompletableFuture.completedFuture[Unit](())
+        }
 
-      // TODO: Once we move initialization to the heartbeat, we should only require these permissions if there are missing internal topics.
-      if(!authHelper.authorize(request.context, CREATE, CLUSTER, CLUSTER_NAME, logIfDenied = false)) {
-        val (_, createTopicUnauthorized) = authHelper.partitionSeqByAuthorized(request.context, CREATE, TOPIC, internalTopics.keys.toSeq)(identity[String])
-        if (createTopicUnauthorized.nonEmpty) {
-          val errorResponse = new StreamsGroupInitializeResponseData()
+        val (_, describeConfigsAuthorized) = authHelper.partitionSeqByAuthorized(request.context, DESCRIBE_CONFIGS, TOPIC, requiredTopics.toSeq)(identity[String])
+        if (describeConfigsAuthorized.nonEmpty) {
+          val errorResponse = new StreamsGroupHeartbeatResponseData()
           errorResponse.setErrorCode(Errors.TOPIC_AUTHORIZATION_FAILED.code)
-          errorResponse.setErrorMessage(f"Unauthorized to CREATE TOPIC ${createTopicUnauthorized.mkString(",")}.")
-          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
+          errorResponse.setErrorMessage(f"Unauthorized to DESCRIBE_CONFIGS on topics ${describeConfigsAuthorized.mkString(",")} are unauthorized.")
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(errorResponse))
           return CompletableFuture.completedFuture[Unit](())
         }
       }
 
-      val (_, describeConfigsAuthorized) = authHelper.partitionSeqByAuthorized(request.context, DESCRIBE_CONFIGS, TOPIC, internalTopics.keys.toSeq)(identity[String])
-      if (describeConfigsAuthorized.nonEmpty) {
-        val errorResponse = new StreamsGroupInitializeResponseData()
-        errorResponse.setErrorCode(Errors.TOPIC_AUTHORIZATION_FAILED.code)
-        errorResponse.setErrorMessage(f"Unauthorized to DESCRIBE_CONFIGS on topics ${describeConfigsAuthorized.mkString(",")} are unauthorized.")
-        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
-        return CompletableFuture.completedFuture[Unit](())
-      }
-
-      groupCoordinator.streamsGroupInitialize(
+      groupCoordinator.streamsGroupHeartbeat(
         request.context,
-        streamsGroupInitializeRequest.data,
+        streamsGroupHeartbeatRequest.data,
       ).handle[Unit] { (response, exception) =>
         if (exception != null) {
-          requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(exception))
+          requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(exception))
         } else {
+          var responseData = response.responseData();
           if (!response.creatableTopics().isEmpty) {
-            // TODO: Once we move this code to the heartbeat, we should indicate which topics are being created. We should also find a way to propagate failures to the client
+
+            if(!authHelper.authorize(request.context, CREATE, CLUSTER, CLUSTER_NAME, logIfDenied = false)) {
+              val (_, createTopicUnauthorized) = authHelper.partitionSeqByAuthorized(request.context, CREATE, TOPIC, response.creatableTopics().keySet().asScala.toSeq)(identity[String])
+              if (createTopicUnauthorized.nonEmpty) {
+                // TODO: Once topic validation is done, this should just add a status to the response
+                val errorResponse = new StreamsGroupHeartbeatResponseData()
+                errorResponse.setErrorCode(Errors.TOPIC_AUTHORIZATION_FAILED.code)
+                errorResponse.setErrorMessage(f"Unauthorized to CREATE on topics ${createTopicUnauthorized.mkString(",")}.")
+                responseData = new StreamsGroupHeartbeatResponse(errorResponse).data();
+              }
+            }
+
             autoTopicCreationManager.createStreamsInternalTopics(response.creatableTopics().asScala, requestContext);
           }
-          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(response.responseData()))
-        }
-      }
-    }
-  }
-
-  def handleStreamsGroupHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    val streamsGroupHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
 
-    if (!isStreamsGroupProtocolEnabled()) {
-      // The API is not supported by the "old" group coordinator (the default). If the
-      // new one is not enabled, we fail directly here.
-      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
-      CompletableFuture.completedFuture[Unit](())
-    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsGroupHeartbeatRequest.data.groupId)) {
-      requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
-      CompletableFuture.completedFuture[Unit](())
-    } else {
-      groupCoordinator.streamsGroupHeartbeat(
-        request.context,
-        streamsGroupHeartbeatRequest.data,
-      ).handle[Unit] { (response, exception) =>
-        if (exception != null) {
-          requestHelper.sendMaybeThrottle(request, streamsGroupHeartbeatRequest.getErrorResponse(exception))
-        } else {
-          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(response))
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(responseData))
         }
       }
     }
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index 68959acc23a..74feeaa7ac2 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -19,7 +19,7 @@ package kafka.coordinator.group
 import kafka.coordinator.group.GroupCoordinatorConcurrencyTest.{JoinGroupCallback, SyncGroupCallback}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
 import org.apache.kafka.common.errors.{InvalidGroupIdException, UnsupportedVersionException}
-import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
+import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol
 import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
 import org.apache.kafka.common.message.OffsetDeleteRequestData.{OffsetDeleteRequestPartition, OffsetDeleteRequestTopic, OffsetDeleteRequestTopicCollection}
@@ -78,22 +78,6 @@ class GroupCoordinatorAdapterTest {
     assertFutureThrows(future, classOf[UnsupportedVersionException])
   }
 
-  @Test
-  def testStreamsGroupInitialize(): Unit = {
-    val groupCoordinator = mock(classOf[GroupCoordinator])
-    val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
-
-    val ctx = makeContext(ApiKeys.STREAMS_GROUP_INITIALIZE, ApiKeys.STREAMS_GROUP_INITIALIZE.latestVersion)
-    val request = new StreamsGroupInitializeRequestData()
-      .setGroupId("group")
-
-    val future = adapter.streamsGroupInitialize(ctx, request)
-
-    assertTrue(future.isDone)
-    assertTrue(future.isCompletedExceptionally)
-    assertFutureThrows(future, classOf[UnsupportedVersionException])
-  }
-
   @Test
   def testStreamsGroupHeartbeat(): Unit = {
     val groupCoordinator = mock(classOf[GroupCoordinator])
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index d31e6fb27e7..d3edc955211 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -78,7 +78,7 @@ import org.apache.kafka.coordinator.group.GroupConfig.{CONSUMER_HEARTBEAT_INTERV
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupConfig
 import org.apache.kafka.coordinator.group.{GroupConfig, GroupCoordinator, GroupCoordinatorConfig}
 import org.apache.kafka.coordinator.group.{GroupCoordinator, GroupCoordinatorConfig}
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult
 import org.apache.kafka.coordinator.share.{ShareCoordinator, ShareCoordinatorConfigTest}
 import org.apache.kafka.coordinator.transaction.TransactionLogConfig
 import org.apache.kafka.metadata.LeaderAndIsr
@@ -11237,17 +11237,17 @@ class KafkaApisTest extends Logging {
   }
 
   @Test
-  def testStreamsGroupInitializeRequest(): Unit = {
+  def testStreamsGroupHeartbeatRequest(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupInitializeResult]()
-    when(groupCoordinator.streamsGroupInitialize(
+    val future = new CompletableFuture[StreamsGroupHeartbeatResult]()
+    when(groupCoordinator.streamsGroupHeartbeat(
       requestChannelRequest.context,
-      streamsGroupInitializeRequest
+      streamsGroupHeartbeatRequest
     )).thenReturn(future)
     kafkaApis = createKafkaApis(
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
@@ -11255,25 +11255,26 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    val streamsGroupInitializeResponse = new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData())
+    val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
+      .setMemberId("member")
 
-    future.complete(streamsGroupInitializeResponse)
-    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
-    assertEquals(streamsGroupInitializeResponse, response.data)
+    future.complete(new StreamsGroupHeartbeatResult(streamsGroupHeartbeatResponse))
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
+    assertEquals(streamsGroupHeartbeatResponse, response.data)
   }
 
   @Test
-  def testStreamsGroupInitializeRequestFutureFailed(): Unit = {
+  def testStreamsGroupHeartbeatRequestFutureFailed(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupInitializeResult]()
-    when(groupCoordinator.streamsGroupInitialize(
+    val future = new CompletableFuture[StreamsGroupHeartbeatResult]()
+    when(groupCoordinator.streamsGroupHeartbeat(
       requestChannelRequest.context,
-      streamsGroupInitializeRequest
+      streamsGroupHeartbeatRequest
     )).thenReturn(future)
     kafkaApis = createKafkaApis(
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
@@ -11282,17 +11283,17 @@ class KafkaApisTest extends Logging {
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
-    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
   }
 
   @Test
-  def testStreamsGroupInitializeRequestAuthorizationFailed(): Unit = {
+  def testStreamsGroupHeartbeatRequestAuthorizationFailed(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val authorizer: Authorizer = mock(classOf[Authorizer])
     when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
@@ -11304,73 +11305,174 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
 
-
   @Test
-  def testStreamsGroupHeartbeatRequest(): Unit = {
+  def testStreamsGroupHeartbeatRequestProtocolDisabled(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
     val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
     val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
-    when(groupCoordinator.streamsGroupHeartbeat(
-      requestChannelRequest.context,
-      streamsGroupHeartbeatRequest
-    )).thenReturn(future)
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,consumer"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
+
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
+    assertEquals(Errors.UNSUPPORTED_VERSION.code, response.data.errorCode)
+  }
+
+  @Test
+  def testStreamsGroupHeartbeatRequestInvalidTopicNames(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group").setTopology(
+      Collections.singletonList(new StreamsGroupHeartbeatRequestData.Subtopology().setSubtopologyId("subtopology")
+        .setSourceTopics(Collections.singletonList("a "))
+        .setRepartitionSinkTopics(Collections.singletonList("b?"))
+        .setRepartitionSourceTopics(Collections.singletonList(new StreamsGroupHeartbeatRequestData.TopicInfo().setName("c!")))
+        .setStateChangelogTopics(Collections.singletonList(new StreamsGroupHeartbeatRequestData.TopicInfo().setName("d/")))
+      )
+    )
+
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
+
     kafkaApis = createKafkaApis(
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
-      .setMemberId("member")
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
+    assertEquals(Errors.STREAMS_INVALID_TOPOLOGY.code, response.data.errorCode)
+    assertEquals("Topic names a ,b?,c!,d/ are not valid topic names.", response.data.errorMessage())
+  }
+
+  @Test
+  def testStreamsGroupHeartbeatRequestInternalTopicNames(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group").setTopology(
+      Collections.singletonList(new StreamsGroupHeartbeatRequestData.Subtopology().setSubtopologyId("subtopology")
+        .setSourceTopics(Collections.singletonList("__consumer_offsets"))
+        .setRepartitionSinkTopics(Collections.singletonList("__transaction_state"))
+        .setRepartitionSourceTopics(Collections.singletonList(new StreamsGroupHeartbeatRequestData.TopicInfo().setName("__share_group_state")))
+      )
+    )
+
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
+
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    future.complete(streamsGroupHeartbeatResponse)
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
-    assertEquals(streamsGroupHeartbeatResponse, response.data)
+    assertEquals(Errors.STREAMS_INVALID_TOPOLOGY.code, response.data.errorCode)
+    assertEquals("Use of Kafka internal topics __consumer_offsets,__transaction_state,__share_group_state in a Kafka Streams topology is prohibited.", response.data.errorMessage())
   }
 
   @Test
-  def testStreamsGroupHeartbeatRequestFutureFailed(): Unit = {
+  def testStreamsGroupHeartbeatRequestMissingDescribeConfigsPermission(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group").setTopology(
+      Collections.singletonList(new StreamsGroupHeartbeatRequestData.Subtopology().setSubtopologyId("subtopology")
+        .setSourceTopics(Collections.singletonList("a"))
+        .setRepartitionSinkTopics(Collections.singletonList("b"))
+        .setRepartitionSourceTopics(Collections.singletonList(new StreamsGroupHeartbeatRequestData.TopicInfo().setName("c")))
+        .setStateChangelogTopics(Collections.singletonList(new StreamsGroupHeartbeatRequestData.TopicInfo().setName("d")))
+      )
+    )
+
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
+
+    val authorizer: Authorizer = mock(classOf[Authorizer])
+    when(authorizer.authorize(any[RequestContext], isNotNull[util.List[Action]])).thenAnswer(invocation => {
+      val actions = invocation.getArgument(1).asInstanceOf[util.List[Action]]
+      actions.asScala.map { action =>
+        if (!action.resourcePattern.name.equals("a") && action.operation() == AclOperation.DESCRIBE_CONFIGS) {
+          AuthorizationResult.DENIED
+        } else {
+          AuthorizationResult.ALLOWED
+        }
+      }.asJava
+    })
+    kafkaApis = createKafkaApis(
+      authorizer = Some(authorizer),
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
+
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
+    assertEquals(Errors.TOPIC_AUTHORIZATION_FAILED.code, response.data.errorCode)
+    assertEquals("Unauthorized to DESCRIBE_CONFIGS on topics b,c,d are unauthorized.", response.data.errorMessage())
+  }
+
+  @Test
+  def testStreamsGroupHeartbeatRequestMissingTopics(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group");
 
     val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
+    val future = new CompletableFuture[StreamsGroupHeartbeatResult]()
     when(groupCoordinator.streamsGroupHeartbeat(
       requestChannelRequest.context,
       streamsGroupHeartbeatRequest
     )).thenReturn(future)
+
     kafkaApis = createKafkaApis(
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
+    val missingTopics = Map("test" -> new CreatableTopic())
+    val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
+      .setMemberId("member")
+
+    future.complete(new StreamsGroupHeartbeatResult(streamsGroupHeartbeatResponse, missingTopics.asJava))
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
-    assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
+    assertEquals(streamsGroupHeartbeatResponse, response.data)
+    verify(autoTopicCreationManager).createStreamsInternalTopics(missingTopics, requestChannelRequest.context)
   }
 
   @Test
-  def testStreamsGroupHeartbeatRequestAuthorizationFailed(): Unit = {
+  def testStreamsGroupHeartbeatRequestMissingTopicsMissingCreateACL(): Unit = {
     metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group");
 
     val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
+    val future = new CompletableFuture[StreamsGroupHeartbeatResult]()
+    when(groupCoordinator.streamsGroupHeartbeat(
+      requestChannelRequest.context,
+      streamsGroupHeartbeatRequest
+    )).thenReturn(future)
+
     val authorizer: Authorizer = mock(classOf[Authorizer])
-    when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
-      .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
+    when(authorizer.authorize(any[RequestContext], isNotNull[util.List[Action]])).thenAnswer(invocation => {
+      val actions = invocation.getArgument(1).asInstanceOf[util.List[Action]]
+      actions.asScala.map { action =>
+        if (action.resourcePattern.name.equals("test") && action.operation() == AclOperation.CREATE && action.resourcePattern().resourceType() == ResourceType.TOPIC) {
+          AuthorizationResult.DENIED
+        } else if (action.operation() == AclOperation.CREATE && action.resourcePattern().resourceType() == ResourceType.CLUSTER) {
+          AuthorizationResult.DENIED
+        } else {
+          AuthorizationResult.ALLOWED
+        }
+      }.asJava
+    })
     kafkaApis = createKafkaApis(
       authorizer = Some(authorizer),
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
@@ -11378,8 +11480,14 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
+    val missingTopics = Map("test" -> new CreatableTopic())
+    val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
+      .setMemberId("member")
+
+    future.complete(new StreamsGroupHeartbeatResult(streamsGroupHeartbeatResponse, missingTopics.asJava))
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
-    assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
+    assertEquals(Errors.TOPIC_AUTHORIZATION_FAILED.code, response.data.errorCode)
+    assertEquals("Unauthorized to CREATE on topics test.", response.data.errorMessage())
   }
 
   @ParameterizedTest
diff --git a/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala b/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
index 154814e35c7..862e0249ba0 100644
--- a/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
+++ b/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
@@ -745,9 +745,6 @@ class RequestQuotaTest extends BaseRequestTest {
         case ApiKeys.STREAMS_GROUP_HEARTBEAT =>
           new StreamsGroupHeartbeatRequest.Builder(new StreamsGroupHeartbeatRequestData(), true)
 
-        case ApiKeys.STREAMS_GROUP_INITIALIZE =>
-          new StreamsGroupInitializeRequest.Builder(new StreamsGroupInitializeRequestData(), true)
-
         case _ =>
           throw new IllegalArgumentException("Unsupported API key " + apiKey)
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index 07d5d7daaee..b5a1cacbdca 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -41,8 +41,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -50,7 +48,7 @@ import org.apache.kafka.common.message.TxnOffsetCommitResponseData;
 import org.apache.kafka.common.requests.RequestContext;
 import org.apache.kafka.common.requests.TransactionResult;
 import org.apache.kafka.common.utils.BufferSupplier;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 
@@ -87,30 +85,16 @@ public interface GroupCoordinator {
         ConsumerGroupHeartbeatRequestData request
     );
 
-    /**
-     * Initialize a Streams Group.
-     *
-     * @param context           The request context.
-     * @param request           The StreamsGroupInitializeRequest data.
-     *
-     * @return  A future yielding the result, which contains the response and all topics to be created.
-     *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
-     */
-    CompletableFuture<StreamsGroupInitializeResult> streamsGroupInitialize(
-        RequestContext context,
-        StreamsGroupInitializeRequestData request
-    );
-
     /**
      * Heartbeat to a Streams Group.
      *
      * @param context           The request context.
      * @param request           The StreamsGroupHeartbeatResponseData data.
      *
-     * @return  A future yielding the response.
+     * @return  A future yielding the response together with internal topics to create.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsGroupHeartbeatResponseData> streamsGroupHeartbeat(
+    CompletableFuture<StreamsGroupHeartbeatResult> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 3f2f4920162..e775a977b6a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -47,8 +47,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -78,7 +76,7 @@ import org.apache.kafka.coordinator.common.runtime.CoordinatorShardBuilderSuppli
 import org.apache.kafka.coordinator.common.runtime.MultiThreadedEventProcessor;
 import org.apache.kafka.coordinator.common.runtime.PartitionWriter;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.record.BrokerCompressionType;
@@ -351,48 +349,18 @@ public class GroupCoordinatorService implements GroupCoordinator {
         ));
     }
 
-    /**
-     * See {@link GroupCoordinator#streamsGroupInitialize(RequestContext, org.apache.kafka.common.message.StreamsGroupInitializeRequestData)}.
-     */
-    @Override
-    public CompletableFuture<StreamsGroupInitializeResult> streamsGroupInitialize(
-        RequestContext context,
-        StreamsGroupInitializeRequestData request
-    ) {
-        if (!isActive.get()) {
-            return CompletableFuture.completedFuture(new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData()
-                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
-            ));
-        }
-
-        return runtime.scheduleWriteOperation(
-            "streams-group-initialize",
-            topicPartitionFor(request.groupId()),
-            Duration.ofMillis(config.offsetCommitTimeoutMs()),
-            coordinator -> coordinator.streamsGroupInitialize(context, request)
-        ).exceptionally(exception -> handleOperationException(
-            "streams-group-initialize",
-            request,
-            exception,
-            (error, message) -> new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData()
-                .setErrorCode(error.code())
-                .setErrorMessage(message)),
-            log
-        ));
-    }
-
     /**
      * See {@link GroupCoordinator#streamsGroupHeartbeat(RequestContext, org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsGroupHeartbeatResponseData> streamsGroupHeartbeat(
+    public CompletableFuture<StreamsGroupHeartbeatResult> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) {
         if (!isActive.get()) {
-            return CompletableFuture.completedFuture(new StreamsGroupHeartbeatResponseData()
+            return CompletableFuture.completedFuture(new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
-            );
+            ));
         }
 
         return runtime.scheduleWriteOperation(
@@ -404,9 +372,12 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-heartbeat",
             request,
             exception,
-            (error, message) -> new StreamsGroupHeartbeatResponseData()
-                .setErrorCode(error.code())
-                .setErrorMessage(message),
+            (error, message) ->
+                new StreamsGroupHeartbeatResult(
+                    new StreamsGroupHeartbeatResponseData()
+                    .setErrorCode(error.code())
+                    .setErrorMessage(message)
+                ),
             log
         ));
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 1e67ca0f882..895a7508696 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -41,8 +41,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -106,13 +104,12 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.coordinator.group.taskassignor.StickyTaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.timeline.SnapshotRegistry;
-
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
@@ -389,32 +386,16 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
         return groupMetadataManager.consumerGroupHeartbeat(context, request);
     }
 
-    /**
-     * Handles a StreamsGroupInitialize request.
-     *
-     * @param context The request context.
-     * @param request The actual StreamsGroupInitialize request.
-     *
-     * @return A Result containing the StreamsGroupInitialize response and
-     *         a list of records to update the state machine.
-     */
-    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
-        RequestContext context,
-        StreamsGroupInitializeRequestData request
-    ) {
-        return groupMetadataManager.streamsGroupInitialize(context, request);
-    }
-
     /**
      * Handles a StreamsGroupHeartbeat request.
      *
      * @param context The request context.
      * @param request The actual StreamsGroupHeartbeat request.
      *
-     * @return A Result containing the StreamsGroupHeartbeat response and
+     * @return A Result containing the StreamsGroupHeartbeat response, a list of internal topics to be created and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 78e433203a4..9b9602d085f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -61,8 +61,6 @@ import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.KeyValue
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskIds;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskOffset;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.protocol.Errors;
@@ -141,11 +139,9 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupAssignmentBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsTopology;
-import org.apache.kafka.coordinator.group.streams.topics.InternalTopicManager;
-import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
@@ -1017,7 +1013,7 @@ public class GroupMetadataManager {
 
         if (group == null || (createIfNotExists && maybeDeleteEmptyClassicGroup(group, records))) {
             log.info("Creating streams group {}", groupId);
-            return new StreamsGroup(snapshotRegistry, groupId, metrics);
+            return new StreamsGroup(logContext, snapshotRegistry, groupId, metrics);
         } else {
             if (group.type() == STREAMS) {
                 return (StreamsGroup) group;
@@ -1163,7 +1159,7 @@ public class GroupMetadataManager {
 
         if (group == null) {
             log.info("Creating persisted streams group {}", groupId);
-            StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, groupId, metrics);
+            StreamsGroup streamsGroup = new StreamsGroup(logContext, snapshotRegistry, groupId, metrics);
             groups.put(groupId, streamsGroup);
             metrics.onStreamsGroupStateTransition(null, streamsGroup.state());
             return streamsGroup;
@@ -1667,27 +1663,6 @@ public class GroupMetadataManager {
             throw new InvalidRequestException("MemberEpoch is invalid.");
         }
     }
-    
-    /**
-     * Validates the request.
-     *
-     * @param request The request to validate.
-     *
-     * @throws InvalidRequestException if the request is not valid.
-     * @throws UnsupportedAssignorException if the assignor is not supported.
-     */
-    private void throwIfStreamsGroupInitializeRequestIsInvalid(
-        StreamsGroupInitializeRequestData request
-    ) throws InvalidRequestException, UnsupportedAssignorException {
-        throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
-
-        if (request.topology().isEmpty()) {
-            throw new InvalidRequestException("There must be at least one subtopology.");
-        }
-
-        // TODO: Check invariants
-    }
-    
 
     /**
     /**
@@ -1728,12 +1703,8 @@ public class GroupMetadataManager {
             throw new InvalidRequestException("MemberEpoch is invalid.");
         }
 
-        // TODO: Check that task assignor exists.
-//        if (request.assignor() != null && !assignors.containsKey(request.assignor())) {
-//            throw new UnsupportedAssignorException("Assignor " + request.assignor()
-//                + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
-//                + ".");
-//        }
+        // TODO: Check supplied topology for invariants
+
     }
 
     /**
@@ -2249,7 +2220,7 @@ public class GroupMetadataManager {
      * @param clientTags
      * @return A Result containing the StreamsGroupHeartbeat response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
+    private CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupHeartbeat(
         String groupId,
         String memberId,
         int memberEpoch,
@@ -2257,6 +2228,7 @@ public class GroupMetadataManager {
         String rackId,
         int rebalanceTimeoutMs,
         final String topologyId,
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> clientTopology,
         String clientId,
         String clientHost,
         List<TaskIds> ownedActiveTasks,
@@ -2340,7 +2312,7 @@ public class GroupMetadataManager {
             .build();
 
         int groupEpoch = group.groupEpoch();
-        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = group.subscriptionMetadata();
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> partitionMetadata = group.partitionMetadata();
 
         boolean bumpGroupEpoch = hasStreamsMemberMetadataChanged(
             groupId,
@@ -2349,18 +2321,40 @@ public class GroupMetadataManager {
             records
         );
 
-        if (bumpGroupEpoch || group.hasMetadataExpired(currentTimeMs)) {
-            // The subscription metadata is updated when the refresh deadline has been reached.
-            subscriptionMetadata = group.computeSubscriptionMetadata(
+        // 2. Initialize/Update the group topology.
+        // TODO: Topology updates will come later
+        if (clientTopology != null && group.topology() == null) {
+
+            log.info("[GroupId {}] Member {} initialized the topology {}", groupId, memberId, topologyId);
+
+            StreamsGroupTopologyValue recordValue = convertToStreamsGroupTopologyRecord(clientTopology);
+
+            records.add(newStreamsGroupTopologyRecord(groupId, recordValue));
+
+            final Map<String, StreamsGroupTopologyValue.Subtopology> subtopologyMap = recordValue.topology().stream()
+                .collect(Collectors.toMap(StreamsGroupTopologyValue.Subtopology::subtopologyId, x -> x));
+            final StreamsTopology topology = new StreamsTopology(topologyId, subtopologyMap);
+
+            group.setTopology(topology);
+
+            bumpGroupEpoch = true;
+        }
+
+        // 3. Configure the partition metadata and create internal topics if needed.
+        if (bumpGroupEpoch || group.hasMetadataExpired(currentTimeMs) || group.configuredTopology() == null || !group.configuredTopology().isReady()) {
+
+            // The partition metadata is updated when the refresh deadline has been reached.
+            partitionMetadata = group.computePartitionMetadata(
                 metadataImage.topics(),
                 metadataImage.cluster()
             );
 
-            if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
+            if (!partitionMetadata.equals(group.partitionMetadata())) {
                 log.info("[GroupId {}] Computed new partition metadata: {}.",
-                    groupId, subscriptionMetadata);
+                    groupId, partitionMetadata);
                 bumpGroupEpoch = true;
-                records.add(newStreamsGroupPartitionMetadataRecord(groupId, subscriptionMetadata));
+                records.add(newStreamsGroupPartitionMetadataRecord(groupId, partitionMetadata));
+                group.setPartitionMetadata(partitionMetadata);
             }
 
             if (bumpGroupEpoch) {
@@ -2383,7 +2377,7 @@ public class GroupMetadataManager {
                 groupEpoch,
                 member,
                 updatedMember,
-                subscriptionMetadata,
+                partitionMetadata,
                 staticMemberReplaced,
                 records
             );
@@ -2408,18 +2402,10 @@ public class GroupMetadataManager {
 
         scheduleStreamsGroupSessionTimeout(groupId, memberId);
 
-        boolean requestTopologyInitialization = false;
-        if (group.topology() == null && !isTopologyInitializationScheduled(groupId, topologyId)) {
-            requestTopologyInitialization = true;
-            scheduleStreamsGroupTopologyInitializationTimeout(groupId, topologyId, memberId, rebalanceTimeoutMs);
-            log.info("Asking member {} at {} to initialize the topology", memberId, clientHost);
-        }
-
         // Prepare the response.
         StreamsGroupHeartbeatResponseData response = new StreamsGroupHeartbeatResponseData()
             .setMemberId(updatedMember.memberId())
             .setMemberEpoch(updatedMember.memberEpoch())
-            .setShouldInitializeTopology(requestTopologyInitialization)
             .setHeartbeatIntervalMs(streamsGroupHeartbeatIntervalMs);
 
         // The assignment is only provided in the following cases:
@@ -2436,7 +2422,14 @@ public class GroupMetadataManager {
             response.setWarmupTasks(createStreamsGroupHeartbeatResponseTaskIds(updatedMember.assignedWarmupTasks()));
         }
 
-        return new CoordinatorResult<>(records, response);
+
+        Map<String, CreatableTopic> internalTopicsToBeCreated = Collections.emptyMap();
+        if (group.configuredTopology() != null) {
+            internalTopicsToBeCreated = group.configuredTopology().internalTopicsToBeCreated();
+            // TODO: Internal topic validation status
+        }
+
+        return new CoordinatorResult<>(records, new StreamsGroupHeartbeatResult(response, internalTopicsToBeCreated));
     }
 
     private List<StreamsGroupHeartbeatResponseData.TaskIds> createStreamsGroupHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
@@ -2658,108 +2651,6 @@ public class GroupMetadataManager {
         return new CoordinatorResult<>(records, response);
     }
 
-
-    /**
-     * Handles the initialization of the topology information on the broker side, that will be reused by all members of the group.
-     *
-     * @param groupId       The group id from the request.
-     * @param topologyId    The topology ID.
-     * @param subtopologies The list of subtopologies.
-     * @return A Result containing the StreamsGroupInitialize response and a list of records to update the state machine.
-     */
-    private CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(String groupId,
-                                                                                                       String topologyId,
-                                                                                                            List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
-        throws ApiException {
-
-        final List<CoordinatorRecord> records = new ArrayList<>();
-
-        log.info("Initializing topology {} for group {} to {}", topologyId, groupId, subtopologies);
-
-        final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, false, records);
-        throwIfNull(group, "group does not exist");
-
-        if (!isTopologyInitializationScheduled(groupId, topologyId)) {
-            log.warn("No topology to initialize for group ID {} and topology ID {} found.", groupId, topologyId);
-            StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
-            return new CoordinatorResult<>(records, new StreamsGroupInitializeResult(response));
-        }
-
-        StreamsGroupTopologyValue recordValue = convertToStreamsGroupTopologyRecord(subtopologies);
-
-        final Map<String, ConfiguredSubtopology> configuredTopics =
-            InternalTopicManager.configureTopics(logContext, recordValue.topology(), metadataImage);
-
-        cancelStreamsGroupTopologyInitializationTimeout(groupId, topologyId);
-
-        records.add(newStreamsGroupTopologyRecord(groupId, recordValue));
-
-        final Map<String, StreamsGroupTopologyValue.Subtopology> subtopologyMap = recordValue.topology().stream()
-            .collect(Collectors.toMap(StreamsGroupTopologyValue.Subtopology::subtopologyId, x -> x));
-        final StreamsTopology topology = new StreamsTopology(topologyId, subtopologyMap);
-
-        final Map<String, CreatableTopic> missingTopics = InternalTopicManager.missingTopics(configuredTopics, metadataImage);
-        // TODO: This needs to be sorted out, once we merge heartbeat and initialization
-        if (missingTopics.isEmpty()) {
-            computeFirstTargetAssignmentAfterTopologyInitialization(group, records, topology);
-        }
-
-        StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
-
-        return new CoordinatorResult<>(records, new StreamsGroupInitializeResult(response, missingTopics));
-
-    }
-
-    // ToDo: verify how much code we can share with Streams heartbeat handler
-    private void computeFirstTargetAssignmentAfterTopologyInitialization(StreamsGroup group,
-                                                                         List<CoordinatorRecord> records,
-                                                                         StreamsTopology topology) {
-        String groupId = group.groupId();
-        final long currentTimeMs = time.milliseconds();
-        int groupEpoch = group.groupEpoch();
-
-        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata =
-            group.computeSubscriptionMetadata(
-                metadataImage.topics(),
-                metadataImage.cluster(),
-                topology
-            );
-        if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
-            log.info("[GroupId {}] Computed new partition metadata: {}.", groupId, subscriptionMetadata);
-            records.add(newStreamsGroupPartitionMetadataRecord(groupId, subscriptionMetadata));
-        }
-        groupEpoch += 1;
-        records.add(newStreamsGroupEpochRecord(groupId, groupEpoch));
-        log.info("[GroupId {}] Bumped streams group epoch to {}.", groupId, groupEpoch);
-        metrics.record(STREAMS_GROUP_REBALANCES_SENSOR_NAME);
-        group.setMetadataRefreshDeadline(currentTimeMs + streamsGroupMetadataRefreshIntervalMs, groupEpoch);
-
-        // TODO: Read the preferred server assignor from the group configuration
-        String preferredServerAssignor = defaultTaskAssignor.name();
-        try {
-            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder assignmentResultBuilder =
-                new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(group.groupId(), groupEpoch, taskAssignors.get(preferredServerAssignor))
-                    .withMembers(group.members())
-                    .withTopology(topology)
-                    .withStaticMembers(group.staticMembers())
-                    .withSubscriptionMetadata(subscriptionMetadata)
-                    .withTargetAssignment(group.targetAssignment());
-            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
-                assignmentResultBuilder
-                    .build();
-
-            log.info("[GroupId {}] Computed a new target assignment for epoch {} with '{}' assignor: {}.",
-                group.groupId(), groupEpoch, preferredServerAssignor, assignmentResult.targetAssignment());
-
-            records.addAll(assignmentResult.records());
-        } catch (PartitionAssignorException ex) {
-            String msg = String.format("Failed to compute a new target assignment for epoch %d: %s",
-                groupEpoch, ex.getMessage());
-            log.error("[GroupId {}] {}.", group.groupId(), msg);
-            throw new UnknownServerException(msg, ex);
-        }
-    }
-
     /**
      * Handle a JoinGroupRequest to a ConsumerGroup.
      *
@@ -3945,7 +3836,7 @@ public class GroupMetadataManager {
                     .withMembers(group.members())
                     .withTopology(group.topology())
                     .withStaticMembers(group.staticMembers())
-                    .withSubscriptionMetadata(subscriptionMetadata)
+                    .withPartitionMetadata(subscriptionMetadata)
                     .withTargetAssignment(group.targetAssignment())
                     .addOrUpdateMember(updatedMember.memberId(), updatedMember);
             org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult assignmentResult;
@@ -4023,7 +3914,7 @@ public class GroupMetadataManager {
      * @return A Result containing the StreamsGroupHeartbeat response and
      *         a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupLeave(
+    private CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupLeave(
         String groupId,
         String instanceId,
         String memberId,
@@ -4037,7 +3928,7 @@ public class GroupMetadataManager {
         if (instanceId == null) {
             StreamsGroupMember member = group.getOrMaybeCreateMember(memberId, false);
             log.info("[GroupId {}] Member {} left the streams group.", groupId, memberId);
-            return streamsGroupFenceMember(group, member, response);
+            return streamsGroupFenceMember(group, member, new StreamsGroupHeartbeatResult(response));
         } else {
             StreamsGroupMember member = group.staticMember(instanceId);
             throwIfStaticMemberIsUnknown(member, instanceId);
@@ -4049,7 +3940,7 @@ public class GroupMetadataManager {
             } else {
                 log.info("[GroupId {}] Static Member {} with instance id {} left the streams group.",
                     group.groupId(), memberId, instanceId);
-                return streamsGroupFenceMember(group, member, response);
+                return streamsGroupFenceMember(group, member, new StreamsGroupHeartbeatResult(response));
             }
         }
     }
@@ -4121,7 +4012,7 @@ public class GroupMetadataManager {
      *
      * @return A CoordinatorResult with a single record signifying that the static member is leaving.
      */
-    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupStaticMemberGroupLeave(
+    private CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupStaticMemberGroupLeave(
         StreamsGroup group,
         StreamsGroupMember member
     ) {
@@ -4133,9 +4024,11 @@ public class GroupMetadataManager {
 
         return new CoordinatorResult<>(
             Collections.singletonList(newStreamsGroupCurrentAssignmentRecord(group.groupId(), leavingStaticMember)),
+            new StreamsGroupHeartbeatResult(
             new StreamsGroupHeartbeatResponseData()
                 .setMemberId(member.memberId())
                 .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH)
+            )
         );
     }
 
@@ -4527,50 +4420,6 @@ public class GroupMetadataManager {
             () -> streamsGroupFenceMemberOperation(groupId, memberId, "the member session expired.")
         );
     }
-    
-    /**
-     * Schedules (or reschedules) the topology initialisation timeout for the member.
-     *
-     * @param groupId                      The group id.
-     * @param topologyId                   The topology id.
-     * @param memberId                     The member id.
-     * @param topologyIntializationTimeout The topology initialization timeout.
-     */
-    private void scheduleStreamsGroupTopologyInitializationTimeout(
-        String groupId,
-        String topologyId,
-        String memberId,
-        int topologyIntializationTimeout
-    ) {
-        timer.schedule(
-            streamsTopologyInitializationTimeoutKey(groupId, topologyId),
-            topologyIntializationTimeout,
-            TimeUnit.MILLISECONDS,
-            true,
-            () -> streamsGroupFenceMemberOperation(groupId, memberId, "the timeout for the topology intialization expired.")
-        );
-    }
-
-    /**
-     * Verifies if the topology initialization timeout is scheduled.
-     *
-     * @param groupId       The group id.
-     * @param topologyId    The topology id.
-     * @return              {@code true} if the topology initialization timeout is scheduled, {@code false} otherwise.
-     */
-    private boolean isTopologyInitializationScheduled(String groupId, String topologyId) {
-        return timer.isScheduled(streamsTopologyInitializationTimeoutKey(groupId, topologyId));
-    }
-
-    /**
-     * Cancels the topology initialization timeout.
-     *
-     * @param groupId       The group id.
-     * @param topologyId     The topology id.
-     */
-    private void cancelStreamsGroupTopologyInitializationTimeout(String groupId, String topologyId) {
-        timer.cancel(streamsTopologyInitializationTimeoutKey(groupId, topologyId));
-    }
 
     /**
      * Cancels the session timeout of the member.
@@ -4889,38 +4738,16 @@ public class GroupMetadataManager {
         }
     }
 
-    /**
-     * Handles a StreamsGroupInitialize request.
-     *
-     * @param context The request context.
-     * @param request The actual StreamsGroupInitialize request.
-     *
-     * @return A Result containing the StreamsGroupInitialize response and
-     *         a list of records to update the state machine.
-     */
-    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
-        RequestContext context,
-        StreamsGroupInitializeRequestData request
-    ) throws ApiException {
-        throwIfStreamsGroupInitializeRequestIsInvalid(request);
-
-        return streamsGroupInitialize(
-            request.groupId(),
-            request.topologyId(),
-            request.topology()
-        );
-    }
-
     /**
      * Handles a StreamsGroupHeartbeat request.
      *
      * @param context The request context.
      * @param request The actual StreamsGroupHeartbeat request.
      *
-     * @return A Result containing the StreamsGroupHeartbeat response and
+     * @return A Result containing the StreamsGroupHeartbeat response, a list of internalt topics to create and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupHeartbeat(
         RequestContext context,
         StreamsGroupHeartbeatRequestData request
     ) throws ApiException {
@@ -4943,6 +4770,7 @@ public class GroupMetadataManager {
                 request.rackId(),
                 request.rebalanceTimeoutMs(),
                 request.topologyId(),
+                request.topology(),
                 context.clientId(),
                 context.clientAddress.toString(),
                 request.activeTasks(),
@@ -4971,18 +4799,16 @@ public class GroupMetadataManager {
     ) {
         String groupId = key.groupId();
         StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, value != null);
-        Set<String> oldSubscribedTopicNames = new HashSet<>(streamsGroup.subscriptionMetadata().keySet());
+        Set<String> oldSubscribedTopicNames;
+        if (streamsGroup.topology() != null) {
+            oldSubscribedTopicNames = streamsGroup.topology().requiredTopics();
+        } else {
+            oldSubscribedTopicNames = Collections.emptySet();
+        }
         if (value != null) {
             StreamsTopology topology = StreamsTopology.fromRecord(value);
             streamsGroup.setTopology(topology);
-            Set<String> newSubscribedTopicNames = new HashSet<>();
-            topology.subtopologies().forEach(
-                (subtopologyId, subtopology) -> {
-                    newSubscribedTopicNames.addAll(subtopology.sourceTopics());
-                    newSubscribedTopicNames.addAll(subtopology.repartitionSourceTopics().stream()
-                        .map(StreamsGroupTopologyValue.TopicInfo::name).collect(Collectors.toSet()));
-                }
-            );
+            Set<String> newSubscribedTopicNames = topology.requiredTopics();
             updateGroupsByTopics(groupId, oldSubscribedTopicNames, newSubscribedTopicNames);
         } else {
             updateGroupsByTopics(groupId, oldSubscribedTopicNames, Collections.emptySet());
@@ -5422,13 +5248,13 @@ public class GroupMetadataManager {
         StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
 
         if (value != null) {
-            Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = new HashMap<>();
+            Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> partitionMetadata = new HashMap<>();
             value.topics().forEach(topicMetadata -> {
-                subscriptionMetadata.put(topicMetadata.topicName(), org.apache.kafka.coordinator.group.streams.TopicMetadata.fromRecord(topicMetadata));
+                partitionMetadata.put(topicMetadata.topicName(), org.apache.kafka.coordinator.group.streams.TopicMetadata.fromRecord(topicMetadata));
             });
-            streamsGroup.setSubscriptionMetadata(subscriptionMetadata);
+            streamsGroup.setPartitionMetadata(partitionMetadata);
         } else {
-            streamsGroup.setSubscriptionMetadata(Collections.emptyMap());
+            streamsGroup.setPartitionMetadata(Collections.emptyMap());
         }
     }
 
@@ -5523,7 +5349,6 @@ public class GroupMetadataManager {
         String memberId = key.memberId();
 
         StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, value != null);
-        Set<String> oldSubscribedTopicNames = new HashSet<>(streamsGroup.subscriptionMetadata().keySet());
 
         if (value != null) {
             StreamsGroupMember oldMember = streamsGroup.getOrMaybeCreateMember(memberId, true);
@@ -5542,10 +5367,6 @@ public class GroupMetadataManager {
             }
             streamsGroup.removeMember(memberId);
         }
-
-        // ToDo: this is probably a no-op for a streams group since the subscribed topics do not change
-        // between group members.
-        updateGroupsByTopics(groupId, oldSubscribedTopicNames, streamsGroup.subscriptionMetadata().keySet());
     }
 
     /**
@@ -5780,6 +5601,9 @@ public class GroupMetadataManager {
             if (group != null && (group.type() == CONSUMER || group.type() == SHARE)) {
                 ((ModernGroup<?>) group).requestMetadataRefresh();
             }
+            if (group != null && (group.type() == STREAMS)) {
+                ((StreamsGroup) group).requestMetadataRefresh();
+            }
         });
     }
 
@@ -5940,10 +5764,6 @@ public class GroupMetadataManager {
         return "rebalance-timeout-" + groupId + "-" + memberId;
     }
 
-    public static String streamsTopologyInitializationTimeoutKey(String groupId, String topologyId) {
-        return "topology-initialization-timeout-" + groupId + "-" + topologyId;
-    }
-
     /**
      * Replays GroupMetadataKey/Value to update the soft state of
      * the classic group.
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
index a2de5ea0d2c..5a28d83a98b 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
@@ -508,8 +508,8 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                 case EMPTY:
                     incrementNumStreamsGroups(StreamsGroupState.EMPTY);
                     break;
-                case INITIALIZING:
-                    incrementNumStreamsGroups(StreamsGroupState.INITIALIZING);
+                case NOT_READY:
+                    incrementNumStreamsGroups(StreamsGroupState.NOT_READY);
                     break;
                 case ASSIGNING:
                     incrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
@@ -533,8 +533,8 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                 case EMPTY:
                     decrementNumStreamsGroups(StreamsGroupState.EMPTY);
                     break;
-                case INITIALIZING:
-                    decrementNumStreamsGroups(StreamsGroupState.INITIALIZING);
+                case NOT_READY:
+                    decrementNumStreamsGroups(StreamsGroupState.NOT_READY);
                     break;
                 case ASSIGNING:
                     decrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 532955f87aa..6e834eb2ba0 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
@@ -105,16 +105,16 @@ public class CoordinatorStreamsRecordHelpers {
     /**
      * Creates a StreamsGroupPartitionMetadata record.
      *
-     * @param groupId                 The streams group id.
-     * @param newSubscriptionMetadata The subscription metadata.
+     * @param groupId              The streams group id.
+     * @param newPartitionMetadata The partition metadata.
      * @return The record.
      */
     public static CoordinatorRecord newStreamsGroupPartitionMetadataRecord(
         String groupId,
-        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newSubscriptionMetadata
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newPartitionMetadata
     ) {
         StreamsGroupPartitionMetadataValue value = new StreamsGroupPartitionMetadataValue();
-        newSubscriptionMetadata.forEach((topicName, topicMetadata) -> {
+        newPartitionMetadata.forEach((topicName, topicMetadata) -> {
             List<StreamsGroupPartitionMetadataValue.PartitionMetadata> partitionMetadata = new ArrayList<>();
             // If the partition rack information map is empty, store an empty list in the record.
             if (!topicMetadata.partitionRacks().isEmpty()) {
@@ -380,7 +380,7 @@ public class CoordinatorStreamsRecordHelpers {
      * @return The record.
      */
     public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
-                                                                  List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
+                                                                  List<StreamsGroupHeartbeatRequestData.Subtopology> subtopologies) {
         return newStreamsGroupTopologyRecord(groupId, convertToStreamsGroupTopologyRecord(subtopologies));
     }
 
@@ -401,12 +401,12 @@ public class CoordinatorStreamsRecordHelpers {
     }
 
     /**
-     * Encodes subtopologies from the initialize RPC to a StreamsTopology record value.
+     * Encodes subtopologies from the Heartbeat RPC to a StreamsTopology record value.
      *
      * @param subtopologies The subtopologies in the new topology.
      * @return The record value.
      */
-    public static StreamsGroupTopologyValue convertToStreamsGroupTopologyRecord(List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
+    public static StreamsGroupTopologyValue convertToStreamsGroupTopologyRecord(List<StreamsGroupHeartbeatRequestData.Subtopology> subtopologies) {
         StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
         subtopologies.forEach(subtopology -> {
             List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics =
@@ -442,7 +442,7 @@ public class CoordinatorStreamsRecordHelpers {
         return value;
     }
 
-    private static StreamsGroupTopologyValue.TopicInfo convertToTopicInfo(StreamsGroupInitializeRequestData.TopicInfo topicInfo) {
+    private static StreamsGroupTopologyValue.TopicInfo convertToTopicInfo(StreamsGroupHeartbeatRequestData.TopicInfo topicInfo) {
         List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
             .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
             .collect(Collectors.toList()) : null;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopology.java
similarity index 50%
copy from group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
copy to group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopology.java
index 408f0bfcbb4..0848576d1e2 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopology.java
@@ -16,53 +16,52 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredInternalTopic;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
 
+import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
-import java.util.Set;
 import java.util.stream.Collectors;
-import java.util.stream.Stream;
 
 /**
- * Immutable topology metadata.
+ * Immutable configured topology metadata.
  */
-public class StreamsTopology {
+public class StreamsConfiguredTopology {
 
     private final String topologyId;
 
-    private final Map<String, Subtopology> subtopologies;
+    private final Map<String, ConfiguredSubtopology> subtopologies;
 
-    public StreamsTopology(final String topologyId,
-                           final Map<String, Subtopology> subtopologies) {
+    private final Map<String, CreatableTopic> internalTopicsToBeCreated;
+
+    public StreamsConfiguredTopology(final String topologyId,
+                                     final Map<String, ConfiguredSubtopology> subtopologies,
+                                     final Map<String, CreatableTopic> internalTopicsToBeCreated
+                                     ) {
         this.topologyId = topologyId;
         this.subtopologies = subtopologies;
+        this.internalTopicsToBeCreated = internalTopicsToBeCreated;
     }
 
     public String topologyId() {
         return topologyId;
     }
 
-    public Map<String, Subtopology> subtopologies() {
+    public Map<String, ConfiguredSubtopology> subtopologies() {
         return subtopologies;
     }
 
-    public Set<String> topicSubscription() {
-        return subtopologies.values().stream()
-            .flatMap(x -> Stream.concat(x.sourceTopics().stream(), x.repartitionSourceTopics().stream().map(
-                TopicInfo::name))).collect(
-                Collectors.toSet());
+    public Map<String, CreatableTopic> internalTopicsToBeCreated() {
+        return internalTopicsToBeCreated;
     }
 
-    public static StreamsTopology fromRecord(StreamsGroupTopologyValue record) {
-        return new StreamsTopology(
-            record.topologyId(),
-            record.topology().stream().collect(Collectors.toMap(Subtopology::subtopologyId, x -> x))
-        );
+    public boolean isReady() {
+        // TODO: Check for internal topics
+        return internalTopicsToBeCreated.isEmpty();
     }
 
     @Override
@@ -73,52 +72,53 @@ public class StreamsTopology {
         if (o == null || getClass() != o.getClass()) {
             return false;
         }
-        final StreamsTopology that = (StreamsTopology) o;
-        return Objects.deepEquals(topologyId, that.topologyId) && Objects.equals(subtopologies, that.subtopologies);
+        final StreamsConfiguredTopology that = (StreamsConfiguredTopology) o;
+        return Objects.equals(topologyId, that.topologyId) && Objects.equals(subtopologies, that.subtopologies)
+            && Objects.equals(internalTopicsToBeCreated, that.internalTopicsToBeCreated);
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(topologyId, subtopologies);
+        return Objects.hash(topologyId, subtopologies, internalTopicsToBeCreated);
     }
 
     @Override
     public String toString() {
-        return "StreamsTopology{" +
-            "topologyId=" + topologyId +
+        return "StreamsConfiguredTopology{" +
+            "topologyId='" + topologyId + '\'' +
             ", subtopologies=" + subtopologies +
+            ", internalTopicsToBeCreated=" + internalTopicsToBeCreated +
             '}';
     }
 
     public List<StreamsGroupDescribeResponseData.Subtopology> asStreamsGroupDescribeTopology() {
-        return subtopologies.values().stream().map(
+        return subtopologies.entrySet().stream().map(
             subtopology -> new StreamsGroupDescribeResponseData.Subtopology()
-                .setSourceTopicRegex(subtopology.sourceTopicRegex())
-                .setSubtopologyId(subtopology.subtopologyId())
-                .setSourceTopics(subtopology.sourceTopics())
-                .setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
+                .setSubtopologyId(subtopology.getKey())
+                .setSourceTopics(subtopology.getValue().sourceTopics().stream().sorted().collect(Collectors.toList()))
+                .setRepartitionSinkTopics(subtopology.getValue().repartitionSinkTopics().stream().sorted().collect(Collectors.toList()))
                 .setRepartitionSourceTopics(
-                    asStreamsGroupDescribeTopicInfo(subtopology.repartitionSourceTopics()))
+                    asStreamsGroupDescribeTopicInfo(subtopology.getValue().repartitionSourceTopics().values()))
                 .setStateChangelogTopics(
-                    asStreamsGroupDescribeTopicInfo(subtopology.stateChangelogTopics()))
+                    asStreamsGroupDescribeTopicInfo(subtopology.getValue().stateChangelogTopics().values()))
         ).collect(Collectors.toList());
     }
 
     private static List<StreamsGroupDescribeResponseData.TopicInfo> asStreamsGroupDescribeTopicInfo(
-        final List<TopicInfo> topicInfos) {
+        final Collection<ConfiguredInternalTopic> topicInfos) {
         return topicInfos.stream().map(x ->
             new StreamsGroupDescribeResponseData.TopicInfo()
                 .setName(x.name())
-                .setPartitions(x.partitions())
-                .setReplicationFactor(x.replicationFactor())
+                .setPartitions(x.numberOfPartitions().orElse(0))
+                .setReplicationFactor(x.replicationFactor().orElse((short) 0))
                 .setTopicConfigs(
                     x.topicConfigs() != null ?
-                        x.topicConfigs().stream().map(
+                        x.topicConfigs().entrySet().stream().map(
                             y -> new StreamsGroupDescribeResponseData.KeyValue()
-                                .setKey(y.key())
-                                .setValue(y.value())
+                                .setKey(y.getKey())
+                                .setValue(y.getValue())
                         ).collect(Collectors.toList()) : null
                 )
-        ).collect(Collectors.toList());
+        ).sorted().collect(Collectors.toList());
     }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index f9891e62953..fac219c5ed4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -22,14 +22,18 @@ import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.StaleMemberEpochException;
 import org.apache.kafka.common.errors.UnknownMemberIdException;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
 import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
+import org.apache.kafka.coordinator.group.streams.topics.InternalTopicManager;
 import org.apache.kafka.image.ClusterImage;
 import org.apache.kafka.image.TopicImage;
 import org.apache.kafka.image.TopicsImage;
@@ -37,6 +41,7 @@ import org.apache.kafka.timeline.SnapshotRegistry;
 import org.apache.kafka.timeline.TimelineHashMap;
 import org.apache.kafka.timeline.TimelineInteger;
 import org.apache.kafka.timeline.TimelineObject;
+import org.slf4j.Logger;
 
 import java.util.Collections;
 import java.util.HashMap;
@@ -51,7 +56,7 @@ import java.util.Set;
 import static java.util.Collections.emptyMap;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.ASSIGNING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.EMPTY;
-import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.INITIALIZING;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.NOT_READY;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.RECONCILING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.STABLE;
 
@@ -62,7 +67,7 @@ public class StreamsGroup implements Group {
 
     public enum StreamsGroupState {
         EMPTY("Empty"),
-        INITIALIZING("Initializing"),
+        NOT_READY("Not Ready"),
         ASSIGNING("Assigning"),
         RECONCILING("Reconciling"),
         STABLE("Stable"),
@@ -74,7 +79,7 @@ public class StreamsGroup implements Group {
 
         StreamsGroupState(String name) {
             this.name = name;
-            this.lowerCaseName = name.toLowerCase(Locale.ROOT);
+            this.lowerCaseName = name.toLowerCase(Locale.ROOT).replace(" ", "_");
         }
 
         @Override
@@ -100,6 +105,9 @@ public class StreamsGroup implements Group {
         }
     }
 
+    private final LogContext logContext;
+    private final Logger log;
+
     /**
      * The snapshot registry.
      */
@@ -116,8 +124,8 @@ public class StreamsGroup implements Group {
     private final TimelineObject<StreamsGroupState> state;
 
     /**
-     * The group epoch. The epoch is incremented whenever the subscriptions are updated and it will trigger the computation of a new
-     * assignment for the group.
+     * The group epoch. The epoch is incremented whenever the topology, topic metadata or the set of members changes and it will trigger
+     * the computation of a new assignment for the group.
      */
     private final TimelineInteger groupEpoch;
 
@@ -134,7 +142,7 @@ public class StreamsGroup implements Group {
     /**
      * The metadata associated with each subscribed topic name.
      */
-    private final TimelineHashMap<String, TopicMetadata> subscribedTopicMetadata;
+    private final TimelineHashMap<String, TopicMetadata> partitionMetadata;
 
     /**
      * The target assignment epoch. An assignment epoch smaller than the group epoch means that a new assignment is required. The assignment
@@ -172,6 +180,11 @@ public class StreamsGroup implements Group {
      */
     private final TimelineObject<Optional<StreamsTopology>> topology;
 
+    /**
+     * The configured topology including resolved regular expressions.
+     */
+    private final TimelineObject<Optional<StreamsConfiguredTopology>> configuredTopology;
+
     /**
      * The metadata refresh deadline. It consists of a timestamp in milliseconds together with the group epoch at the time of setting it.
      * The metadata refresh time is considered as a soft state (read that it is not stored in a timeline data structure). It is like this
@@ -182,17 +195,20 @@ public class StreamsGroup implements Group {
     private DeadlineAndEpoch metadataRefreshDeadline = DeadlineAndEpoch.EMPTY;
 
     public StreamsGroup(
+        LogContext logContext,
         SnapshotRegistry snapshotRegistry,
         String groupId,
         GroupCoordinatorMetricsShard metrics
     ) {
+        this.log = logContext.logger(StreamsGroup.class);
+        this.logContext = logContext;
         this.snapshotRegistry = Objects.requireNonNull(snapshotRegistry);
         this.groupId = Objects.requireNonNull(groupId);
-        this.state = new TimelineObject<>(snapshotRegistry, INITIALIZING);
+        this.state = new TimelineObject<>(snapshotRegistry, EMPTY);
         this.groupEpoch = new TimelineInteger(snapshotRegistry);
         this.members = new TimelineHashMap<>(snapshotRegistry, 0);
         this.staticMembers = new TimelineHashMap<>(snapshotRegistry, 0);
-        this.subscribedTopicMetadata = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.partitionMetadata = new TimelineHashMap<>(snapshotRegistry, 0);
         this.targetAssignmentEpoch = new TimelineInteger(snapshotRegistry);
         this.targetAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
         this.invertedTargetActiveTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
@@ -203,6 +219,7 @@ public class StreamsGroup implements Group {
         this.currentWarmupTaskProcessIds = new TimelineHashMap<>(snapshotRegistry, 0);
         this.metrics = Objects.requireNonNull(metrics);
         this.topology = new TimelineObject<>(snapshotRegistry, Optional.empty());
+        this.configuredTopology = new TimelineObject<>(snapshotRegistry, Optional.empty());
     }
 
     /**
@@ -239,12 +256,17 @@ public class StreamsGroup implements Group {
             .setGroupType(type().toString());
     }
 
+    public StreamsConfiguredTopology configuredTopology() {
+        return configuredTopology.get().orElse(null);
+    }
+
     public StreamsTopology topology() {
         return topology.get().orElse(null);
     }
 
     public void setTopology(StreamsTopology topology) {
         this.topology.set(Optional.of(topology));
+        maybeUpdateConfiguredTopology();
         maybeUpdateGroupState();
     }
 
@@ -657,42 +679,44 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * @return An immutable Map of subscription metadata for each topic that the consumer group is subscribed to.
+     * @return An immutable Map of partition metadata for each topic that the consumer group is subscribed to.
      */
-    public Map<String, TopicMetadata> subscriptionMetadata() {
-        return Collections.unmodifiableMap(subscribedTopicMetadata);
+    public Map<String, TopicMetadata> partitionMetadata() {
+        return Collections.unmodifiableMap(partitionMetadata);
     }
 
     /**
-     * Updates the subscription metadata. This replaces the previous one.
+     * Updates the partition metadata. This replaces the previous one.
      *
-     * @param subscriptionMetadata The new subscription metadata.
+     * @param partitionMetadata The new partition metadata.
      */
-    public void setSubscriptionMetadata(
-        Map<String, TopicMetadata> subscriptionMetadata
+    public void setPartitionMetadata(
+        Map<String, TopicMetadata> partitionMetadata
     ) {
-        this.subscribedTopicMetadata.clear();
-        this.subscribedTopicMetadata.putAll(subscriptionMetadata);
+        this.partitionMetadata.clear();
+        this.partitionMetadata.putAll(partitionMetadata);
+        maybeUpdateConfiguredTopology();
+        maybeUpdateGroupState();
     }
 
     /**
-     * Computes the subscription metadata based on the current subscription info.
+     * Computes the partition metadata based on the current topology and the current topics/cluster image.
      *
      * @param topicsImage          The current metadata for all available topics.
      * @param clusterImage         The current metadata for the Kafka cluster.
-     * @return An immutable map of subscription metadata for each topic that the consumer group is subscribed to.
+     * @return An immutable map of partition metadata for each topic that the streams topology is using (besides non-repartition sink topics)
      */
-    public Map<String, TopicMetadata> computeSubscriptionMetadata(
+    public Map<String, TopicMetadata> computePartitionMetadata(
         TopicsImage topicsImage,
         ClusterImage clusterImage,
         StreamsTopology topology
     ) {
-        Set<String> subscribedTopicNames = topology.topicSubscription();
+        Set<String> requiredTopicNames = topology.requiredTopics();
 
         // Create the topic metadata for each subscribed topic.
-        Map<String, TopicMetadata> newSubscriptionMetadata = new HashMap<>(subscribedTopicNames.size());
+        Map<String, TopicMetadata> newSubscriptionMetadata = new HashMap<>(requiredTopicNames.size());
 
-        subscribedTopicNames.forEach(topicName -> {
+        requiredTopicNames.forEach(topicName -> {
             TopicImage topicImage = topicsImage.getTopic(topicName);
             if (topicImage != null) {
                 Map<Integer, Set<String>> partitionRacks = new HashMap<>();
@@ -723,19 +747,19 @@ public class StreamsGroup implements Group {
     }
 
     /**
-     * Computes the subscription metadata based on the current subscription info.
+     * Computes the partition metadata based on the current topology and the current topics/cluster image.
      *
      * @param topicsImage          The current metadata for all available topics.
      * @param clusterImage         The current metadata for the Kafka cluster.
-     * @return An immutable map of subscription metadata for each topic that the consumer group is subscribed to.
+     * @return An immutable map of partition metadata for each topic that the streams topology is using (besides non-repartition sink topics)
      */
-    public Map<String, TopicMetadata> computeSubscriptionMetadata(
+    public Map<String, TopicMetadata> computePartitionMetadata(
         TopicsImage topicsImage,
         ClusterImage clusterImage
     ) {
         Optional<StreamsTopology> topology = this.topology.get();
         if (topology.isPresent()) {
-            return computeSubscriptionMetadata(topicsImage, clusterImage, topology.get());
+            return computePartitionMetadata(topicsImage, clusterImage, topology.get());
         }
         return Collections.emptyMap();
     }
@@ -846,7 +870,7 @@ public class StreamsGroup implements Group {
      */
     @Override
     public void validateDeleteGroup() throws ApiException {
-        if (state() != StreamsGroupState.EMPTY && state() != StreamsGroupState.INITIALIZING) {
+        if (state() != StreamsGroupState.EMPTY) {
             throw Errors.NON_EMPTY_GROUP.exception();
         }
     }
@@ -920,10 +944,10 @@ public class StreamsGroup implements Group {
     private void maybeUpdateGroupState() {
         StreamsGroupState previousState = state.get();
         StreamsGroupState newState = STABLE;
-        if (topology() == null) {
-            newState = INITIALIZING;
-        } else if (members.isEmpty()) {
+        if (members.isEmpty()) {
             newState = EMPTY;
+        } else if (topology() == null || configuredTopology() == null || !configuredTopology().isReady()) {
+            newState = NOT_READY;
         } else if (groupEpoch.get() > targetAssignmentEpoch.get()) {
             newState = ASSIGNING;
         } else {
@@ -939,6 +963,35 @@ public class StreamsGroup implements Group {
         metrics.onStreamsGroupStateTransition(previousState, newState);
     }
 
+    private void maybeUpdateConfiguredTopology() {
+        if (topology.get().isPresent()) {
+            final StreamsTopology streamsTopology = topology.get().get();
+
+            log.info("[GroupId {}] Attempting to configure the topology {}", groupId, streamsTopology);
+
+            try {
+                final Map<String, ConfiguredSubtopology> configuredTopics =
+                    InternalTopicManager.configureTopics(logContext, streamsTopology.subtopologies().values(), partitionMetadata);
+                final Map<String, CreatableTopic> internalTopicsToBeCreated = InternalTopicManager.missingTopics(
+                    configuredTopics, partitionMetadata);
+                if (internalTopicsToBeCreated.isEmpty()) {
+                    log.info("[GroupId {}] Valid topic configuration found, topology {} is now initialized.", groupId, streamsTopology.topologyId());
+                } else {
+                    log.info("[GroupId {}] Internal topics for topology {} need to be created: {}.", groupId, streamsTopology.topologyId(), internalTopicsToBeCreated.keySet());
+                }
+
+                this.configuredTopology.set(Optional.of(new StreamsConfiguredTopology(streamsTopology.topologyId(), configuredTopics, internalTopicsToBeCreated)));
+            } catch (Exception e) {
+                log.warn("[GroupId {}] Failed to configure internal topics for topology {}.", groupId, streamsTopology.topologyId(), e);
+                this.configuredTopology.set(Optional.empty());
+                // TODO: Set validation error, so it can be propagated to all members.
+            }
+
+        } else {
+            configuredTopology.set(Optional.empty());
+        }
+    }
+
     /**
      * Updates the tasks process IDs based on the old and the new member.
      *
@@ -1145,7 +1198,7 @@ public class StreamsGroup implements Group {
             .setGroupEpoch(groupEpoch.get(committedOffset))
             .setGroupState(state.get(committedOffset).toString())
             .setAssignmentEpoch(targetAssignmentEpoch.get(committedOffset))
-            .setTopology(topology.get(committedOffset).map(StreamsTopology::asStreamsGroupDescribeTopology).orElse(null));
+            .setTopology(configuredTopology.get(committedOffset).map(StreamsConfiguredTopology::asStreamsGroupDescribeTopology).orElse(null));
         members.entrySet(committedOffset).forEach(
             entry -> describedGroup.members().add(
                 entry.getValue().asStreamsGroupDescribeMember(
@@ -1181,7 +1234,7 @@ public class StreamsGroup implements Group {
         );
 
         records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId(), groupEpoch()));
-        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), subscriptionMetadata()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), partitionMetadata()));
 
         members().forEach((__, streamsGroupMember) ->
             records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId(), streamsGroupMember))
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupHeartbeatResult.java
similarity index 76%
rename from group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java
rename to group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupHeartbeatResult.java
index 7a4845993eb..cd4060e183c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupHeartbeatResult.java
@@ -17,28 +17,28 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 
 import java.util.Collections;
 import java.util.Map;
 import java.util.Objects;
 
-public class StreamsGroupInitializeResult {
+public class StreamsGroupHeartbeatResult {
 
-    private final StreamsGroupInitializeResponseData data;
+    private final StreamsGroupHeartbeatResponseData data;
     private final Map<String, CreatableTopic> creatableTopics;
 
-    public StreamsGroupInitializeResult(StreamsGroupInitializeResponseData data, Map<String, CreatableTopic> creatableTopics) {
+    public StreamsGroupHeartbeatResult(StreamsGroupHeartbeatResponseData data, Map<String, CreatableTopic> creatableTopics) {
         this.data = data;
         this.creatableTopics = creatableTopics;
     }
 
-    public StreamsGroupInitializeResult(StreamsGroupInitializeResponseData data) {
+    public StreamsGroupHeartbeatResult(StreamsGroupHeartbeatResponseData data) {
         this.data = data;
         this.creatableTopics = Collections.emptyMap();
     }
 
-    public StreamsGroupInitializeResponseData responseData() {
+    public StreamsGroupHeartbeatResponseData responseData() {
         return data;
     }
 
@@ -54,7 +54,7 @@ public class StreamsGroupInitializeResult {
         if (o == null || getClass() != o.getClass()) {
             return false;
         }
-        final StreamsGroupInitializeResult that = (StreamsGroupInitializeResult) o;
+        final StreamsGroupHeartbeatResult that = (StreamsGroupHeartbeatResult) o;
         return Objects.equals(data, that.data) && Objects.equals(creatableTopics,
             that.creatableTopics);
     }
@@ -66,7 +66,7 @@ public class StreamsGroupInitializeResult {
 
     @Override
     public String toString() {
-        return "StreamsGroupInitializeResult{" +
+        return "StreamsGroupHeartbeatResult{" +
             "data=" + data +
             ", creatableTopics=" + creatableTopics +
             '}';
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 408f0bfcbb4..c40f896713c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -16,12 +16,10 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
 
-import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
@@ -51,11 +49,17 @@ public class StreamsTopology {
         return subtopologies;
     }
 
-    public Set<String> topicSubscription() {
+    public Set<String> requiredTopics() {
         return subtopologies.values().stream()
-            .flatMap(x -> Stream.concat(x.sourceTopics().stream(), x.repartitionSourceTopics().stream().map(
-                TopicInfo::name))).collect(
-                Collectors.toSet());
+            .flatMap(x ->
+                Stream.concat(
+                    Stream.concat(
+                        x.sourceTopics().stream(),
+                        x.repartitionSourceTopics().stream().map(TopicInfo::name)
+                    ),
+                    x.stateChangelogTopics().stream().map(TopicInfo::name)
+                )
+            ).collect(Collectors.toSet());
     }
 
     public static StreamsTopology fromRecord(StreamsGroupTopologyValue record) {
@@ -89,36 +93,4 @@ public class StreamsTopology {
             ", subtopologies=" + subtopologies +
             '}';
     }
-
-    public List<StreamsGroupDescribeResponseData.Subtopology> asStreamsGroupDescribeTopology() {
-        return subtopologies.values().stream().map(
-            subtopology -> new StreamsGroupDescribeResponseData.Subtopology()
-                .setSourceTopicRegex(subtopology.sourceTopicRegex())
-                .setSubtopologyId(subtopology.subtopologyId())
-                .setSourceTopics(subtopology.sourceTopics())
-                .setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
-                .setRepartitionSourceTopics(
-                    asStreamsGroupDescribeTopicInfo(subtopology.repartitionSourceTopics()))
-                .setStateChangelogTopics(
-                    asStreamsGroupDescribeTopicInfo(subtopology.stateChangelogTopics()))
-        ).collect(Collectors.toList());
-    }
-
-    private static List<StreamsGroupDescribeResponseData.TopicInfo> asStreamsGroupDescribeTopicInfo(
-        final List<TopicInfo> topicInfos) {
-        return topicInfos.stream().map(x ->
-            new StreamsGroupDescribeResponseData.TopicInfo()
-                .setName(x.name())
-                .setPartitions(x.partitions())
-                .setReplicationFactor(x.replicationFactor())
-                .setTopicConfigs(
-                    x.topicConfigs() != null ?
-                        x.topicConfigs().stream().map(
-                            y -> new StreamsGroupDescribeResponseData.KeyValue()
-                                .setKey(y.key())
-                                .setValue(y.value())
-                        ).collect(Collectors.toList()) : null
-                )
-        ).collect(Collectors.toList());
-    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index fcb2e99ff55..b0a1d6e1874 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -175,13 +175,13 @@ public class TargetAssignmentBuilder {
     /**
      * Adds the subscription metadata to use.
      *
-     * @param subscriptionMetadata The subscription metadata.
+     * @param partitionMetadata The subscription metadata.
      * @return This object.
      */
-    public TargetAssignmentBuilder withSubscriptionMetadata(
-        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata
+    public TargetAssignmentBuilder withPartitionMetadata(
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> partitionMetadata
     ) {
-        this.subscriptionMetadata = subscriptionMetadata;
+        this.subscriptionMetadata = partitionMetadata;
         return this;
     }
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
index 9485617261f..cc2383fae42 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
@@ -21,16 +21,13 @@ import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCon
 import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfigCollection;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
-import org.apache.kafka.image.MetadataImage;
-import org.apache.kafka.image.TopicImage;
-
+import org.apache.kafka.coordinator.group.streams.TopicMetadata;
 import org.slf4j.Logger;
 
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
@@ -41,7 +38,7 @@ import java.util.stream.Stream;
 public class InternalTopicManager {
 
     public static Map<String, CreatableTopic> missingTopics(Map<String, ConfiguredSubtopology> subtopologyMap,
-                                                            MetadataImage metadataImage) {
+                                                            Map<String, TopicMetadata> topicMetadata) {
 
         final Map<String, CreatableTopic> topicsToCreate = new HashMap<>();
         for (ConfiguredSubtopology subtopology : subtopologyMap.values()) {
@@ -50,29 +47,27 @@ public class InternalTopicManager {
             subtopology.stateChangelogTopics().values()
                 .forEach(x -> topicsToCreate.put(x.name(), toCreatableTopic(x)));
         }
-        // TODO: Validate if existing topics are compatible with the new topics
-        for (String topic : metadataImage.topics().topicsByName().keySet()) {
+        // TODO: Validate if existing topics are compatible with the required topics
+        for (String topic : topicMetadata.keySet()) {
             topicsToCreate.remove(topic);
         }
         return topicsToCreate;
     }
 
-
     public static Map<String, ConfiguredSubtopology> configureTopics(LogContext logContext,
-                                                                     List<StreamsGroupTopologyValue.Subtopology> subtopologyList,
-                                                                     MetadataImage metadataImage) {
-
+                                                                     Collection<StreamsGroupTopologyValue.Subtopology> subtopologies,
+                                                                     Map<String, TopicMetadata> topicMetadata) {
         final Logger log = logContext.logger(InternalTopicManager.class);
 
         final Map<String, ConfiguredSubtopology> configuredSubtopologies =
-            subtopologyList.stream()
+            subtopologies.stream()
                 .collect(Collectors.toMap(
                     StreamsGroupTopologyValue.Subtopology::subtopologyId,
                     InternalTopicManager::fromPersistedSubtopology)
                 );
 
         final Map<String, Collection<Set<String>>> copartitionGroupsBySubtopology =
-            subtopologyList.stream()
+            subtopologies.stream()
                 .collect(Collectors.toMap(
                     StreamsGroupTopologyValue.Subtopology::subtopologyId,
                     InternalTopicManager::copartitionGroupsFromPersistedSubtopology)
@@ -87,7 +82,7 @@ public class InternalTopicManager {
             ).collect(Collectors.toMap(ConfiguredInternalTopic::name, x -> x));
 
         final Function<String, Integer> topicPartitionCountProvider =
-            topic -> getPartitionCount(metadataImage, topic, configuredInternalTopics);
+            topic -> getPartitionCount(topicMetadata, topic, configuredInternalTopics);
 
         configureRepartitionTopics(logContext, configuredSubtopologies, topicPartitionCountProvider);
         enforceCopartitioning(logContext, configuredSubtopologies, copartitionGroupsBySubtopology, topicPartitionCountProvider, log);
@@ -141,18 +136,18 @@ public class InternalTopicManager {
         changelogTopics.setup();
     }
 
-    private static Integer getPartitionCount(MetadataImage metadataImage,
+    private static Integer getPartitionCount(Map<String, TopicMetadata> topicMetadata,
                                              String topic,
                                              Map<String, ConfiguredInternalTopic> configuredInternalTopics) {
-        final TopicImage topicImage = metadataImage.topics().getTopic(topic);
-        if (topicImage == null) {
+        final TopicMetadata metadata = topicMetadata.get(topic);
+        if (metadata == null) {
             if (configuredInternalTopics.containsKey(topic) && configuredInternalTopics.get(topic).numberOfPartitions().isPresent()) {
                 return configuredInternalTopics.get(topic).numberOfPartitions().get();
             } else {
                 return null;
             }
         } else {
-            return topicImage.partitions().size();
+            return metadata.numPartitions();
         }
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index 6ce91186adf..0bc81517647 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -57,8 +57,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -78,7 +76,7 @@ import org.apache.kafka.common.utils.Utils;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRuntime;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.server.record.BrokerCompressionType;
 import org.apache.kafka.server.util.FutureUtils;
 
@@ -267,122 +265,6 @@ public class GroupCoordinatorServiceTest {
         );
     }
 
-    @Test
-    public void testStreamsGroupInitializeWhenNotStarted() throws ExecutionException, InterruptedException {
-        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
-        GroupCoordinatorService service = new GroupCoordinatorService(
-            new LogContext(),
-            createConfig(),
-            runtime,
-            new GroupCoordinatorMetrics(),
-            createConfigManager()
-        );
-
-        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
-            .setGroupId("foo");
-
-        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
-            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
-            request
-        );
-
-        assertEquals(
-            new StreamsGroupInitializeResult(
-                new StreamsGroupInitializeResponseData()
-                    .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())),
-            future.get()
-        );
-    }
-
-    @Test
-    public void testStreamsGroupInitialize() throws ExecutionException, InterruptedException, TimeoutException {
-        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
-        GroupCoordinatorService service = new GroupCoordinatorService(
-            new LogContext(),
-            createConfig(),
-            runtime,
-            new GroupCoordinatorMetrics(),
-            createConfigManager()
-        );
-
-        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
-            .setGroupId("foo");
-
-        service.startup(() -> 1);
-
-        when(runtime.scheduleWriteOperation(
-            ArgumentMatchers.eq("streams-group-initialize"),
-            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
-            ArgumentMatchers.eq(Duration.ofMillis(5000)),
-            ArgumentMatchers.any()
-        )).thenReturn(CompletableFuture.completedFuture(
-            new StreamsGroupInitializeResponseData()
-        ));
-
-        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
-            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
-            request
-        );
-
-        assertEquals(new StreamsGroupInitializeResponseData(), future.get(5, TimeUnit.SECONDS));
-    }
-
-    private static Stream<Arguments> testStreamsGroupInitializeWithExceptionSource() {
-        return Stream.of(
-            Arguments.arguments(new UnknownTopicOrPartitionException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
-            Arguments.arguments(new NotEnoughReplicasException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
-            Arguments.arguments(new org.apache.kafka.common.errors.TimeoutException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
-            Arguments.arguments(new NotLeaderOrFollowerException(), Errors.NOT_COORDINATOR.code(), null),
-            Arguments.arguments(new KafkaStorageException(), Errors.NOT_COORDINATOR.code(), null),
-            Arguments.arguments(new RecordTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
-            Arguments.arguments(new RecordBatchTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
-            Arguments.arguments(new InvalidFetchSizeException(""), Errors.UNKNOWN_SERVER_ERROR.code(), null),
-            Arguments.arguments(new InvalidRequestException("Invalid"), Errors.INVALID_REQUEST.code(), "Invalid"),
-            Arguments.arguments(new StreamsInvalidTopologyException("Invalid"), Errors.STREAMS_INVALID_TOPOLOGY.code(), "Invalid")
-        );
-    }
-
-    @ParameterizedTest
-    @MethodSource("testStreamsGroupInitializeWithExceptionSource")
-    public void testStreamsGroupInitializeWithException(
-        Throwable exception,
-        short expectedErrorCode,
-        String expectedErrorMessage
-    ) throws ExecutionException, InterruptedException, TimeoutException {
-        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
-        GroupCoordinatorService service = new GroupCoordinatorService(
-            new LogContext(),
-            createConfig(),
-            runtime,
-            new GroupCoordinatorMetrics(),
-            createConfigManager()
-        );
-
-        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
-            .setGroupId("foo");
-
-        service.startup(() -> 1);
-
-        when(runtime.scheduleWriteOperation(
-            ArgumentMatchers.eq("streams-group-initialize"),
-            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
-            ArgumentMatchers.eq(Duration.ofMillis(5000)),
-            ArgumentMatchers.any()
-        )).thenReturn(FutureUtils.failedFuture(exception));
-
-        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
-            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
-            request
-        );
-
-        assertEquals(
-            new StreamsGroupInitializeResponseData()
-                .setErrorCode(expectedErrorCode)
-                .setErrorMessage(expectedErrorMessage),
-            future.get(5, TimeUnit.SECONDS).responseData()
-        );
-    }
-
     @Test
     public void testStreamsGroupHeartbeatWhenNotStarted() throws ExecutionException, InterruptedException {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
@@ -397,14 +279,14 @@ public class GroupCoordinatorServiceTest {
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResult> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
         assertEquals(
-            new StreamsGroupHeartbeatResponseData()
-                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
+            new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData()
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())),
             future.get()
         );
     }
@@ -431,15 +313,15 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.eq(Duration.ofMillis(5000)),
             ArgumentMatchers.any()
         )).thenReturn(CompletableFuture.completedFuture(
-            new StreamsGroupHeartbeatResponseData()
+            new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData())
         ));
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResult> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
-        assertEquals(new StreamsGroupHeartbeatResponseData(), future.get(5, TimeUnit.SECONDS));
+        assertEquals(new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData()), future.get(5, TimeUnit.SECONDS));
     }
 
     private static Stream<Arguments> testStreamsGroupHeartbeatWithExceptionSource() {
@@ -452,7 +334,9 @@ public class GroupCoordinatorServiceTest {
             Arguments.arguments(new RecordTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
             Arguments.arguments(new RecordBatchTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
             Arguments.arguments(new InvalidFetchSizeException(""), Errors.UNKNOWN_SERVER_ERROR.code(), null),
-            Arguments.arguments(new InvalidRequestException("Invalid"), Errors.INVALID_REQUEST.code(), "Invalid")
+            Arguments.arguments(new InvalidRequestException("Invalid"), Errors.INVALID_REQUEST.code(), "Invalid"),
+            Arguments.arguments(new StreamsInvalidTopologyException("Invalid"), Errors.STREAMS_INVALID_TOPOLOGY.code(), "Invalid")
+            // TODO: Add other exceptions
         );
     }
 
@@ -484,19 +368,19 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsGroupHeartbeat(
+        CompletableFuture<StreamsGroupHeartbeatResult> future = service.streamsGroupHeartbeat(
             requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
         assertEquals(
-            new StreamsGroupHeartbeatResponseData()
+            new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(expectedErrorCode)
-                .setErrorMessage(expectedErrorMessage),
+                .setErrorMessage(expectedErrorMessage)),
             future.get(5, TimeUnit.SECONDS)
         );
     }
-    
+
     @Test
     public void testPartitionFor() {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
@@ -1920,7 +1804,7 @@ public class GroupCoordinatorServiceTest {
             future.get()
         );
     }
-    
+
     @Test
     public void testDeleteOffsets() throws Exception {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index b836131e667..c828c2b1dcd 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -26,8 +26,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
 import org.apache.kafka.common.message.TxnOffsetCommitResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
@@ -65,7 +63,7 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupMemberMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMemberMetadataValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataValue;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 
@@ -136,38 +134,6 @@ public class GroupCoordinatorShardTest {
         assertEquals(result, coordinator.consumerGroupHeartbeat(context, request));
     }
 
-    @Test
-    public void testStreamsGroupInitialize() {
-        GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
-        OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
-        CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
-        CoordinatorMetricsShard metricsShard = mock(CoordinatorMetricsShard.class);
-        GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
-            new LogContext(),
-            groupMetadataManager,
-            offsetMetadataManager,
-            Time.SYSTEM,
-            new MockCoordinatorTimer<>(Time.SYSTEM),
-            mock(GroupCoordinatorConfig.class),
-            coordinatorMetrics,
-            metricsShard
-        );
-
-        RequestContext context = requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE);
-        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData();
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = new CoordinatorResult<>(
-            Collections.emptyList(),
-            new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData())
-        );
-
-        when(groupMetadataManager.streamsGroupInitialize(
-            context,
-            request
-        )).thenReturn(result);
-
-        assertEquals(result, coordinator.streamsGroupInitialize(context, request));
-    }
-
     @Test
     public void testStreamsGroupHeartbeat() {
         GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
@@ -187,9 +153,9 @@ public class GroupCoordinatorShardTest {
 
         RequestContext context = requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT);
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData();
-        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+        CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> result = new CoordinatorResult<>(
             Collections.emptyList(),
-            new StreamsGroupHeartbeatResponseData()
+            new StreamsGroupHeartbeatResult(new StreamsGroupHeartbeatResponseData())
         );
 
         when(groupMetadataManager.streamsGroupHeartbeat(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index afdbe390021..4cf7f099d26 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -59,9 +59,8 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TopicInfo;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -99,8 +98,9 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil;
 import org.apache.kafka.image.MetadataDelta;
@@ -275,9 +275,7 @@ public class GroupMetadataManagerTest {
 
     @Test
     public void testStreamsRequestValidation() {
-//        TODO MockTaskAssignor assignor = new MockTaskAssignor("range");
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-//            .withAssignors(Collections.singletonList(assignor))
             .build();
         Exception ex;
 
@@ -355,14 +353,7 @@ public class GroupMetadataManagerTest {
                 .setRackId("")));
         assertEquals("RackId can't be empty.", ex.getMessage());
 
-//       TODO: // ServerAssignor must exist if provided in all requests.
-//        ex = assertThrows(UnsupportedAssignorException.class, () -> context.streamsGroupHeartbeat(
-//            new StreamsGroupHeartbeatRequestData()
-//                .setGroupId("foo")
-//                .setMemberId(Uuid.randomUuid().toString())
-//                .setMemberEpoch(1)
-//                .setServerAssignor("bar")));
-//        assertEquals("ServerAssignor bar is not supported. Supported assignors: range.", ex.getMessage());
+        // TODO: Test supplied topology
     }
 
     @Test
@@ -421,28 +412,44 @@ public class GroupMetadataManagerTest {
     }
 
     @Test
-    public void testJoiningNonExistingStreamsGroup() {
+    public void testJoiningNonExistingStreamsGroupNoMissingTopics() {
         String groupId = "group-id";
         int rebalanceTimeoutMs = 300000;
         String topologyId = "topology-id";
         String processId = "process-id";
+        String subtopologyId = "subtopology-id";
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(new MetadataImageBuilder()
+                .addTopic(Uuid.randomUuid(), "input-topic", 3)
+                .addRacks()
+                .build())
+            .withTaskAssignors(Collections.singletonList(assignor))
             .build();
-        StreamsGroupHeartbeatRequestData heartbeat = buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> topology = new ArrayList<>();
+        topology.add(new StreamsGroupHeartbeatRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+            .setStateChangelogTopics(Collections.emptyList())
+        );
+        StreamsGroupHeartbeatRequestData heartbeat =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, topology, processId, rebalanceTimeoutMs);
+        prepareStreamsGroupAssignment(assignor, heartbeat.memberId(), "subtopology-id");
 
-        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
+        CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
 
         assertNotNull(result.response());
-        StreamsGroupHeartbeatResponseData response = result.response();
+        StreamsGroupHeartbeatResponseData response = result.response().responseData();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertFalse(response.memberId().isEmpty());
         assertEquals(1, response.memberEpoch());
-        assertTrue(response.shouldInitializeTopology());
         assertTrue(response.activeTasks().isEmpty());
         assertTrue(response.standbyTasks().isEmpty());
         assertTrue(response.warmupTasks().isEmpty());
         List<CoordinatorRecord> coordinatorRecords = result.records();
-        assertEquals(5, coordinatorRecords.size());
+        assertEquals(7, coordinatorRecords.size());
         assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 1)));
         StreamsGroupMember member = new StreamsGroupMember.Builder(response.memberId())
             .setClientId("client")
@@ -462,6 +469,12 @@ public class GroupMetadataManagerTest {
                 Collections.emptyMap()
             )
         ));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(
+                groupId,
+                topology
+            )
+        ));
         StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
             .withTargetAssignment(
                 1,
@@ -471,40 +484,55 @@ public class GroupMetadataManagerTest {
             .withOwnedStandbyTasks(Collections.emptyList())
             .withOwnedWarmupTasks(Collections.emptyList())
             .build();
-        CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember);
-        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, context.streamsGroupState("group-id"));
-        assertTrue(context.timer.isScheduled("topology-initialization-timeout-group-id-topology-id"));
-        assertEquals(rebalanceTimeoutMs, context.timer.timeout("topology-initialization-timeout-group-id-topology-id").deadlineMs - context.time.milliseconds());
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember)
+        ));
+        assertEquals(StreamsGroup.StreamsGroupState.STABLE, context.streamsGroupState("group-id"));
+
+        final Map<String, CreatableTopic> creatableTopic = result.response().creatableTopics();
+        assertEquals(Collections.emptyMap(), creatableTopic);
     }
 
     @Test
-    public void testJoiningExistingInitializingStreamsGroup() {
+    public void testJoiningNonExistingStreamsGroupMissingTopics() {
         String groupId = "group-id";
         int rebalanceTimeoutMs = 300000;
         String topologyId = "topology-id";
         String processId = "process-id";
+        String subtopologyId = "subtopology-id";
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(new MetadataImageBuilder()
+                .addTopic(Uuid.randomUuid(), "input-topic", 3)
+                .addRacks()
+                .build())
+            .withTaskAssignors(Collections.singletonList(assignor))
             .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> topology = new ArrayList<>();
+        topology.add(new StreamsGroupHeartbeatRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+            .setStateChangelogTopics(Collections.singletonList(new TopicInfo().setName("changelog-topic")))
+        );
         StreamsGroupHeartbeatRequestData heartbeat =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, topology, processId, rebalanceTimeoutMs);
+        prepareStreamsGroupAssignment(assignor, heartbeat.memberId(), "subtopology-id");
 
-        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
+        CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
 
         assertNotNull(result.response());
-        StreamsGroupHeartbeatResponseData response = result.response();
+        StreamsGroupHeartbeatResponseData response = result.response().responseData();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertFalse(response.memberId().isEmpty());
-        assertEquals(2, response.memberEpoch());
-        assertFalse(response.shouldInitializeTopology());
+        assertEquals(1, response.memberEpoch());
         assertTrue(response.activeTasks().isEmpty());
         assertTrue(response.standbyTasks().isEmpty());
         assertTrue(response.warmupTasks().isEmpty());
         List<CoordinatorRecord> coordinatorRecords = result.records();
-        assertEquals(5, coordinatorRecords.size());
-        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
+        assertEquals(7, coordinatorRecords.size());
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 1)));
         StreamsGroupMember member = new StreamsGroupMember.Builder(response.memberId())
             .setClientId("client")
             .setClientHost("localhost/127.0.0.1")
@@ -513,7 +541,7 @@ public class GroupMetadataManagerTest {
             .setProcessId(processId)
             .build();
         assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId, member)));
-        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 2)));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 1)));
         assertTrue(coordinatorRecords.contains(
             CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
                 groupId,
@@ -523,6 +551,12 @@ public class GroupMetadataManagerTest {
                 Collections.emptyMap()
             )
         ));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(
+                groupId,
+                topology
+            )
+        ));
         StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
             .withTargetAssignment(
                 1,
@@ -532,248 +566,43 @@ public class GroupMetadataManagerTest {
             .withOwnedStandbyTasks(Collections.emptyList())
             .withOwnedWarmupTasks(Collections.emptyList())
             .build();
-        CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember);
-        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, context.streamsGroupState("group-id"));
-    }
-
-    @Test
-    public void testInitTopologyExistingInitializingStreamsGroup() {
-        String groupId = "group-id";
-        int rebalanceTimeoutMs = 300000;
-        String topologyId = "topology-id";
-        String processId = "process-id";
-        String inputTopicName = "input-topic";
-        String subtopologyId = "subtopology-id";
-        Uuid inputTopicId = Uuid.randomUuid();
-        MetadataImage metadataImage = new MetadataImageBuilder()
-            .addTopic(inputTopicId, inputTopicName, 3)
-            .addRacks()
-            .build();
-        MockTaskAssignor assignor = new MockTaskAssignor("mock");
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(metadataImage)
-            .withTaskAssignors(Collections.singletonList(assignor))
-            .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
-            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
-        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
-        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
-            .setSubtopologyId(subtopologyId)
-            .setRepartitionSinkTopics(Collections.emptyList())
-            .setRepartitionSourceTopics(Collections.emptyList())
-            .setSourceTopics(Collections.singletonList("input-topic"))
-        );
-        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
-        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
-            .setGroupId(groupId)
-            .setTopologyId(topologyId)
-            .setTopology(subtopologies);
-
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
-
-        assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response().responseData();
-        assertEquals(Errors.NONE.code(), response.errorCode());
-        List<CoordinatorRecord> coordinatorRecords = result.records();
-        assertEquals(5, coordinatorRecords.size());
-        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
-        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(groupId, subtopologies)));
-
-        org.apache.kafka.coordinator.group.streams.TopicMetadata topicMetadata = new org.apache.kafka.coordinator.group.streams.TopicMetadata(
-            inputTopicId,
-            inputTopicName,
-            3,
-            mkMap(
-                mkEntry(0, new HashSet<>(List.of("rack1", "rack0"))),
-                mkEntry(1, new HashSet<>(List.of("rack2", "rack1"))),
-                mkEntry(2, new HashSet<>(List.of("rack2", "rack3")))
-            )
-        );
         assertTrue(coordinatorRecords.contains(
-            CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId, mkMap(mkEntry(inputTopicName, topicMetadata)))
+            CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember)
         ));
-        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 2)));
-        assertTrue(coordinatorRecords.contains(
-            CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
-                groupId,
-                heartbeatResult.response().memberId(),
-                TaskAssignmentTestUtil.mkTasksPerSubtopology(TaskAssignmentTestUtil.mkTasks(subtopologyId, 0, 1, 2)),
-                Collections.emptyMap(),
-                Collections.emptyMap()
-            )
-        ));
-        assertFalse(context.timer.isScheduled("topology-initialization-timeout-group-id-topology-id"));
-        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, context.streamsGroupState("group-id"));
-    }
-
-    @Test
-    public void testInitTopologyWithWrongGroupId() {
-        String groupId = "group-id";
-        int rebalanceTimeoutMs = 300000;
-        String topologyId = "topology-id";
-        String processId = "process-id";
-        String inputTopicName = "input-topic";
-        String subtopologyId = "subtopology-id";
-        Uuid inputTopicId = Uuid.randomUuid();
-        MetadataImage metadataImage = new MetadataImageBuilder()
-            .addTopic(inputTopicId, inputTopicName, 3)
-            .addRacks()
-            .build();
-        MockTaskAssignor assignor = new MockTaskAssignor("mock");
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(metadataImage)
-            .withTaskAssignors(Collections.singletonList(assignor))
-            .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
-            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
-        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
-        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
-            .setSubtopologyId(subtopologyId)
-            .setRepartitionSinkTopics(Collections.emptyList())
-            .setRepartitionSourceTopics(Collections.emptyList())
-            .setSourceTopics(Collections.singletonList("input-topic"))
-        );
-        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
-        final String wrongGroupId = "wrong-" + groupId;
-        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
-            .setGroupId(wrongGroupId)
-            .setTopologyId(topologyId)
-            .setTopology(subtopologies);
-
-        final GroupIdNotFoundException groupIdNotFoundException =
-            assertThrows(GroupIdNotFoundException.class, () -> context.streamsGroupInitialize(initialize));
+        assertEquals(StreamsGroupState.NOT_READY, context.streamsGroupState("group-id"));
 
+        final Map<String, CreatableTopic> creatableTopic = result.response().creatableTopics();
         assertEquals(
-            "Streams group " + wrongGroupId + " not found.",
-            groupIdNotFoundException.getMessage()
+            Map.of("changelog-topic", new CreatableTopic().setName("changelog-topic").setNumPartitions(3).setReplicationFactor((short) -1)),
+            creatableTopic
         );
     }
 
     @Test
-    public void testInitTopologyWithWrongTopologyId() {
+    public void testJoiningExistingNotReadyStreamsGroupMissingTopics() {
         String groupId = "group-id";
         int rebalanceTimeoutMs = 300000;
         String topologyId = "topology-id";
         String processId = "process-id";
-        String inputTopicName = "input-topic";
-        String subtopologyId = "subtopology-id";
-        Uuid inputTopicId = Uuid.randomUuid();
-        MetadataImage metadataImage = new MetadataImageBuilder()
-            .addTopic(inputTopicId, inputTopicName, 3)
-            .addRacks()
-            .build();
-        MockTaskAssignor assignor = new MockTaskAssignor("mock");
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(metadataImage)
-            .withTaskAssignors(Collections.singletonList(assignor))
-            .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
-            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
-        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
-        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
-            .setSubtopologyId(subtopologyId)
-            .setRepartitionSinkTopics(Collections.emptyList())
-            .setRepartitionSourceTopics(Collections.emptyList())
-            .setSourceTopics(Collections.singletonList("input-topic"))
-        );
-        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
-        final String wrongTopologyId = "wrong-" + topologyId;
-        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
-            .setGroupId(groupId)
-            .setTopologyId(wrongTopologyId)
-            .setTopology(subtopologies);
-
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
-
-        assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response().responseData();
-        assertEquals(Errors.NONE.code(), response.errorCode());
-        assertTrue(result.records().isEmpty());
-    }
-
-    @Test
-    public void testInitTopologyForInitializedStreamsGroup() {
-        String groupId = "group-id";
-        int rebalanceTimeoutMs = 300000;
-        String topologyId = "topology-id";
-        String processId = "process-id";
-        String inputTopicName = "input-topic";
-        String subtopologyId = "subtopology-id";
-        Uuid inputTopicId = Uuid.randomUuid();
-        MetadataImage metadataImage = new MetadataImageBuilder()
-            .addTopic(inputTopicId, inputTopicName, 3)
-            .addRacks()
-            .build();
         MockTaskAssignor assignor = new MockTaskAssignor("mock");
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(metadataImage)
-            .withTaskAssignors(Collections.singletonList(assignor))
-            .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
-            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
-        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
-        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
-            .setSubtopologyId(subtopologyId)
-            .setRepartitionSinkTopics(Collections.emptyList())
-            .setRepartitionSourceTopics(Collections.emptyList())
-            .setSourceTopics(Collections.singletonList("input-topic"))
-        );
-        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
-        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
-            .setGroupId(groupId)
-            .setTopologyId(topologyId)
-            .setTopology(subtopologies);
-
-        context.streamsGroupInitialize(initialize);
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
-
-        assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response().responseData();
-        assertEquals(Errors.NONE.code(), response.errorCode());
-        assertTrue(result.records().isEmpty());
-    }
-
-    @Test
-    public void testTopologyInitializationMissingInternalTopics() {
-        String groupId = "group-id";
-        int rebalanceTimeoutMs = 300000;
-        String topologyId = "topology-id";
-        String processId = "process-id";
-        Uuid fooTopicId = Uuid.randomUuid();
-        String fooTopicName = "repartition";
-        Uuid barTopicId = Uuid.randomUuid();
-        String barTopicName = "bar";
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
             .withMetadataImage(new MetadataImageBuilder()
-                .addTopic(fooTopicId, fooTopicName, 4)
-                .addTopic(barTopicId, barTopicName, 4)
+                .addTopic(Uuid.randomUuid(), "bar", 3)
                 .addRacks()
                 .build())
+            .withTaskAssignors(Collections.singletonList(assignor))
             .build();
-        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
-            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
-        context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
-        assertThrows(GroupIdNotFoundException.class, () ->
-            context.groupMetadataManager.consumerGroup(groupId));
-        final List<StreamsGroupInitializeRequestData.Subtopology> topology = Collections.singletonList(
-            new StreamsGroupInitializeRequestData.Subtopology()
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> topology = Collections.singletonList(
+            new StreamsGroupHeartbeatRequestData.Subtopology()
                 .setSubtopologyId("subtopology-id")
                 .setSourceTopics(Collections.singletonList("bar"))
                 .setRepartitionSourceTopics(
                     Collections.singletonList(
-                        new StreamsGroupInitializeRequestData.TopicInfo()
+                        new StreamsGroupHeartbeatRequestData.TopicInfo()
                             .setName("repartition")
                             .setPartitions(4)
                             .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                new StreamsGroupHeartbeatRequestData.KeyValue()
                                     .setKey("config-name1")
                                     .setValue("config-value1")
                             ))
@@ -781,55 +610,106 @@ public class GroupMetadataManagerTest {
                 )
                 .setStateChangelogTopics(
                     Collections.singletonList(
-                        new StreamsGroupInitializeRequestData.TopicInfo()
+                        new StreamsGroupHeartbeatRequestData.TopicInfo()
                             .setName("changelog")
-                            .setReplicationFactor((short) 3)
+                            .setReplicationFactor((short) 1)
                             .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                new StreamsGroupHeartbeatRequestData.KeyValue()
                                     .setKey("config-name2")
                                     .setValue("config-value2")
                             ))
                     )
                 )
         );
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result =
-            context.streamsGroupInitialize(
-                new StreamsGroupInitializeRequestData()
-                    .setGroupId(groupId)
-                    .setTopologyId(topologyId)
-                    .setTopology(topology)
-            );
+        StreamsGroupHeartbeatRequestData heartbeatToCreateGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, topology, processId, rebalanceTimeoutMs);
+        prepareStreamsGroupAssignment(assignor, heartbeatToCreateGroup.memberId(), "subtopology-id");
+        context.streamsGroupHeartbeat(heartbeatToCreateGroup);
+
+        StreamsGroupHeartbeatRequestData heartbeat =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, topology, processId, rebalanceTimeoutMs);
+
+        CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
 
-        CreatableTopicConfigCollection expectedConfig = new CreatableTopicConfigCollection();
-        expectedConfig.add(
+        assertNotNull(result.response());
+        Map<String, CreatableTopic> creatableTopics = result.response().creatableTopics();
+        CreatableTopicConfigCollection expectedConfig1 = new CreatableTopicConfigCollection();
+        expectedConfig1.add(
+            new CreatableTopicConfig()
+                .setName("config-name1")
+                .setValue("config-value1")
+        );
+        CreatableTopicConfigCollection expectedConfig2 = new CreatableTopicConfigCollection();
+        expectedConfig2.add(
             new CreatableTopicConfig()
                 .setName("config-name2")
                 .setValue("config-value2")
         );
-        CreatableTopic expected =
+        CreatableTopic expected1 =
             new CreatableTopic()
-                .setName("changelog")
+                .setName("repartition")
                 .setNumPartitions(4)
-                .setReplicationFactor((short) 3)
-                .setConfigs(expectedConfig);
+                .setReplicationFactor((short) -1) // default
+                .setConfigs(expectedConfig1);
+        CreatableTopic expected2 =
+            new CreatableTopic()
+                .setName("changelog")
+                .setNumPartitions(3)
+                .setReplicationFactor((short) 1)
+                .setConfigs(expectedConfig2);
 
         assertEquals(
-            new StreamsGroupInitializeResult(
-                new StreamsGroupInitializeResponseData(),
-                Collections.singletonMap(
-                    "changelog", expected
-                )
+            Map.of(
+                "repartition", expected1,
+                "changelog", expected2
             ),
-            result.response()
+            creatableTopics
         );
 
-        // TODO: Need to check the generated records. Adapt this unit test after merging of
-        //       initilization & heartbeat
+        StreamsGroupHeartbeatResponseData response = result.response().responseData();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertFalse(response.memberId().isEmpty());
+        assertEquals(2, response.memberEpoch());
+        assertTrue(response.activeTasks().isEmpty());
+        assertTrue(response.standbyTasks().isEmpty());
+        assertTrue(response.warmupTasks().isEmpty());
+        List<CoordinatorRecord> coordinatorRecords = result.records();
+        assertEquals(5, coordinatorRecords.size());
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
+        StreamsGroupMember member = new StreamsGroupMember.Builder(response.memberId())
+            .setClientId("client")
+            .setClientHost("localhost/127.0.0.1")
+            .setRebalanceTimeoutMs(rebalanceTimeoutMs)
+            .setTopologyId(topologyId)
+            .setProcessId(processId)
+            .build();
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId, member)));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 2)));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
+                groupId,
+                member.memberId(),
+                Collections.emptyMap(),
+                Collections.emptyMap(),
+                Collections.emptyMap()
+            )
+        ));
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(
+                1,
+                new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())
+            )
+            .withOwnedActiveTasks(Collections.emptyList())
+            .withOwnedStandbyTasks(Collections.emptyList())
+            .withOwnedWarmupTasks(Collections.emptyList())
+            .build();
+        assertEquals(StreamsGroup.StreamsGroupState.NOT_READY, context.streamsGroupState("group-id"));
     }
 
     private StreamsGroupHeartbeatRequestData buildFirstStreamsGroupHeartbeatRequest(
         final String groupId,
         final String topologyId,
+        final List<StreamsGroupHeartbeatRequestData.Subtopology> topology,
         final String processId,
         final int rebalanceTimeoutMs) {
 
@@ -841,6 +721,7 @@ public class GroupMetadataManagerTest {
             .setRackId(null)
             .setRebalanceTimeoutMs(rebalanceTimeoutMs)
             .setTopologyId(topologyId)
+            .setTopology(topology)
             .setActiveTasks(Collections.emptyList())
             .setStandbyTasks(Collections.emptyList())
             .setWarmupTasks(Collections.emptyList())
@@ -9329,7 +9210,7 @@ public class GroupMetadataManagerTest {
             new StreamsGroupDescribeResponseData.DescribedGroup()
                 .setGroupEpoch(epoch)
                 .setGroupId(streamsGroupIds.get(0))
-                .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
+                .setGroupState(StreamsGroupState.EMPTY.toString())
                 .setAssignmentEpoch(0),
             new StreamsGroupDescribeResponseData.DescribedGroup()
                 .setGroupEpoch(epoch)
@@ -9339,7 +9220,7 @@ public class GroupMetadataManagerTest {
                         TaskAssignmentTestUtil.mkAssignment(Collections.emptyMap())
                     )
                 ))
-                .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
+                .setGroupState(StreamsGroupState.NOT_READY.toString())
         );
         List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.sendStreamsGroupDescribe(streamsGroupIds);
 
@@ -9409,7 +9290,7 @@ public class GroupMetadataManagerTest {
                 memberBuilder1.build().asStreamsGroupDescribeMember(TaskAssignmentTestUtil.mkAssignment(Collections.emptyMap())),
                 memberBuilder2.build().asStreamsGroupDescribeMember(TaskAssignmentTestUtil.mkAssignment(assignmentMap, assignmentMap, assignmentMap))
             ))
-            .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
+            .setGroupState(StreamsGroup.StreamsGroupState.NOT_READY.toString())
             .setGroupEpoch(epoch + 2);
         assertEquals(1, actual.size());
         assertEquals(describedGroup, actual.get(0));
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 08990d9c077..08ef0327abe 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -38,8 +38,6 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.network.ClientInformation;
@@ -110,7 +108,7 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -735,38 +733,7 @@ public class GroupMetadataManagerTestContext {
         return result;
     }
 
-
-    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
-        StreamsGroupInitializeRequestData request
-    ) {
-        RequestContext context = new RequestContext(
-            new RequestHeader(
-                ApiKeys.STREAMS_GROUP_INITIALIZE,
-                ApiKeys.STREAMS_GROUP_INITIALIZE.latestVersion(),
-                "client",
-                0
-            ),
-            "1",
-            InetAddress.getLoopbackAddress(),
-            KafkaPrincipal.ANONYMOUS,
-            ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT),
-            SecurityProtocol.PLAINTEXT,
-            ClientInformation.EMPTY,
-            false
-        );
-
-        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = groupMetadataManager.streamsGroupInitialize(
-            context,
-            request
-        );
-
-        if (result.replayRecords()) {
-            result.records().forEach(this::replay);
-        }
-        return result;
-    }
-
-    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> streamsGroupHeartbeat(
         StreamsGroupHeartbeatRequestData request
     ) {
         RequestContext context = new RequestContext(
@@ -785,7 +752,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsGroupHeartbeat(
+        CoordinatorResult<StreamsGroupHeartbeatResult, CoordinatorRecord> result = groupMetadataManager.streamsGroupHeartbeat(
             context,
             request
         );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 65ad8d43fa8..029c3b8025f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
@@ -34,20 +34,20 @@ class CoordinatorStreamsRecordHelpersTest {
 
     @Test
     public void testNewStreamsGroupTopologyRecord() {
-        List<StreamsGroupInitializeRequestData.Subtopology> topology =
-            Collections.singletonList(new StreamsGroupInitializeRequestData.Subtopology()
+        List<StreamsGroupHeartbeatRequestData.Subtopology> topology =
+            Collections.singletonList(new StreamsGroupHeartbeatRequestData.Subtopology()
                 .setSubtopologyId("subtopology-id")
                 .setRepartitionSinkTopics(Collections.singletonList("foo"))
                 .setSourceTopics(Collections.singletonList("bar"))
                 .setSourceTopicRegex(Collections.singletonList("regex"))
                 .setRepartitionSourceTopics(
                     Collections.singletonList(
-                        new StreamsGroupInitializeRequestData.TopicInfo()
+                        new StreamsGroupHeartbeatRequestData.TopicInfo()
                             .setName("repartition")
                             .setPartitions(4)
                             .setReplicationFactor((short) 3)
                             .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                new StreamsGroupHeartbeatRequestData.KeyValue()
                                     .setKey("config-name1")
                                     .setValue("config-value1")
                             ))
@@ -55,21 +55,21 @@ class CoordinatorStreamsRecordHelpersTest {
                 )
                 .setStateChangelogTopics(
                     Collections.singletonList(
-                        new StreamsGroupInitializeRequestData.TopicInfo()
+                        new StreamsGroupHeartbeatRequestData.TopicInfo()
                             .setName("changelog")
                             .setReplicationFactor((short) 2)
                             .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                new StreamsGroupHeartbeatRequestData.KeyValue()
                                     .setKey("config-name2")
                                     .setValue("config-value2")
                             ))
                     )
                 )
                 .setCopartitionGroups(Arrays.asList(
-                    new StreamsGroupInitializeRequestData.CopartitionGroup()
+                    new StreamsGroupHeartbeatRequestData.CopartitionGroup()
                         .setSourceTopics(Collections.singletonList((short) 0))
                         .setRepartitionSourceTopics(Collections.singletonList((short) 0)),
-                    new StreamsGroupInitializeRequestData.CopartitionGroup()
+                    new StreamsGroupHeartbeatRequestData.CopartitionGroup()
                         .setSourceTopicRegex(Collections.singletonList((short) 0))
                 ))
             );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java
new file mode 100644
index 00000000000..9e91b36f0b2
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java
@@ -0,0 +1,93 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredInternalTopic;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class StreamsConfiguredTopologyTest {
+
+    @Test
+    public void streamsTopologyIdShouldBeCorrect() {
+        StreamsConfiguredTopology topology = new StreamsConfiguredTopology("topology-id", Collections.emptyMap(), Collections.emptyMap());
+        assertEquals("topology-id", topology.topologyId());
+    }
+
+    @Test
+    public void subtopologiesShouldBeCorrect() {
+        Map<String, ConfiguredSubtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new ConfiguredSubtopology()),
+            mkEntry("subtopology-2", new ConfiguredSubtopology())
+        );
+        StreamsConfiguredTopology topology = new StreamsConfiguredTopology("topology-id", subtopologies, Collections.emptyMap());
+        assertEquals(subtopologies, topology.subtopologies());
+    }
+
+    @Test
+    public void asStreamsGroupDescribeTopologyShouldReturnCorrectSubtopologies() {
+        Map<String, ConfiguredSubtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new ConfiguredSubtopology()
+                .setSourceTopics(Collections.singleton("source-topic-1"))
+                .setRepartitionSinkTopics(Collections.singleton("sink-topic-1"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonMap("repartition-topic-1", new ConfiguredInternalTopic("repartition-topic-1", Collections.emptyMap(), Optional.of(2), Optional.of((short) 3))))
+                .setStateChangelogTopics(
+                    Collections.singletonMap("changelog-topic-1", new ConfiguredInternalTopic("changelog-topic-1", Collections.emptyMap(), Optional.of(1), Optional.of((short) 2))))
+            ),
+            mkEntry("subtopology-2", new ConfiguredSubtopology()
+                .setSourceTopics(Collections.singleton("source-topic-2"))
+                .setRepartitionSinkTopics(Collections.singleton("sink-topic-2"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonMap("repartition-topic-2", new ConfiguredInternalTopic("repartition-topic-2", Collections.emptyMap(), Optional.of(2), Optional.of((short) 3))))
+                .setStateChangelogTopics(
+                    Collections.singletonMap("changelog-topic-2", new ConfiguredInternalTopic("changelog-topic-2", Collections.emptyMap(), Optional.of(1), Optional.of((short) 2))))
+            )
+        );
+        StreamsConfiguredTopology topology = new StreamsConfiguredTopology("topology-id", subtopologies, Collections.emptyMap());
+        List<StreamsGroupDescribeResponseData.Subtopology> result = topology.asStreamsGroupDescribeTopology();
+        assertEquals(2, result.size());
+        assertEquals("subtopology-1", result.get(0).subtopologyId());
+        assertEquals(Collections.singletonList("source-topic-1"), result.get(0).sourceTopics());
+        assertEquals(Collections.singletonList("sink-topic-1"), result.get(0).repartitionSinkTopics());
+        assertEquals("repartition-topic-1", result.get(0).repartitionSourceTopics().get(0).name());
+        assertEquals((short) 3, result.get(0).repartitionSourceTopics().get(0).replicationFactor());
+        assertEquals(2, result.get(0).repartitionSourceTopics().get(0).partitions());
+        assertEquals("changelog-topic-1", result.get(0).stateChangelogTopics().get(0).name());
+        assertEquals((short) 2, result.get(0).stateChangelogTopics().get(0).replicationFactor());
+        assertEquals(1, result.get(0).stateChangelogTopics().get(0).partitions());
+        assertEquals("subtopology-2", result.get(1).subtopologyId());
+        assertEquals(Collections.singletonList("source-topic-2"), result.get(1).sourceTopics());
+        assertEquals(Collections.singletonList("sink-topic-2"), result.get(1).repartitionSinkTopics());
+        assertEquals("repartition-topic-2", result.get(1).repartitionSourceTopics().get(0).name());
+        assertEquals((short) 3, result.get(1).repartitionSourceTopics().get(0).replicationFactor());
+        assertEquals(2, result.get(1).repartitionSourceTopics().get(0).partitions());
+        assertEquals("changelog-topic-2", result.get(1).stateChangelogTopics().get(0).name());
+        assertEquals((short) 2, result.get(1).stateChangelogTopics().get(0).replicationFactor());
+        assertEquals(1, result.get(1).stateChangelogTopics().get(0).partitions());
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index fbe9ca1821e..1269587d6c4 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -28,8 +28,8 @@ import org.apache.kafka.coordinator.group.OffsetAndMetadata;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState;
 import org.apache.kafka.timeline.SnapshotRegistry;
-
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 
@@ -53,9 +53,12 @@ import static org.mockito.Mockito.mock;
 
 public class StreamsGroupTest {
 
+    private static final LogContext LOG_CONTEXT = new LogContext();
+
     private StreamsGroup createStreamsGroup(String groupId) {
-        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(LOG_CONTEXT);
         return new StreamsGroup(
+            LOG_CONTEXT,
             snapshotRegistry,
             groupId,
             mock(GroupCoordinatorMetricsShard.class)
@@ -421,7 +424,7 @@ public class StreamsGroupTest {
     @Test
     public void testGroupState() {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
-        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
+        assertEquals(StreamsGroupState.EMPTY, streamsGroup.state());
 
         StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
             .setState(MemberState.STABLE)
@@ -433,7 +436,7 @@ public class StreamsGroupTest {
         streamsGroup.setGroupEpoch(1);
 
         assertEquals(MemberState.STABLE, member1.state());
-        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
+        assertEquals(StreamsGroup.StreamsGroupState.NOT_READY, streamsGroup.state());
 
         streamsGroup.setTopology(new StreamsTopology("topology-id", Collections.emptyMap()));
 
@@ -498,9 +501,9 @@ public class StreamsGroupTest {
 
     @Test
     public void testUpdateInvertedAssignment() {
-        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(LOG_CONTEXT);
         GroupCoordinatorMetricsShard metricsShard = mock(GroupCoordinatorMetricsShard.class);
-        StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, "test-group", metricsShard);
+        StreamsGroup streamsGroup = new StreamsGroup(LOG_CONTEXT, snapshotRegistry, "test-group", metricsShard);
         String subtopologyId = "foo-sub";
         String memberId1 = "member1";
         String memberId2 = "member2";
@@ -543,7 +546,7 @@ public class StreamsGroupTest {
             emptyMap(),
             emptyMap()
         );
-        streamsGroup.updateTargetAssignment(memberId2, newAssignment);
+        streamsGroup.updateTargetAssignment(memberId2, newAssignment2);
 
         // Verify that partition 1 is assigned to member2
         assertEquals(
@@ -664,8 +667,9 @@ public class StreamsGroupTest {
 
     @Test
     public void testValidateOffsetFetch() {
-        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(LOG_CONTEXT);
         StreamsGroup group = new StreamsGroup(
+            LOG_CONTEXT,
             snapshotRegistry,
             "group-foo",
             mock(GroupCoordinatorMetricsShard.class)
@@ -698,7 +702,7 @@ public class StreamsGroupTest {
     public void testValidateDeleteGroup() {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
-        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
+        assertEquals(StreamsGroupState.EMPTY, streamsGroup.state());
         assertDoesNotThrow(streamsGroup::validateDeleteGroup);
 
         StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
@@ -732,7 +736,7 @@ public class StreamsGroupTest {
         long commitTimestamp = 20000L;
         long offsetsRetentionMs = 10000L;
         OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(15000L, OptionalInt.empty(), "", commitTimestamp, OptionalLong.empty());
-        StreamsGroup group = new StreamsGroup(new SnapshotRegistry(new LogContext()), "group-id", mock(GroupCoordinatorMetricsShard.class));
+        StreamsGroup group = new StreamsGroup(LOG_CONTEXT, new SnapshotRegistry(LOG_CONTEXT), "group-id", mock(GroupCoordinatorMetricsShard.class));
 
         Optional<OffsetExpirationCondition> offsetExpirationCondition = group.offsetExpirationCondition();
         assertTrue(offsetExpirationCondition.isPresent());
@@ -743,22 +747,23 @@ public class StreamsGroupTest {
     }
 
     @Test
-    public void testIsInStatesCaseInsensitive() {
-        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+    public void testIsInStatesCaseInsensitiveAndUnderscored() {
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(LOG_CONTEXT);
         GroupCoordinatorMetricsShard metricsShard = new GroupCoordinatorMetricsShard(
             snapshotRegistry,
             emptyMap(),
             new TopicPartition("__consumer_offsets", 0)
         );
-        StreamsGroup group = new StreamsGroup(snapshotRegistry, "group-foo", metricsShard);
+        StreamsGroup group = new StreamsGroup(LOG_CONTEXT, snapshotRegistry, "group-foo", metricsShard);
         snapshotRegistry.idempotentCreateSnapshot(0);
-        assertTrue(group.isInStates(Collections.singleton("initializing"), 0));
-        assertFalse(group.isInStates(Collections.singleton("Initializing"), 0));
+        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
+        assertFalse(group.isInStates(Collections.singleton("Empty"), 0));
 
-        group.setTopology(new StreamsTopology("topology-id", Collections.emptyMap()));
+        group.updateMember(new StreamsGroupMember.Builder("member1")
+            .build());
         snapshotRegistry.idempotentCreateSnapshot(1);
-        assertTrue(group.isInStates(Collections.singleton("initializing"), 0));
-        assertTrue(group.isInStates(Collections.singleton("empty"), 1));
-        assertFalse(group.isInStates(Collections.singleton("initializing"), 1));
+        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
+        assertTrue(group.isInStates(Collections.singleton("not_ready"), 1));
+        assertFalse(group.isInStates(Collections.singleton("empty"), 1));
     }
 }
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
index 7aa303603ab..54f8de1a3da 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -16,17 +16,14 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
-
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
@@ -55,7 +52,7 @@ public class StreamsTopologyTest {
     }
 
     @Test
-    public void topicSubscriptionShouldBeCorrect() {
+    public void requiredTopicsShouldBeCorrect() {
         Map<String, Subtopology> subtopologies = mkMap(
             mkEntry("subtopology-1", new Subtopology()
                 .setSourceTopics(Arrays.asList("source-topic-1", "source-topic-2"))
@@ -63,6 +60,10 @@ public class StreamsTopologyTest {
                     new TopicInfo().setName("repartition-topic-1"),
                     new TopicInfo().setName("repartition-topic-2")
                 ))
+                .setStateChangelogTopics(Arrays.asList(
+                    new TopicInfo().setName("changelog-topic-1"),
+                    new TopicInfo().setName("changelog-topic-2")
+                ))
             ),
             mkEntry("subtopology-2", new Subtopology()
                 .setSourceTopics(Arrays.asList("source-topic-3", "source-topic-4"))
@@ -75,9 +76,10 @@ public class StreamsTopologyTest {
         StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
         Set<String> expectedTopics = new HashSet<>(Arrays.asList(
             "source-topic-1", "source-topic-2", "repartition-topic-1", "repartition-topic-2",
-            "source-topic-3", "source-topic-4", "repartition-topic-3", "repartition-topic-4"
+            "source-topic-3", "source-topic-4", "repartition-topic-3", "repartition-topic-4",
+            "changelog-topic-1", "changelog-topic-2"
         ));
-        assertEquals(expectedTopics, topology.topicSubscription());
+        assertEquals(expectedTopics, topology.requiredTopics());
     }
 
     @Test
@@ -140,65 +142,4 @@ public class StreamsTopologyTest {
         String expectedString = "StreamsTopology{topologyId=topology-id, subtopologies=" + subtopologies + "}";
         assertEquals(expectedString, topology.toString());
     }
-
-    @Test
-    public void asStreamsGroupDescribeTopologyShouldReturnCorrectSubtopologies() {
-        Map<String, Subtopology> subtopologies = mkMap(
-            mkEntry("subtopology-1", new Subtopology()
-                .setSourceTopicRegex(Collections.singletonList("regex-1"))
-                .setSubtopologyId("subtopology-1")
-                .setSourceTopics(Collections.singletonList("source-topic-1"))
-                .setRepartitionSinkTopics(Collections.singletonList("sink-topic-1"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(new TopicInfo()
-                        .setName("repartition-topic-1")
-                        .setReplicationFactor((short) 3)
-                        .setPartitions(2)))
-                .setStateChangelogTopics(
-                    Collections.singletonList(new TopicInfo()
-                        .setName("changelog-topic-1")
-                        .setReplicationFactor((short) 2)
-                        .setPartitions(1)))
-            ),
-            mkEntry("subtopology-2", new Subtopology()
-                .setSourceTopicRegex(Collections.singletonList("regex-2"))
-                .setSubtopologyId("subtopology-2")
-                .setSourceTopics(Collections.singletonList("source-topic-2"))
-                .setRepartitionSinkTopics(Collections.singletonList("sink-topic-2"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(new TopicInfo()
-                        .setName("repartition-topic-2")
-                        .setReplicationFactor((short) 3)
-                        .setPartitions(2)))
-                .setStateChangelogTopics(
-                    Collections.singletonList(new TopicInfo()
-                        .setName("changelog-topic-2")
-                        .setReplicationFactor((short) 2)
-                        .setPartitions(1)))
-            )
-        );
-        StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
-        List<StreamsGroupDescribeResponseData.Subtopology> result = topology.asStreamsGroupDescribeTopology();
-        assertEquals(2, result.size());
-        assertEquals(Collections.singletonList("regex-1"), result.get(0).sourceTopicRegex());
-        assertEquals("subtopology-1", result.get(0).subtopologyId());
-        assertEquals(Collections.singletonList("source-topic-1"), result.get(0).sourceTopics());
-        assertEquals(Collections.singletonList("sink-topic-1"), result.get(0).repartitionSinkTopics());
-        assertEquals("repartition-topic-1", result.get(0).repartitionSourceTopics().get(0).name());
-        assertEquals((short) 3, result.get(0).repartitionSourceTopics().get(0).replicationFactor());
-        assertEquals(2, result.get(0).repartitionSourceTopics().get(0).partitions());
-        assertEquals("changelog-topic-1", result.get(0).stateChangelogTopics().get(0).name());
-        assertEquals((short) 2, result.get(0).stateChangelogTopics().get(0).replicationFactor());
-        assertEquals(1, result.get(0).stateChangelogTopics().get(0).partitions());
-        assertEquals(Collections.singletonList("regex-2"), result.get(1).sourceTopicRegex());
-        assertEquals("subtopology-2", result.get(1).subtopologyId());
-        assertEquals(Collections.singletonList("source-topic-2"), result.get(1).sourceTopics());
-        assertEquals(Collections.singletonList("sink-topic-2"), result.get(1).repartitionSinkTopics());
-        assertEquals("repartition-topic-2", result.get(1).repartitionSourceTopics().get(0).name());
-        assertEquals((short) 3, result.get(1).repartitionSourceTopics().get(0).replicationFactor());
-        assertEquals(2, result.get(1).repartitionSourceTopics().get(0).partitions());
-        assertEquals("changelog-topic-2", result.get(1).stateChangelogTopics().get(0).name());
-        assertEquals((short) 2, result.get(1).stateChangelogTopics().get(0).replicationFactor());
-        assertEquals(1, result.get(1).stateChangelogTopics().get(0).partitions());
-    }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index e9324bcf696..773bafd6f1d 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -226,7 +226,7 @@ public class TargetAssignmentBuilderTest {
                 .withMembers(members)
                 .withTopology(topology)
                 .withStaticMembers(staticMembers)
-                .withSubscriptionMetadata(subscriptionMetadata)
+                .withPartitionMetadata(subscriptionMetadata)
                 .withTargetAssignment(targetAssignment);
 
             // Add the updated members or delete the deleted members.
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
index e6ef6fee5d3..ecde45d96d5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
@@ -23,14 +23,12 @@ import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCon
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
-import org.apache.kafka.image.MetadataImage;
-import org.apache.kafka.image.TopicImage;
-import org.apache.kafka.image.TopicsImage;
-import org.apache.kafka.server.immutable.ImmutableMap;
+import org.apache.kafka.coordinator.group.streams.TopicMetadata;
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
@@ -39,34 +37,19 @@ import java.util.Set;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
 
 class InternalTopicManagerTest {
 
     @Test
     void testMissingTopics() {
-        MetadataImage metadataImage = mock(MetadataImage.class);
-        TopicsImage topicsImage = mock(TopicsImage.class);
-        when(metadataImage.topics()).thenReturn(topicsImage);
-        final TopicImage sourceTopic1 =
-            new TopicImage("source_topic1", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null)));
-        final TopicImage sourceTopic2 =
-            new TopicImage("source_topic2", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null)));
-        final TopicImage stateChangelogTopic2 = new TopicImage("state_changelog_topic2", Uuid.randomUuid(),
-            mkMap(mkEntry(0, null), mkEntry(1, null)));
-        when(topicsImage.topicsByName()).thenReturn(
-            ImmutableMap.singleton("source_topic1", sourceTopic1)
-                .updated("source_topic2", sourceTopic2)
-                .updated("state_changelog_topic2", stateChangelogTopic2)
-        );
-        when(topicsImage.getTopic(eq("source_topic1"))).thenReturn(sourceTopic1);
-        when(topicsImage.getTopic(eq("source_topic2"))).thenReturn(sourceTopic2);
-        when(topicsImage.getTopic(eq("state_changelog_topic2"))).thenReturn(stateChangelogTopic2);
+        Map<String, TopicMetadata> topicMetadata = new HashMap<>();
+        topicMetadata.put("source_topic1", new TopicMetadata(Uuid.randomUuid(), "source_topic1", 2, Collections.emptyMap()));
+        topicMetadata.put("source_topic2", new TopicMetadata(Uuid.randomUuid(), "source_topic2", 2, Collections.emptyMap()));
+        topicMetadata.put("state_changelog_topic2",
+            new TopicMetadata(Uuid.randomUuid(), "state_changelog_topic2", 2, Collections.emptyMap()));
         Map<String, ConfiguredSubtopology> subtopologyMap = makeExpectedConfiguredTopology();
 
-        Map<String, CreatableTopic> missingTopics = InternalTopicManager.missingTopics(subtopologyMap, metadataImage);
+        Map<String, CreatableTopic> missingTopics = InternalTopicManager.missingTopics(subtopologyMap, topicMetadata);
 
         assertEquals(2, missingTopics.size());
         assertEquals(
@@ -90,17 +73,13 @@ class InternalTopicManagerTest {
 
     @Test
     void testConfigureTopics() {
-        MetadataImage metadataImage = mock(MetadataImage.class);
-        TopicsImage topicsImage = mock(TopicsImage.class);
-        when(metadataImage.topics()).thenReturn(topicsImage);
-        when(topicsImage.getTopic(eq("source_topic1"))).thenReturn(
-            new TopicImage("source_topic1", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null))));
-        when(topicsImage.getTopic(eq("source_topic2"))).thenReturn(
-            new TopicImage("source_topic2", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null))));
+        Map<String, TopicMetadata> topicMetadata = new HashMap<>();
+        topicMetadata.put("source_topic1", new TopicMetadata(Uuid.randomUuid(), "source_topic1", 2, Collections.emptyMap()));
+        topicMetadata.put("source_topic2", new TopicMetadata(Uuid.randomUuid(), "source_topic2", 2, Collections.emptyMap()));
         List<Subtopology> subtopologyList = makeTestTopology();
 
         Map<String, ConfiguredSubtopology> configuredSubtopologies =
-            InternalTopicManager.configureTopics(new LogContext(), subtopologyList, metadataImage);
+            InternalTopicManager.configureTopics(new LogContext(), subtopologyList, topicMetadata);
 
         Map<String, ConfiguredSubtopology> expectedConfiguredSubtopologyMap = makeExpectedConfiguredTopology();
         assertEquals(expectedConfiguredSubtopologyMap, configuredSubtopologies);
diff --git a/server/src/main/java/org/apache/kafka/network/RequestConvertToJson.java b/server/src/main/java/org/apache/kafka/network/RequestConvertToJson.java
index ac744ef7bac..f7b26601f7c 100644
--- a/server/src/main/java/org/apache/kafka/network/RequestConvertToJson.java
+++ b/server/src/main/java/org/apache/kafka/network/RequestConvertToJson.java
@@ -175,6 +175,10 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestDataJsonConvert
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseDataJsonConverter;
 import org.apache.kafka.common.message.StopReplicaRequestDataJsonConverter;
 import org.apache.kafka.common.message.StopReplicaResponseDataJsonConverter;
+import org.apache.kafka.common.message.StreamsGroupDescribeRequestDataJsonConverter;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseDataJsonConverter;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestDataJsonConverter;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseDataJsonConverter;
 import org.apache.kafka.common.message.SyncGroupRequestDataJsonConverter;
 import org.apache.kafka.common.message.SyncGroupResponseDataJsonConverter;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestDataJsonConverter;
@@ -356,6 +360,10 @@ import org.apache.kafka.common.requests.ShareGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.ShareGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.StopReplicaRequest;
 import org.apache.kafka.common.requests.StopReplicaResponse;
+import org.apache.kafka.common.requests.StreamsGroupDescribeRequest;
+import org.apache.kafka.common.requests.StreamsGroupDescribeResponse;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.SyncGroupRequest;
 import org.apache.kafka.common.requests.SyncGroupResponse;
 import org.apache.kafka.common.requests.TxnOffsetCommitRequest;
@@ -541,6 +549,10 @@ public class RequestConvertToJson {
                 return ShareGroupDescribeRequestDataJsonConverter.write(((ShareGroupDescribeRequest) request).data(), request.version());
             case SHARE_GROUP_HEARTBEAT:
                 return ShareGroupHeartbeatRequestDataJsonConverter.write(((ShareGroupHeartbeatRequest) request).data(), request.version());
+            case STREAMS_GROUP_DESCRIBE:
+                return StreamsGroupDescribeRequestDataJsonConverter.write(((StreamsGroupDescribeRequest) request).data(), request.version());
+            case STREAMS_GROUP_HEARTBEAT:
+                return StreamsGroupHeartbeatRequestDataJsonConverter.write(((StreamsGroupHeartbeatRequest) request).data(), request.version());
             case STOP_REPLICA:
                 return StopReplicaRequestDataJsonConverter.write(((StopReplicaRequest) request).data(), request.version());
             case SYNC_GROUP:
@@ -725,6 +737,10 @@ public class RequestConvertToJson {
                 return ShareGroupDescribeResponseDataJsonConverter.write(((ShareGroupDescribeResponse) response).data(), version);
             case SHARE_GROUP_HEARTBEAT:
                 return ShareGroupHeartbeatResponseDataJsonConverter.write(((ShareGroupHeartbeatResponse) response).data(), version);
+            case STREAMS_GROUP_DESCRIBE:
+                return StreamsGroupDescribeResponseDataJsonConverter.write(((StreamsGroupDescribeResponse) response).data(), version);
+            case STREAMS_GROUP_HEARTBEAT:
+                return StreamsGroupHeartbeatResponseDataJsonConverter.write(((StreamsGroupHeartbeatResponse) response).data(), version);
             case STOP_REPLICA:
                 return StopReplicaResponseDataJsonConverter.write(((StopReplicaResponse) response).data(), version);
             case SYNC_GROUP:
diff --git a/streams/src/test/resources/log4j.properties b/streams/src/test/resources/log4j.properties
index 2f0f3833eb9..4dcab88183b 100644
--- a/streams/src/test/resources/log4j.properties
+++ b/streams/src/test/resources/log4j.properties
@@ -28,7 +28,6 @@ log4j.logger.org.apache.kafka.clients.consumer=INFO
 log4j.logger.org.apache.kafka.clients.producer=INFO
 log4j.logger.org.apache.kafka.streams=INFO
 log4j.logger.org.apache.kafka.coordinator.group=INFO
-log4j.logger.org.apache.kafka.clients.consumer.internals.StreamsGroupInitializeRequestManager=INFO
 log4j.logger.org.apache.kafka.clients.consumer.internals.StreamsGroupHeartbeatRequestManager=INFO
 
 # printing out the configs takes up a huge amount of the allotted characters,


(kafka) 34/42: Resolve conflicts from trunk rebase - Port tools for topic configuration (#17371)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit f5f901771ce1b5d53f65d76046638898b622f968
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue Oct 22 15:11:40 2024 +0200

    Resolve conflicts from trunk rebase - Port tools for topic configuration (#17371)
    
    * KSTREAMS-6456: Port tools for topic configuration
    
    Ports several tools for topic configuration from the client side, to the
    broker-side. Several things are refactored:
    
     - Decoupling. On the client side, for example, RepartitionTopics was
       using the CopartitionedTopicEnforcer, the InternalTopicCreator, the
       TopologyMetadata and the Cluster objects. All of those are mocked
       with Mockito during testing. This points to bad coupling. We
       refactored all classes to be mostly self-sufficient, only relying on
       themselves and simple interfaces.
     - Tests only use JUnit5, not hamcrast matchers and no other streams
       utilities, to not pollute the group coordinator module.
     - All classes only modify the configurations -- the code does not
       actually call into the AdminClient anymore.
     - We map all errors to new errors in the broker, in particular,
       the error for missing topics, inconsistent internal topics, and
       invalid topologies.
    
    We include the internal, mutable datastructures, that are set- and
    map-based for effiecient algorithms. They are distinctly different
    from the data represented in `StreamsGroupTopologyValue` and
    `StreamsGroupInitializeRequest`, since regular expressions must
    be resolved at this point.
    
    Both the topic creation and internal topic validation will be
    based on this code, the basics of this are implemented in the
    `InternalTopicManager`.
    
    Every time, either the broker-side topology or the topic metadata
    on the broker changes, we reconfigure the internal topics, check
    consistency with the current topics on the broker, and possibly
    trigger creation of the missing internal topics. These changes
    will be built on top of this change.
    
    * formatting fixes
---
 checkstyle/import-control-group-coordinator.xml    |   1 +
 ...StreamsInconsistentInternalTopicsException.java |  23 ++
 .../org/apache/kafka/common/protocol/Errors.java   |  11 +-
 .../group/streams/topics/ChangelogTopics.java      |  82 +++++++
 .../streams/topics/ConfiguredInternalTopic.java    | 138 ++++++++++++
 .../streams/topics/ConfiguredSubtopology.java      | 144 +++++++++++++
 .../topics/CopartitionedTopicsEnforcer.java        | 191 ++++++++++++++++
 .../group/streams/topics/InternalTopicManager.java | 231 ++++++++++++++++++++
 .../group/streams/topics/RepartitionTopics.java    | 180 ++++++++++++++++
 .../group/streams/topics/ChangelogTopicsTest.java  | 136 ++++++++++++
 .../topics/ConfiguredInternalTopicTest.java        | 104 +++++++++
 .../streams/topics/ConfiguredSubtopologyTest.java  | 137 ++++++++++++
 .../topics/CopartitionedTopicsEnforcerTest.java    | 230 ++++++++++++++++++++
 .../streams/topics/InternalTopicManagerTest.java   | 178 +++++++++++++++
 .../streams/topics/RepartitionTopicsTest.java      | 239 +++++++++++++++++++++
 15 files changed, 2020 insertions(+), 5 deletions(-)

diff --git a/checkstyle/import-control-group-coordinator.xml b/checkstyle/import-control-group-coordinator.xml
index 0619ea444d5..0f54365322c 100644
--- a/checkstyle/import-control-group-coordinator.xml
+++ b/checkstyle/import-control-group-coordinator.xml
@@ -63,6 +63,7 @@
             <allow pkg="org.apache.kafka.deferred" />
             <allow pkg="org.apache.kafka.image"/>
             <allow pkg="org.apache.kafka.server.common"/>
+            <allow pkg="org.apache.kafka.server.immutable"/>
             <allow pkg="org.apache.kafka.server.record"/>
             <allow pkg="org.apache.kafka.server.util"/>
             <allow pkg="org.apache.kafka.storage.internals.log"/>
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentInternalTopicsException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentInternalTopicsException.java
new file mode 100644
index 00000000000..fbf81f14260
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentInternalTopicsException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsInconsistentInternalTopicsException extends ApiException {
+    public StreamsInconsistentInternalTopicsException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index db5194d4a2b..e8687314808 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -120,6 +120,7 @@ import org.apache.kafka.common.errors.SnapshotNotFoundException;
 import org.apache.kafka.common.errors.StaleBrokerEpochException;
 import org.apache.kafka.common.errors.StaleMemberEpochException;
 import org.apache.kafka.common.errors.StreamsGroupUninitializedException;
+import org.apache.kafka.common.errors.StreamsInconsistentInternalTopicsException;
 import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
 import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
 import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
@@ -425,12 +426,12 @@ public enum Errors {
         StreamsInconsistentTopologyException::new),
     STREAMS_MISSING_SOURCE_TOPICS(132, "One or more source topics are missing.",
         StreamsMissingSourceTopicsException::new),
-    STREAMS_MISSING_INTERNAL_TOPICS(133, "One or more internal topics are missing.",
-        StreamsMissingInternalTopicsException::new),
-    STREAMS_GROUP_UNINITIALIZED(134, "The group is not (fully) initialized, broker-side topology information or internal topics are missing.",
+    STREAMS_GROUP_UNINITIALIZED(133, "The group is not (fully) initialized, broker-side topology information or internal topics are missing.",
             StreamsGroupUninitializedException::new),
-    STREAMS_SHUTDOWN_APPLICATION(135, "A client requested the shutdown of the whole application.",
-            StreamsShutdownApplicationException::new);
+    STREAMS_SHUTDOWN_APPLICATION(134, "A client requested the shutdown of the whole application.",
+            StreamsShutdownApplicationException::new),
+    STREAMS_INCONSISTENT_INTERNAL_TOPICS(135, "One or more internal topics are missing.",
+        StreamsInconsistentInternalTopicsException::new);
 
     private static final Logger log = LoggerFactory.getLogger(Errors.class);
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopics.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopics.java
new file mode 100644
index 00000000000..298c8abbfa3
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopics.java
@@ -0,0 +1,82 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.slf4j.Logger;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.OptionalInt;
+import java.util.function.Function;
+
+/**
+ * This class is responsible for setting up the changelog topics for a topology.
+ */
+public class ChangelogTopics {
+
+    private final Map<String, ConfiguredSubtopology> subtopologies;
+    private final Function<String, Integer> topicPartitionCountProvider;
+    private final Logger log;
+
+    public ChangelogTopics(
+        final LogContext logContext,
+        final Map<String, ConfiguredSubtopology> subtopologies,
+        final Function<String, Integer> topicPartitionCountProvider
+    ) {
+        this.log = logContext.logger(getClass());
+        this.subtopologies = subtopologies;
+        this.topicPartitionCountProvider = topicPartitionCountProvider;
+    }
+
+    /**
+     * Modifies the provided ConfiguredSubtopology to set the number of partitions for each changelog topic.
+     *
+     * @return the map of changelog topics for the requested topology that are internal and may need to be created.
+     */
+    public Map<String, ConfiguredInternalTopic> setup() {
+        final Map<String, ConfiguredInternalTopic> changelogTopicMetadata = new HashMap<>();
+        for (final Map.Entry<String, ConfiguredSubtopology> entry : subtopologies.entrySet()) {
+            final ConfiguredSubtopology configuredSubtopology = entry.getValue();
+
+            final OptionalInt maxNumPartitions =
+                configuredSubtopology.sourceTopics().stream().mapToInt(this::getPartitionCountOrFail).max();
+
+            if (!maxNumPartitions.isPresent()) {
+                throw new StreamsInvalidTopologyException("No source topics found for subtopology " + entry.getKey());
+            }
+            for (final ConfiguredInternalTopic topicConfig : configuredSubtopology.nonSourceChangelogTopics()) {
+                changelogTopicMetadata.put(topicConfig.name(), topicConfig);
+                topicConfig.setNumberOfPartitions(maxNumPartitions.getAsInt());
+            }
+        }
+
+        log.debug("Expecting state changelog topics {} for the requested topology.", changelogTopicMetadata.values());
+        return changelogTopicMetadata;
+    }
+
+    private int getPartitionCountOrFail(String topic) {
+        final Integer topicPartitionCount = topicPartitionCountProvider.apply(topic);
+        if (topicPartitionCount == null) {
+            throw new StreamsMissingSourceTopicsException("No partition count for source topic " + topic);
+        }
+        return topicPartitionCount;
+    }
+}
\ No newline at end of file
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopic.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopic.java
new file mode 100644
index 00000000000..875b3192ea1
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopic.java
@@ -0,0 +1,138 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.internals.Topic;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * ConfiguredInternalTopic captures the properties required for configuring the internal topics we create for change-logs and repartitioning
+ * etc.
+ * <p>
+ * It is derived from the topology sent by the client, and the current state of the topics inside the broker. If the topics on the broker
+ * changes, the internal topic may need to be reconfigured.
+ */
+public class ConfiguredInternalTopic {
+
+    private final String name;
+    private final Map<String, String> topicConfigs;
+    private final Optional<Short> replicationFactor;
+    private final boolean enforceNumberOfPartitions;
+    private Optional<Integer> numberOfPartitions;
+
+    public ConfiguredInternalTopic(final String name) {
+        this(name, Collections.emptyMap(), Optional.empty(), Optional.empty());
+    }
+
+    public ConfiguredInternalTopic(final String name,
+                                   final Map<String, String> topicConfigs) {
+        this(name, topicConfigs, Optional.empty(), Optional.empty());
+    }
+
+    public ConfiguredInternalTopic(final String name,
+                                   final Map<String, String> topicConfigs,
+                                   final Optional<Integer> numberOfPartitions,
+                                   final Optional<Short> replicationFactor) {
+        this.name = Objects.requireNonNull(name, "name can't be null");
+        Topic.validate(name);
+        numberOfPartitions.ifPresent(ConfiguredInternalTopic::validateNumberOfPartitions);
+        this.topicConfigs = Objects.requireNonNull(topicConfigs, "topicConfigs can't be null");
+        this.numberOfPartitions = numberOfPartitions;
+        this.replicationFactor = replicationFactor;
+        this.enforceNumberOfPartitions = numberOfPartitions.isPresent();
+    }
+
+    private static void validateNumberOfPartitions(final int numberOfPartitions) {
+        if (numberOfPartitions < 1) {
+            throw new IllegalArgumentException("Number of partitions must be at least 1.");
+        }
+    }
+
+    public Map<String, String> topicConfigs() {
+        return topicConfigs;
+    }
+
+    public boolean hasEnforcedNumberOfPartitions() {
+        return enforceNumberOfPartitions;
+    }
+
+    public String name() {
+        return name;
+    }
+
+    public Optional<Integer> numberOfPartitions() {
+        return numberOfPartitions;
+    }
+
+    public Optional<Short> replicationFactor() {
+        return replicationFactor;
+    }
+
+    public ConfiguredInternalTopic setNumberOfPartitions(final int numberOfPartitions) {
+        if (this.hasEnforcedNumberOfPartitions()
+            && this.numberOfPartitions.isPresent()
+            && this.numberOfPartitions.get() != numberOfPartitions) {
+            throw new UnsupportedOperationException(
+                "number of partitions are enforced on topic " + name() + " and can't be altered.");
+        }
+
+        validateNumberOfPartitions(numberOfPartitions);
+
+        this.numberOfPartitions = Optional.of(numberOfPartitions);
+        return this;
+    }
+
+    @Override
+    public String toString() {
+        return "ConfiguredInternalTopic(" +
+            "name=" + name +
+            ", topicConfigs=" + topicConfigs +
+            ", numberOfPartitions=" + numberOfPartitions +
+            ", replicationFactor=" + replicationFactor +
+            ", enforceNumberOfPartitions=" + enforceNumberOfPartitions +
+            ")";
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        ConfiguredInternalTopic that = (ConfiguredInternalTopic) o;
+        return enforceNumberOfPartitions == that.enforceNumberOfPartitions
+            && Objects.equals(name, that.name)
+            && Objects.equals(topicConfigs, that.topicConfigs)
+            && Objects.equals(numberOfPartitions, that.numberOfPartitions)
+            && Objects.equals(replicationFactor, that.replicationFactor);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(name,
+            topicConfigs,
+            numberOfPartitions,
+            replicationFactor,
+            enforceNumberOfPartitions);
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopology.java
new file mode 100644
index 00000000000..1faba6c38ba
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopology.java
@@ -0,0 +1,144 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Internal representation of a subtopology.
+ * <p>
+ * The subtopology is configured according to the number of partitions available in the source topics. It has regular expressions already
+ * resolved and defined exactly the information that is being used by streams groups assignment reconciliation.
+ * <p>
+ * Configured subtopologies may be recreated every time the input topics used by the subtopology are modified.
+ */
+public class ConfiguredSubtopology {
+
+    private Set<String> repartitionSinkTopics;
+    private Set<String> sourceTopics;
+    private Map<String, ConfiguredInternalTopic> stateChangelogTopics;
+    private Map<String, ConfiguredInternalTopic> repartitionSourceTopics;
+
+    public ConfiguredSubtopology() {
+        this.repartitionSinkTopics = new HashSet<>();
+        this.sourceTopics = new HashSet<>();
+        this.stateChangelogTopics = new HashMap<>();
+        this.repartitionSourceTopics = new HashMap<>();
+    }
+
+    public ConfiguredSubtopology(
+        final Set<String> repartitionSinkTopics,
+        final Set<String> sourceTopics,
+        final Map<String, ConfiguredInternalTopic> repartitionSourceTopics,
+        final Map<String, ConfiguredInternalTopic> stateChangelogTopics
+    ) {
+        this.repartitionSinkTopics = repartitionSinkTopics;
+        this.sourceTopics = sourceTopics;
+        this.stateChangelogTopics = stateChangelogTopics;
+        this.repartitionSourceTopics = repartitionSourceTopics;
+    }
+
+    public Set<String> repartitionSinkTopics() {
+        return repartitionSinkTopics;
+    }
+
+    public Set<String> sourceTopics() {
+        return sourceTopics;
+    }
+
+    public Map<String, ConfiguredInternalTopic> stateChangelogTopics() {
+        return stateChangelogTopics;
+    }
+
+    public Map<String, ConfiguredInternalTopic> repartitionSourceTopics() {
+        return repartitionSourceTopics;
+    }
+
+    public ConfiguredSubtopology setRepartitionSinkTopics(final Set<String> repartitionSinkTopics) {
+        this.repartitionSinkTopics = repartitionSinkTopics;
+        return this;
+    }
+
+    public ConfiguredSubtopology setSourceTopics(final Set<String> sourceTopics) {
+        this.sourceTopics = sourceTopics;
+        return this;
+    }
+
+    public ConfiguredSubtopology setStateChangelogTopics(
+        final Map<String, ConfiguredInternalTopic> stateChangelogTopics
+    ) {
+        this.stateChangelogTopics = stateChangelogTopics;
+        return this;
+    }
+
+    public ConfiguredSubtopology setRepartitionSourceTopics(
+        final Map<String, ConfiguredInternalTopic> repartitionSourceTopics
+    ) {
+        this.repartitionSourceTopics = repartitionSourceTopics;
+        return this;
+    }
+
+    /**
+     * Returns the config for any changelogs that must be prepared for this topic group, ie excluding any source topics that are reused as a
+     * changelog
+     */
+    public Set<ConfiguredInternalTopic> nonSourceChangelogTopics() {
+        final Set<ConfiguredInternalTopic> topicConfigs = new HashSet<>();
+        for (final Map.Entry<String, ConfiguredInternalTopic> changelogTopicEntry : stateChangelogTopics.entrySet()) {
+            if (!sourceTopics.contains(changelogTopicEntry.getKey())) {
+                topicConfigs.add(changelogTopicEntry.getValue());
+            }
+        }
+        return topicConfigs;
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final ConfiguredSubtopology that = (ConfiguredSubtopology) o;
+        return Objects.equals(repartitionSinkTopics, that.repartitionSinkTopics)
+            && Objects.equals(sourceTopics, that.sourceTopics)
+            && Objects.equals(stateChangelogTopics, that.stateChangelogTopics)
+            && Objects.equals(repartitionSourceTopics, that.repartitionSourceTopics);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(repartitionSinkTopics, sourceTopics,
+            stateChangelogTopics, repartitionSourceTopics);
+    }
+
+    @Override
+    public String toString() {
+        return "ConfiguredSubtopology{" +
+            "repartitionSinkTopics=" + repartitionSinkTopics +
+            ", sourceTopics=" + sourceTopics +
+            ", stateChangelogTopics=" + stateChangelogTopics +
+            ", repartitionSourceTopics=" + repartitionSourceTopics +
+            '}';
+    }
+
+}
\ No newline at end of file
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcer.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcer.java
new file mode 100644
index 00000000000..a74cff5d33e
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcer.java
@@ -0,0 +1,191 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsInconsistentInternalTopicsException;
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+/**
+ * This class is responsible for enforcing the number of partitions in copartitioned topics.
+ */
+public class CopartitionedTopicsEnforcer {
+
+    private final Logger log;
+    private final Function<String, Integer> topicPartitionCountProvider;
+
+    public CopartitionedTopicsEnforcer(final LogContext logContext,
+                                       final Function<String, Integer> topicPartitionCountProvider) {
+        this.log = logContext.logger(getClass());
+        this.topicPartitionCountProvider = topicPartitionCountProvider;
+    }
+
+    private static void maybeSetNumberOfPartitionsForInternalTopic(final int numPartitionsToUseForRepartitionTopics,
+                                                                   final ConfiguredInternalTopic config) {
+        if (!config.hasEnforcedNumberOfPartitions()) {
+            config.setNumberOfPartitions(numPartitionsToUseForRepartitionTopics);
+        }
+    }
+
+    private static Supplier<StreamsInvalidTopologyException> emptyNumberOfPartitionsExceptionSupplier(final String topic) {
+        return () -> new StreamsInvalidTopologyException("Number of partitions is not set for topic: " + topic);
+    }
+
+    /**
+     * Enforces the number of partitions for copartitioned topics.
+     *
+     * @param copartitionedTopics the set of copartitioned topics
+     * @param repartitionTopics   a map from repartition topics to their internal topic configs
+     */
+    public void enforce(final Set<String> copartitionedTopics,
+                        final Map<String, ConfiguredInternalTopic> repartitionTopics) {
+        if (copartitionedTopics.isEmpty()) {
+            return;
+        }
+
+        final Map<Object, ConfiguredInternalTopic> repartitionTopicConfigs =
+            copartitionedTopics.stream()
+                .filter(repartitionTopics::containsKey)
+                .collect(Collectors.toMap(topic -> topic, repartitionTopics::get));
+
+        final Map<String, Integer> nonRepartitionTopicPartitions =
+            copartitionedTopics.stream().filter(topic -> !repartitionTopics.containsKey(topic))
+                .collect(Collectors.toMap(topic -> topic, topic -> {
+                    final Integer topicPartitionCount = topicPartitionCountProvider.apply(topic);
+                    if (topicPartitionCount == null) {
+                        final String str = String.format("Topic not found: %s", topic);
+                        log.error(str);
+                        throw new StreamsInvalidTopologyException(str);
+                    } else {
+                        return topicPartitionCount;
+                    }
+                }));
+
+        final int numPartitionsToUseForRepartitionTopics;
+        final Collection<ConfiguredInternalTopic> configuredInternalTopics = repartitionTopicConfigs.values();
+
+        if (copartitionedTopics.equals(repartitionTopicConfigs.keySet())) {
+            final Collection<ConfiguredInternalTopic> configuredConfiguredInternalTopicsWithEnforcedNumberOfPartitions =
+                configuredInternalTopics
+                    .stream()
+                    .filter(ConfiguredInternalTopic::hasEnforcedNumberOfPartitions)
+                    .collect(Collectors.toList());
+
+            // if there's at least one repartition topic with enforced number of partitions
+            // validate that they all have same number of partitions
+            if (!configuredConfiguredInternalTopicsWithEnforcedNumberOfPartitions.isEmpty()) {
+                numPartitionsToUseForRepartitionTopics = validateAndGetNumOfPartitions(
+                    repartitionTopicConfigs,
+                    configuredConfiguredInternalTopicsWithEnforcedNumberOfPartitions
+                );
+            } else {
+                // If all topics for this co-partition group are repartition topics,
+                // then set the number of partitions to be the maximum of the number of partitions.
+                numPartitionsToUseForRepartitionTopics = getMaxPartitions(repartitionTopicConfigs);
+            }
+        } else {
+            // Otherwise, use the number of partitions from external topics (which must all be the same)
+            numPartitionsToUseForRepartitionTopics = getSamePartitions(nonRepartitionTopicPartitions);
+        }
+
+        // coerce all the repartition topics to use the decided number of partitions.
+        for (final ConfiguredInternalTopic config : configuredInternalTopics) {
+            maybeSetNumberOfPartitionsForInternalTopic(numPartitionsToUseForRepartitionTopics, config);
+
+            final int numberOfPartitionsOfInternalTopic = config
+                .numberOfPartitions()
+                .orElseThrow(emptyNumberOfPartitionsExceptionSupplier(config.name()));
+
+            if (numberOfPartitionsOfInternalTopic != numPartitionsToUseForRepartitionTopics) {
+                final String msg = String.format("Number of partitions [%d] of repartition topic [%s] " +
+                        "doesn't match number of partitions [%d] of the source topic.",
+                    numberOfPartitionsOfInternalTopic,
+                    config.name(),
+                    numPartitionsToUseForRepartitionTopics);
+                throw new StreamsInconsistentInternalTopicsException(msg);
+            }
+        }
+    }
+
+    private int validateAndGetNumOfPartitions(final Map<Object, ConfiguredInternalTopic> repartitionTopicConfigs,
+                                              final Collection<ConfiguredInternalTopic> configuredInternalTopics) {
+        final ConfiguredInternalTopic firstConfiguredInternalTopic = configuredInternalTopics.iterator().next();
+
+        final int firstNumberOfPartitionsOfInternalTopic = firstConfiguredInternalTopic
+            .numberOfPartitions()
+            .orElseThrow(emptyNumberOfPartitionsExceptionSupplier(firstConfiguredInternalTopic.name()));
+
+        for (final ConfiguredInternalTopic configuredInternalTopic : configuredInternalTopics) {
+            final Integer numberOfPartitions = configuredInternalTopic
+                .numberOfPartitions()
+                .orElseThrow(emptyNumberOfPartitionsExceptionSupplier(configuredInternalTopic.name()));
+
+            if (numberOfPartitions != firstNumberOfPartitionsOfInternalTopic) {
+                final Map<Object, Integer> repartitionTopics = repartitionTopicConfigs
+                    .entrySet()
+                    .stream()
+                    .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().numberOfPartitions().get()));
+
+                final String msg = String.format("Following topics do not have the same number of partitions: [%s]",
+                    new TreeMap<>(repartitionTopics));
+                throw new StreamsInconsistentInternalTopicsException(msg);
+            }
+        }
+
+        return firstNumberOfPartitionsOfInternalTopic;
+    }
+
+    private int getSamePartitions(final Map<String, Integer> nonRepartitionTopicsInCopartitionGroup) {
+        final int partitions = nonRepartitionTopicsInCopartitionGroup.values().iterator().next();
+        for (final Entry<String, Integer> entry : nonRepartitionTopicsInCopartitionGroup.entrySet()) {
+            if (entry.getValue() != partitions) {
+                final TreeMap<String, Integer> sorted = new TreeMap<>(nonRepartitionTopicsInCopartitionGroup);
+                throw new StreamsInconsistentInternalTopicsException(
+                    String.format("Topics not co-partitioned: [%s]", sorted)
+                );
+            }
+        }
+        return partitions;
+    }
+
+    private int getMaxPartitions(final Map<Object, ConfiguredInternalTopic> repartitionTopicsInCopartitionGroup) {
+        int maxPartitions = 0;
+
+        for (final ConfiguredInternalTopic config : repartitionTopicsInCopartitionGroup.values()) {
+            final Optional<Integer> partitions = config.numberOfPartitions();
+            maxPartitions = Integer.max(maxPartitions, partitions.orElse(maxPartitions));
+        }
+        if (maxPartitions == 0) {
+            throw new StreamsInvalidTopologyException("All topics in the copartition group had undefined partition number: " +
+                repartitionTopicsInCopartitionGroup.keySet());
+        }
+        return maxPartitions;
+    }
+
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
new file mode 100644
index 00000000000..9485617261f
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
@@ -0,0 +1,231 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfig;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfigCollection;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.image.MetadataImage;
+import org.apache.kafka.image.TopicImage;
+
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class InternalTopicManager {
+
+    public static Map<String, CreatableTopic> missingTopics(Map<String, ConfiguredSubtopology> subtopologyMap,
+                                                            MetadataImage metadataImage) {
+
+        final Map<String, CreatableTopic> topicsToCreate = new HashMap<>();
+        for (ConfiguredSubtopology subtopology : subtopologyMap.values()) {
+            subtopology.repartitionSourceTopics().values()
+                .forEach(x -> topicsToCreate.put(x.name(), toCreatableTopic(x)));
+            subtopology.stateChangelogTopics().values()
+                .forEach(x -> topicsToCreate.put(x.name(), toCreatableTopic(x)));
+        }
+        // TODO: Validate if existing topics are compatible with the new topics
+        for (String topic : metadataImage.topics().topicsByName().keySet()) {
+            topicsToCreate.remove(topic);
+        }
+        return topicsToCreate;
+    }
+
+
+    public static Map<String, ConfiguredSubtopology> configureTopics(LogContext logContext,
+                                                                     List<StreamsGroupTopologyValue.Subtopology> subtopologyList,
+                                                                     MetadataImage metadataImage) {
+
+        final Logger log = logContext.logger(InternalTopicManager.class);
+
+        final Map<String, ConfiguredSubtopology> configuredSubtopologies =
+            subtopologyList.stream()
+                .collect(Collectors.toMap(
+                    StreamsGroupTopologyValue.Subtopology::subtopologyId,
+                    InternalTopicManager::fromPersistedSubtopology)
+                );
+
+        final Map<String, Collection<Set<String>>> copartitionGroupsBySubtopology =
+            subtopologyList.stream()
+                .collect(Collectors.toMap(
+                    StreamsGroupTopologyValue.Subtopology::subtopologyId,
+                    InternalTopicManager::copartitionGroupsFromPersistedSubtopology)
+                );
+
+        final Map<String, ConfiguredInternalTopic> configuredInternalTopics =
+            configuredSubtopologies.values().stream().flatMap(x ->
+                Stream.concat(
+                    x.repartitionSourceTopics().values().stream(),
+                    x.stateChangelogTopics().values().stream()
+                )
+            ).collect(Collectors.toMap(ConfiguredInternalTopic::name, x -> x));
+
+        final Function<String, Integer> topicPartitionCountProvider =
+            topic -> getPartitionCount(metadataImage, topic, configuredInternalTopics);
+
+        configureRepartitionTopics(logContext, configuredSubtopologies, topicPartitionCountProvider);
+        enforceCopartitioning(logContext, configuredSubtopologies, copartitionGroupsBySubtopology, topicPartitionCountProvider, log);
+        configureChangelogTopics(logContext, configuredSubtopologies, topicPartitionCountProvider);
+
+        return configuredSubtopologies;
+    }
+
+
+    private static void configureRepartitionTopics(LogContext logContext,
+                                                   Map<String, ConfiguredSubtopology> configuredSubtopologies,
+                                                   Function<String, Integer> topicPartitionCountProvider) {
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(logContext,
+            configuredSubtopologies,
+            topicPartitionCountProvider);
+        repartitionTopics.setup();
+    }
+
+    private static void enforceCopartitioning(LogContext logContext,
+                                              Map<String, ConfiguredSubtopology> configuredSubtopologies,
+                                              Map<String, Collection<Set<String>>> copartitionGroupsBySubtopology,
+                                              Function<String, Integer> topicPartitionCountProvider,
+                                              Logger log) {
+        final CopartitionedTopicsEnforcer copartitionedTopicsEnforcer = new CopartitionedTopicsEnforcer(
+            logContext, topicPartitionCountProvider);
+
+        final Map<String, ConfiguredInternalTopic> repartitionTopicConfigs =
+            configuredSubtopologies.values().stream().flatMap(x ->
+                x.repartitionSourceTopics().values().stream()
+            ).collect(Collectors.toMap(ConfiguredInternalTopic::name, x -> x));
+
+        if (repartitionTopicConfigs.isEmpty()) {
+            log.info("Skipping the repartition topic validation since there are no repartition topics.");
+        } else {
+            // ensure the co-partitioning topics within the group have the same number of partitions,
+            // and enforce the number of partitions for those repartition topics to be the same if they
+            // are co-partitioned as well.
+            for (Collection<Set<String>> copartitionGroups : copartitionGroupsBySubtopology.values()) {
+                for (Set<String> copartitionGroup : copartitionGroups) {
+                    copartitionedTopicsEnforcer.enforce(copartitionGroup, repartitionTopicConfigs);
+                }
+            }
+        }
+    }
+
+    private static void configureChangelogTopics(LogContext logContext,
+                                                 Map<String, ConfiguredSubtopology> configuredSubtopologies,
+                                                 Function<String, Integer> topicPartitionCountProvider) {
+        final ChangelogTopics changelogTopics = new ChangelogTopics(logContext,
+            configuredSubtopologies, topicPartitionCountProvider);
+        changelogTopics.setup();
+    }
+
+    private static Integer getPartitionCount(MetadataImage metadataImage,
+                                             String topic,
+                                             Map<String, ConfiguredInternalTopic> configuredInternalTopics) {
+        final TopicImage topicImage = metadataImage.topics().getTopic(topic);
+        if (topicImage == null) {
+            if (configuredInternalTopics.containsKey(topic) && configuredInternalTopics.get(topic).numberOfPartitions().isPresent()) {
+                return configuredInternalTopics.get(topic).numberOfPartitions().get();
+            } else {
+                return null;
+            }
+        } else {
+            return topicImage.partitions().size();
+        }
+    }
+
+    private static CreatableTopic toCreatableTopic(final ConfiguredInternalTopic config) {
+
+        final CreatableTopic creatableTopic = new CreatableTopic();
+
+        creatableTopic.setName(config.name());
+
+        if (!config.numberOfPartitions().isPresent()) {
+            throw new IllegalStateException(
+                "Number of partitions must be set for topic " + config.name());
+        } else {
+            creatableTopic.setNumPartitions(config.numberOfPartitions().get());
+        }
+
+        if (config.replicationFactor().isPresent() && config.replicationFactor().get() != 0) {
+            creatableTopic.setReplicationFactor(config.replicationFactor().get());
+        } else {
+            creatableTopic.setReplicationFactor((short) -1);
+        }
+
+        final CreatableTopicConfigCollection topicConfigs = new CreatableTopicConfigCollection();
+
+        config.topicConfigs().forEach((k, v) -> {
+            final CreatableTopicConfig topicConfig = new CreatableTopicConfig();
+            topicConfig.setName(k);
+            topicConfig.setValue(v);
+            topicConfigs.add(topicConfig);
+        });
+
+        creatableTopic.setConfigs(topicConfigs);
+
+        return creatableTopic;
+    }
+
+    private static ConfiguredSubtopology fromPersistedSubtopology(
+        final StreamsGroupTopologyValue.Subtopology subtopology) {
+        // TODO: Need to resolve regular expressions here.
+        return new ConfiguredSubtopology(
+            new HashSet<>(subtopology.repartitionSinkTopics()),
+            new HashSet<>(subtopology.sourceTopics()),
+            subtopology.repartitionSourceTopics().stream()
+                .map(InternalTopicManager::fromPersistedTopicInfo)
+                .collect(Collectors.toMap(ConfiguredInternalTopic::name, x -> x)),
+            subtopology.stateChangelogTopics().stream()
+                .map(InternalTopicManager::fromPersistedTopicInfo)
+                .collect(Collectors.toMap(ConfiguredInternalTopic::name, x -> x))
+        );
+    }
+
+    private static ConfiguredInternalTopic fromPersistedTopicInfo(
+        final StreamsGroupTopologyValue.TopicInfo topicInfo) {
+        return new ConfiguredInternalTopic(
+            topicInfo.name(),
+            topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+                .collect(Collectors.toMap(StreamsGroupTopologyValue.TopicConfig::key,
+                    StreamsGroupTopologyValue.TopicConfig::value))
+                : Collections.emptyMap(),
+            topicInfo.partitions() == 0 ? Optional.empty() : Optional.of(topicInfo.partitions()),
+            topicInfo.replicationFactor() == 0 ? Optional.empty()
+                : Optional.of(topicInfo.replicationFactor()));
+    }
+
+    private static Collection<Set<String>> copartitionGroupsFromPersistedSubtopology(
+        final StreamsGroupTopologyValue.Subtopology subtopology) {
+        return subtopology.copartitionGroups().stream().map(copartitionGroup ->
+            Stream.concat(
+                copartitionGroup.sourceTopics().stream()
+                    .map(i -> subtopology.sourceTopics().get(i)),
+                copartitionGroup.repartitionSourceTopics().stream()
+                    .map(i -> subtopology.repartitionSourceTopics().get(i).name())
+            ).collect(Collectors.toSet())
+        ).collect(Collectors.toList());
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopics.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopics.java
new file mode 100644
index 00000000000..022e7a3a5e6
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopics.java
@@ -0,0 +1,180 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * This class is responsible for configuring the number of partitions in repartitioning topics.
+ */
+public class RepartitionTopics {
+
+    private final Logger log;
+    private final Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology;
+    private final Function<String, Integer> topicPartitionCountProvider;
+
+    private final Map<String, Set<String>> missingInputTopicsBySubtopology = new HashMap<>();
+
+    public RepartitionTopics(final LogContext logContext,
+                             final Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology,
+                             final Function<String, Integer> topicPartitionCountProvider) {
+        this.log = logContext.logger(getClass());
+        this.subtopologyToConfiguredSubtopology = subtopologyToConfiguredSubtopology;
+        this.topicPartitionCountProvider = topicPartitionCountProvider;
+    }
+
+    /**
+     * Modifies the provided ConfiguredSubtopology to set the number of partitions for each repartition topic.
+     *
+     * @return the map of repartition topics for the requested topology that are internal and may need to be created.
+     */
+    public Map<String, ConfiguredInternalTopic> setup() {
+        final Set<String> missingSourceTopicsForTopology = new HashSet<>();
+        final Map<String, ConfiguredInternalTopic> configuredRepartitionTopics = new HashMap<>();
+
+        for (final Map.Entry<String, ConfiguredSubtopology> subtopologyEntry : subtopologyToConfiguredSubtopology.entrySet()) {
+            final ConfiguredSubtopology configuredSubtopology = subtopologyEntry.getValue();
+
+            configuredRepartitionTopics.putAll(
+                configuredSubtopology.repartitionSourceTopics()
+                    .values()
+                    .stream()
+                    .collect(Collectors.toMap(ConfiguredInternalTopic::name, topicConfig -> topicConfig)));
+
+            final Set<String> missingSourceTopicsForSubtopology = computeMissingExternalSourceTopics(configuredSubtopology);
+            missingSourceTopicsForTopology.addAll(missingSourceTopicsForSubtopology);
+            if (!missingSourceTopicsForSubtopology.isEmpty()) {
+                final String subtopologyId = subtopologyEntry.getKey();
+                missingInputTopicsBySubtopology.put(subtopologyId, missingSourceTopicsForSubtopology);
+                log.error("Subtopology {} has missing source topics {} and will be excluded from the current assignment, "
+                        + "this can be due to the consumer client's metadata being stale or because they have "
+                        + "not been created yet. Please verify that you have created all input topics; if they "
+                        + "do exist, you just need to wait for the metadata to be updated, at which time a new "
+                        + "rebalance will be kicked off automatically and the topology will be retried at that time.",
+                    subtopologyId, missingSourceTopicsForSubtopology);
+            }
+        }
+
+        if (missingSourceTopicsForTopology.isEmpty()) {
+            setRepartitionSourceTopicPartitionCount(configuredRepartitionTopics);
+            return configuredRepartitionTopics;
+        } else {
+            Set<String> missingSourceTopics = missingInputTopicsBySubtopology.values().stream()
+                .flatMap(Collection::stream)
+                .collect(Collectors.toSet());
+            throw new StreamsMissingSourceTopicsException(String.format("Missing source topics: %s",
+                String.join(", ", missingSourceTopics)));
+        }
+    }
+
+    private Set<String> computeMissingExternalSourceTopics(final ConfiguredSubtopology configuredSubtopology) {
+        final Set<String> missingExternalSourceTopics = new HashSet<>(configuredSubtopology.sourceTopics());
+        missingExternalSourceTopics.removeAll(configuredSubtopology.repartitionSourceTopics().keySet());
+        missingExternalSourceTopics.removeIf(x -> topicPartitionCountProvider.apply(x) != null);
+        return missingExternalSourceTopics;
+    }
+
+    /**
+     * Computes the number of partitions and sets it for each repartition topic in repartitionTopicMetadata
+     */
+    private void setRepartitionSourceTopicPartitionCount(final Map<String, ConfiguredInternalTopic> repartitionTopicMetadata) {
+        boolean partitionCountNeeded;
+        do {
+            partitionCountNeeded = false;
+            // avoid infinitely looping without making any progress on unknown repartitions
+            boolean progressMadeThisIteration = false;
+
+            for (final ConfiguredSubtopology configuredSubtopology : subtopologyToConfiguredSubtopology.values()) {
+                for (final String repartitionSourceTopic : configuredSubtopology.repartitionSourceTopics()
+                    .keySet()) {
+                    final Optional<Integer> repartitionSourceTopicPartitionCount =
+                        repartitionTopicMetadata.get(repartitionSourceTopic).numberOfPartitions();
+
+                    if (!repartitionSourceTopicPartitionCount.isPresent()) {
+                        final Integer numPartitions = computePartitionCount(
+                            repartitionTopicMetadata,
+                            repartitionSourceTopic
+                        );
+
+                        if (numPartitions == null) {
+                            partitionCountNeeded = true;
+                            log.trace("Unable to determine number of partitions for {}, another iteration is needed",
+                                repartitionSourceTopic);
+                        } else {
+                            log.trace("Determined number of partitions for {} to be {}",
+                                repartitionSourceTopic,
+                                numPartitions);
+                            repartitionTopicMetadata.get(repartitionSourceTopic).setNumberOfPartitions(numPartitions);
+                            progressMadeThisIteration = true;
+                        }
+                    }
+                }
+            }
+            if (!progressMadeThisIteration && partitionCountNeeded) {
+                throw new StreamsMissingSourceTopicsException("Failed to compute number of partitions for all " +
+                    "repartition topics, make sure all user input topics are created and all pattern subscriptions " +
+                    "match at least one topic in the cluster");
+            }
+        } while (partitionCountNeeded);
+    }
+
+    private Integer computePartitionCount(final Map<String, ConfiguredInternalTopic> repartitionTopicMetadata,
+                                          final String repartitionSourceTopic) {
+        Integer partitionCount = null;
+        // try set the number of partitions for this repartition topic if it is not set yet
+        for (final ConfiguredSubtopology configuredSubtopology : subtopologyToConfiguredSubtopology.values()) {
+            final Set<String> repartitionSinkTopics = configuredSubtopology.repartitionSinkTopics();
+
+            if (repartitionSinkTopics.contains(repartitionSourceTopic)) {
+                // if this topic is one of the sink topics of this topology,
+                // use the maximum of all its source topic partitions as the number of partitions
+                for (final String upstreamSourceTopic : configuredSubtopology.sourceTopics()) {
+                    Integer numPartitionsCandidate = null;
+                    // It is possible the sourceTopic is another internal topic, i.e,
+                    // map().join().join(map())
+                    if (repartitionTopicMetadata.containsKey(upstreamSourceTopic)) {
+                        if (repartitionTopicMetadata.get(upstreamSourceTopic).numberOfPartitions().isPresent()) {
+                            numPartitionsCandidate =
+                                repartitionTopicMetadata.get(upstreamSourceTopic).numberOfPartitions().get();
+                        }
+                    } else {
+                        numPartitionsCandidate = topicPartitionCountProvider.apply(upstreamSourceTopic);
+                    }
+
+                    if (numPartitionsCandidate != null) {
+                        if (partitionCount == null || numPartitionsCandidate > partitionCount) {
+                            partitionCount = numPartitionsCandidate;
+                        }
+                    }
+                }
+            }
+        }
+        return partitionCount;
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopicsTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopicsTest.java
new file mode 100644
index 00000000000..19584c53fef
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ChangelogTopicsTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ChangelogTopicsTest {
+
+    private static final LogContext LOG_CONTEXT = new LogContext();
+    private static final String SOURCE_TOPIC_NAME = "source";
+    private static final String SINK_TOPIC_NAME = "sink";
+    private static final String REPARTITION_TOPIC_NAME = "repartition";
+    private static final String CHANGELOG_TOPIC_NAME1 = "changelog1";
+    private static final Map<String, String> TOPIC_CONFIG = Collections.singletonMap("config1", "val1");
+    private static final ConfiguredInternalTopic REPARTITION_TOPIC_CONFIG =
+        new ConfiguredInternalTopic(REPARTITION_TOPIC_NAME, TOPIC_CONFIG);
+    private static final ConfiguredSubtopology TOPICS_INFO_NOSOURCE = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME),
+        Collections.emptySet(),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME, REPARTITION_TOPIC_CONFIG)),
+        mkMap()
+    );
+    private static final ConfiguredSubtopology TOPICS_INFO_STATELESS = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME),
+        Collections.singleton(SOURCE_TOPIC_NAME),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME, REPARTITION_TOPIC_CONFIG)),
+        mkMap()
+    );
+    private static final ConfiguredInternalTopic CHANGELOG_TOPIC_CONFIG =
+        new ConfiguredInternalTopic(CHANGELOG_TOPIC_NAME1, TOPIC_CONFIG);
+    private static final ConfiguredSubtopology TOPICS_INFO_STATEFUL = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME),
+        Collections.singleton(SOURCE_TOPIC_NAME),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME, REPARTITION_TOPIC_CONFIG)),
+        mkMap(mkEntry(CHANGELOG_TOPIC_NAME1, CHANGELOG_TOPIC_CONFIG))
+    );
+    private static final ConfiguredSubtopology TOPICS_INFO_SOURCE_CHANGELOG = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME),
+        Collections.singleton(SOURCE_TOPIC_NAME),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME, REPARTITION_TOPIC_CONFIG)),
+        mkMap(mkEntry(SOURCE_TOPIC_NAME, CHANGELOG_TOPIC_CONFIG))
+    );
+    private static final ConfiguredSubtopology TOPICS_INFO_BOTH = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME),
+        Collections.singleton(SOURCE_TOPIC_NAME),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME, REPARTITION_TOPIC_CONFIG)),
+        mkMap(mkEntry(SOURCE_TOPIC_NAME, null), mkEntry(CHANGELOG_TOPIC_NAME1, CHANGELOG_TOPIC_CONFIG))
+    );
+
+    private static Integer topicPartitionProvider(String s) {
+        return 3;
+    }
+
+    @Test
+    public void shouldFailIfNoSourceTopics() {
+        final Map<String, ConfiguredSubtopology> subtopologies = mkMap(mkEntry("subtopology_0", TOPICS_INFO_NOSOURCE));
+
+        final ChangelogTopics changelogTopics =
+            new ChangelogTopics(LOG_CONTEXT, subtopologies, ChangelogTopicsTest::topicPartitionProvider);
+        StreamsInvalidTopologyException e = assertThrows(StreamsInvalidTopologyException.class, () -> changelogTopics.setup());
+
+        assertTrue(e.getMessage().contains("No source topics found for subtopology"));
+    }
+
+    @Test
+    public void shouldNotContainChangelogsForStatelessTasks() {
+        final Map<String, ConfiguredSubtopology> subtopologies = mkMap(mkEntry("subtopology_0", TOPICS_INFO_STATELESS));
+
+        final ChangelogTopics changelogTopics =
+            new ChangelogTopics(LOG_CONTEXT, subtopologies, ChangelogTopicsTest::topicPartitionProvider);
+        Map<String, ConfiguredInternalTopic> setup = changelogTopics.setup();
+
+        assertEquals(Collections.emptyMap(), setup);
+    }
+
+    @Test
+    public void shouldContainNonSourceBasedChangelogs() {
+        final Map<String, ConfiguredSubtopology> subtopologies = mkMap(mkEntry("subtopology_0", TOPICS_INFO_STATEFUL));
+
+        final ChangelogTopics changelogTopics =
+            new ChangelogTopics(LOG_CONTEXT, subtopologies, ChangelogTopicsTest::topicPartitionProvider);
+        Map<String, ConfiguredInternalTopic> setup = changelogTopics.setup();
+
+        assertEquals(mkMap(mkEntry(CHANGELOG_TOPIC_NAME1, CHANGELOG_TOPIC_CONFIG)), setup);
+        assertEquals(3, CHANGELOG_TOPIC_CONFIG.numberOfPartitions().orElse(Integer.MIN_VALUE));
+    }
+
+    @Test
+    public void shouldNotContainSourceBasedChangelogs() {
+        final Map<String, ConfiguredSubtopology> subtopologies = mkMap(mkEntry("subtopology_0", TOPICS_INFO_SOURCE_CHANGELOG));
+
+        final ChangelogTopics changelogTopics =
+            new ChangelogTopics(LOG_CONTEXT, subtopologies, ChangelogTopicsTest::topicPartitionProvider);
+        Map<String, ConfiguredInternalTopic> setup = changelogTopics.setup();
+
+        assertEquals(Collections.emptyMap(), setup);
+    }
+
+    @Test
+    public void shouldContainBothTypesOfPreExistingChangelogs() {
+        final Map<String, ConfiguredSubtopology> subtopologies = mkMap(mkEntry("subtopology_0", TOPICS_INFO_BOTH));
+
+        final ChangelogTopics changelogTopics =
+            new ChangelogTopics(LOG_CONTEXT, subtopologies, ChangelogTopicsTest::topicPartitionProvider);
+        Map<String, ConfiguredInternalTopic> setup = changelogTopics.setup();
+
+        assertEquals(mkMap(mkEntry(CHANGELOG_TOPIC_NAME1, CHANGELOG_TOPIC_CONFIG)), setup);
+        assertEquals(3, CHANGELOG_TOPIC_CONFIG.numberOfPartitions().orElse(Integer.MIN_VALUE));
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopicTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopicTest.java
new file mode 100644
index 00000000000..12c8adb0a3b
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredInternalTopicTest.java
@@ -0,0 +1,104 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.InvalidTopicException;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class ConfiguredInternalTopicTest {
+
+    @Test
+    public void testConstructorAndGetters() {
+        Map<String, String> topicConfigs = new HashMap<>();
+        topicConfigs.put("retention.ms", "1000");
+        topicConfigs.put("message.timestamp.type", "LogAppendTime");
+
+        ConfiguredInternalTopic config = new ConfiguredInternalTopic("test-topic", topicConfigs, Optional.of(3), Optional.of((short) 2));
+
+        assertEquals("test-topic", config.name());
+        assertEquals(topicConfigs, config.topicConfigs());
+        assertEquals(Optional.of(3), config.numberOfPartitions());
+        assertEquals(Optional.of((short) 2), config.replicationFactor());
+    }
+
+    @Test
+    public void testConstructorWithNullName() {
+        assertThrows(NullPointerException.class, () -> new ConfiguredInternalTopic(null, Collections.emptyMap()));
+    }
+
+    @Test
+    public void testConstructorWithInvalidName() {
+        assertThrows(InvalidTopicException.class, () -> new ConfiguredInternalTopic("invalid topic name", Collections.emptyMap()));
+    }
+
+    @Test
+    public void testConstructorWithNullTopicConfigs() {
+        assertThrows(NullPointerException.class, () -> new ConfiguredInternalTopic("test-topic", null));
+    }
+
+    @Test
+    public void testSetNumberOfPartitions() {
+        ConfiguredInternalTopic config = new ConfiguredInternalTopic("test-topic", Collections.emptyMap());
+        config.setNumberOfPartitions(3);
+        assertEquals(Optional.of(3), config.numberOfPartitions());
+    }
+
+    @Test
+    public void testSetNumberOfPartitionsInvalid() {
+        ConfiguredInternalTopic config = new ConfiguredInternalTopic("test-topic", Collections.emptyMap());
+        assertThrows(IllegalArgumentException.class, () -> config.setNumberOfPartitions(0));
+    }
+
+    @Test
+    public void testSetNumberOfPartitionsUnsupportedOperation() {
+        ConfiguredInternalTopic config = new ConfiguredInternalTopic("test-topic", Collections.emptyMap(), Optional.of(3),
+            Optional.empty());
+        assertThrows(UnsupportedOperationException.class, () -> config.setNumberOfPartitions(4));
+    }
+
+    @Test
+    public void testEqualsAndHashCode() {
+        Map<String, String> topicConfigs = new HashMap<>();
+        topicConfigs.put("retention.ms", "1000");
+
+        ConfiguredInternalTopic config1 = new ConfiguredInternalTopic("test-topic", topicConfigs, Optional.of(3), Optional.of((short) 2));
+        ConfiguredInternalTopic config2 = new ConfiguredInternalTopic("test-topic", topicConfigs, Optional.of(3), Optional.of((short) 2));
+
+        assertEquals(config1, config2);
+        assertEquals(config1.hashCode(), config2.hashCode());
+    }
+
+    @Test
+    public void testToString() {
+        Map<String, String> topicConfigs = new HashMap<>();
+        topicConfigs.put("retention.ms", "1000");
+
+        ConfiguredInternalTopic config = new ConfiguredInternalTopic("test-topic", topicConfigs, Optional.of(3), Optional.of((short) 2));
+        String expectedString = "ConfiguredInternalTopic(name=test-topic, topicConfigs={retention.ms=1000}, numberOfPartitions=Optional[3], replicationFactor=Optional[2], enforceNumberOfPartitions=true)";
+
+        assertEquals(expectedString, config.toString());
+    }
+}
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopologyTest.java
new file mode 100644
index 00000000000..71d05ce3d2a
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/ConfiguredSubtopologyTest.java
@@ -0,0 +1,137 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ConfiguredSubtopologyTest {
+
+    @Test
+    public void testConstructorAndGetters() {
+        Set<String> repartitionSinkTopics = Set.of("repartitionSinkTopic1", "repartitionSinkTopic2");
+        Set<String> sourceTopics = Set.of("sourceTopic1", "sourceTopic2");
+        Map<String, ConfiguredInternalTopic> repartitionSourceTopics = new HashMap<>();
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+
+        ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+
+        assertEquals(repartitionSinkTopics, configuredSubtopology.repartitionSinkTopics());
+        assertEquals(sourceTopics, configuredSubtopology.sourceTopics());
+        assertEquals(repartitionSourceTopics, configuredSubtopology.repartitionSourceTopics());
+        assertEquals(stateChangelogTopics, configuredSubtopology.stateChangelogTopics());
+    }
+
+    @Test
+    public void testSetters() {
+        ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology();
+
+        Set<String> repartitionSinkTopics = Set.of("repartitionSinkTopic1", "repartitionSinkTopic2");
+        configuredSubtopology.setRepartitionSinkTopics(repartitionSinkTopics);
+        assertEquals(repartitionSinkTopics, configuredSubtopology.repartitionSinkTopics());
+
+        Set<String> sourceTopics = Set.of("sourceTopic1", "sourceTopic2");
+        configuredSubtopology.setSourceTopics(sourceTopics);
+        assertEquals(sourceTopics, configuredSubtopology.sourceTopics());
+
+        Map<String, ConfiguredInternalTopic> repartitionSourceTopics = new HashMap<>();
+        configuredSubtopology.setRepartitionSourceTopics(repartitionSourceTopics);
+        assertEquals(repartitionSourceTopics, configuredSubtopology.repartitionSourceTopics());
+
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+        configuredSubtopology.setStateChangelogTopics(stateChangelogTopics);
+        assertEquals(stateChangelogTopics, configuredSubtopology.stateChangelogTopics());
+    }
+
+    @Test
+    public void testNonSourceChangelogTopics() {
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+        stateChangelogTopics.put("changelogTopic1", new ConfiguredInternalTopic("changelogTopic1"));
+        stateChangelogTopics.put("sourceTopic1", new ConfiguredInternalTopic("sourceTopic1"));
+
+        ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(
+            Collections.emptySet(),
+            Collections.singleton("sourceTopic1"),
+            Collections.emptyMap(),
+            stateChangelogTopics
+        );
+
+        Set<ConfiguredInternalTopic> nonSourceChangelogTopics = configuredSubtopology.nonSourceChangelogTopics();
+        assertEquals(1, nonSourceChangelogTopics.size());
+        assertTrue(nonSourceChangelogTopics.contains(new ConfiguredInternalTopic("changelogTopic1")));
+    }
+
+    @Test
+    public void testEquals() {
+        Set<String> repartitionSinkTopics = new HashSet<>(Arrays.asList("repartitionSinkTopic1", "repartitionSinkTopic2"));
+        Set<String> sourceTopics = new HashSet<>(Arrays.asList("sourceTopic1", "sourceTopic2"));
+        Map<String, ConfiguredInternalTopic> repartitionSourceTopics = new HashMap<>();
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+
+        ConfiguredSubtopology configuredSubtopology1 = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+        ConfiguredSubtopology configuredSubtopology2 = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+
+        assertEquals(configuredSubtopology1, configuredSubtopology2);
+    }
+
+    @Test
+    public void testHashCode() {
+        Set<String> repartitionSinkTopics = new HashSet<>(Arrays.asList("repartitionSinkTopic1", "repartitionSinkTopic2"));
+        Set<String> sourceTopics = new HashSet<>(Arrays.asList("sourceTopic1", "sourceTopic2"));
+        Map<String, ConfiguredInternalTopic> repartitionSourceTopics = new HashMap<>();
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+
+        ConfiguredSubtopology configuredSubtopology1 = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+        ConfiguredSubtopology configuredSubtopology2 = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+
+        assertEquals(configuredSubtopology1.hashCode(), configuredSubtopology2.hashCode());
+    }
+
+    @Test
+    public void testToString() {
+        Set<String> repartitionSinkTopics = new HashSet<>(Arrays.asList("repartitionSinkTopic1", "repartitionSinkTopic2"));
+        Set<String> sourceTopics = new HashSet<>(Arrays.asList("sourceTopic1", "sourceTopic2"));
+        Map<String, ConfiguredInternalTopic> repartitionSourceTopics = new HashMap<>();
+        Map<String, ConfiguredInternalTopic> stateChangelogTopics = new HashMap<>();
+
+        ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(repartitionSinkTopics, sourceTopics,
+            repartitionSourceTopics, stateChangelogTopics);
+
+        String expectedString = "ConfiguredSubtopology{" +
+            "repartitionSinkTopics=" + repartitionSinkTopics +
+            ", sourceTopics=" + sourceTopics +
+            ", stateChangelogTopics=" + stateChangelogTopics +
+            ", repartitionSourceTopics=" + repartitionSourceTopics +
+            '}';
+
+        assertEquals(expectedString, configuredSubtopology.toString());
+    }
+}
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcerTest.java
new file mode 100644
index 00000000000..1e476247c49
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/CopartitionedTopicsEnforcerTest.java
@@ -0,0 +1,230 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsInconsistentInternalTopicsException;
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Utils;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@SuppressWarnings("OptionalGetWithoutIsPresent")
+public class CopartitionedTopicsEnforcerTest {
+
+    private static final LogContext LOG_CONTEXT = new LogContext();
+
+    private static Integer emptyTopicPartitionProvider(String topic) {
+        return null;
+    }
+
+    private static Integer firstSecondTopicConsistent(String topic) {
+        if (topic.equals("first") || topic.equals("second")) {
+            return 2;
+        }
+        return null;
+    }
+
+    private static Integer firstSecondTopicInconsistent(String topic) {
+        if (topic.equals("first")) {
+            return 2;
+        }
+        if (topic.equals("second")) {
+            return 1;
+        }
+        return null;
+    }
+
+    @Test
+    public void shouldThrowStreamsInconsistentInternalTopicsExceptionIfNoPartitionsFoundForCoPartitionedTopic() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::emptyTopicPartitionProvider);
+        assertThrows(StreamsInvalidTopologyException.class, () -> validator.enforce(Collections.singleton("topic"),
+            Collections.emptyMap()));
+    }
+
+    @Test
+    public void shouldThrowStreamsInconsistentInternalTopicsExceptionIfPartitionCountsForCoPartitionedTopicsDontMatch() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicInconsistent);
+        assertThrows(StreamsInconsistentInternalTopicsException.class, () -> validator.enforce(Set.of("first", "second"),
+            Collections.emptyMap()));
+    }
+
+
+    @Test
+    public void shouldEnforceCopartitioningOnRepartitionTopics() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic config = createTopicConfig("repartitioned", 10);
+
+        validator.enforce(Set.of("first", "second", config.name()),
+            Collections.singletonMap(config.name(), config));
+
+        assertEquals(Optional.of(2), config.numberOfPartitions());
+    }
+
+
+    @Test
+    public void shouldSetNumPartitionsToMaximumPartitionsWhenAllTopicsAreRepartitionTopics() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::emptyTopicPartitionProvider);
+        final ConfiguredInternalTopic one = createTopicConfig("one", 1);
+        final ConfiguredInternalTopic two = createTopicConfig("two", 15);
+        final ConfiguredInternalTopic three = createTopicConfig("three", 5);
+        final Map<String, ConfiguredInternalTopic> configuredInternalTopics = new HashMap<>();
+
+        configuredInternalTopics.put(one.name(), one);
+        configuredInternalTopics.put(two.name(), two);
+        configuredInternalTopics.put(three.name(), three);
+
+        validator.enforce(Set.of(
+                one.name(),
+                two.name(),
+                three.name()
+            ),
+            configuredInternalTopics
+        );
+
+        assertEquals(Optional.of(15), one.numberOfPartitions());
+        assertEquals(Optional.of(15), two.numberOfPartitions());
+        assertEquals(Optional.of(15), three.numberOfPartitions());
+    }
+
+    @Test
+    public void shouldThrowAnExceptionIfConfiguredInternalTopicsWithEnforcedNumOfPartitionsHaveDifferentNumOfPartitions() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic topic1 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-1", 10);
+        final ConfiguredInternalTopic topic2 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-2", 5);
+
+        final StreamsInconsistentInternalTopicsException ex = assertThrows(
+            StreamsInconsistentInternalTopicsException.class,
+            () -> validator.enforce(Set.of(topic1.name(), topic2.name()),
+                Utils.mkMap(
+                    Utils.mkEntry(topic1.name(), topic1),
+                    Utils.mkEntry(topic2.name(), topic2)
+                )
+            )
+        );
+
+        final TreeMap<String, Integer> sorted = new TreeMap<>(
+            Utils.mkMap(Utils.mkEntry(topic1.name(), topic1.numberOfPartitions().get()),
+                Utils.mkEntry(topic2.name(), topic2.numberOfPartitions().get()))
+        );
+
+        assertEquals(String.format(
+            "Following topics do not have the same number of partitions: " +
+                "[%s]", sorted), ex.getMessage());
+    }
+
+    @Test
+    public void shouldNotThrowAnExceptionWhenConfiguredInternalTopicsWithEnforcedNumOfPartitionsAreValid() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic topic1 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-1", 10);
+        final ConfiguredInternalTopic topic2 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-2", 10);
+
+        validator.enforce(Set.of(topic1.name(), topic2.name()),
+            Utils.mkMap(
+                Utils.mkEntry(topic1.name(), topic1),
+                Utils.mkEntry(topic2.name(), topic2)
+            )
+        );
+
+        assertEquals(Optional.of(10), topic1.numberOfPartitions());
+        assertEquals(Optional.of(10), topic2.numberOfPartitions());
+    }
+
+    @Test
+    public void shouldThrowAnExceptionWhenNumberOfPartitionsOfNonRepartitionTopicAndRepartitionTopicWithEnforcedNumOfPartitionsDoNotMatch() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic topic1 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-1", 10);
+
+        final StreamsInconsistentInternalTopicsException ex = assertThrows(
+            StreamsInconsistentInternalTopicsException.class,
+            () -> validator.enforce(Set.of(topic1.name(), "second"),
+                Utils.mkMap(Utils.mkEntry(topic1.name(), topic1)))
+        );
+
+        assertEquals(String.format("Number of partitions [%s] " +
+                "of repartition topic [%s] " +
+                "doesn't match number of partitions [%s] of the source topic.",
+            topic1.numberOfPartitions().get(), topic1.name(), 2), ex.getMessage());
+    }
+
+    @Test
+    public void shouldNotThrowAnExceptionWhenNumberOfPartitionsOfNonRepartitionTopicAndRepartitionTopicWithEnforcedNumOfPartitionsMatch() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic topic1 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-1", 2);
+
+        validator.enforce(Set.of(topic1.name(), "second"),
+            Utils.mkMap(Utils.mkEntry(topic1.name(), topic1)));
+
+        assertEquals(Optional.of(2), topic1.numberOfPartitions());
+    }
+
+    @Test
+    public void shouldDeductNumberOfPartitionsFromRepartitionTopicWithEnforcedNumberOfPartitions() {
+        final CopartitionedTopicsEnforcer validator = new CopartitionedTopicsEnforcer(LOG_CONTEXT,
+            CopartitionedTopicsEnforcerTest::firstSecondTopicConsistent);
+        final ConfiguredInternalTopic topic1 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-1", 2);
+        final ConfiguredInternalTopic topic2 = createTopicConfig("repartitioned-2", 5);
+        final ConfiguredInternalTopic topic3 = createConfiguredInternalTopicWithEnforcedNumberOfPartitions("repartitioned-3", 2);
+
+        validator.enforce(Set.of(topic1.name(), topic2.name()),
+            Utils.mkMap(
+                Utils.mkEntry(topic1.name(), topic1),
+                Utils.mkEntry(topic2.name(), topic2),
+                Utils.mkEntry(topic3.name(), topic3)
+            )
+        );
+
+        assertEquals(topic1.numberOfPartitions(), topic2.numberOfPartitions());
+        assertEquals(topic2.numberOfPartitions(), topic3.numberOfPartitions());
+    }
+
+    private ConfiguredInternalTopic createTopicConfig(final String repartitionTopic,
+                                                      final int partitions) {
+        final ConfiguredInternalTopic config =
+            new ConfiguredInternalTopic(repartitionTopic, Collections.emptyMap());
+
+        config.setNumberOfPartitions(partitions);
+        return config;
+    }
+
+    private ConfiguredInternalTopic createConfiguredInternalTopicWithEnforcedNumberOfPartitions(final String repartitionTopic,
+                                                                                                final int partitions) {
+        return new ConfiguredInternalTopic(repartitionTopic,
+            Collections.emptyMap(),
+            Optional.of(partitions),
+            Optional.empty());
+    }
+
+}
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
new file mode 100644
index 00000000000..e6ef6fee5d3
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
@@ -0,0 +1,178 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfig;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfigCollection;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+import org.apache.kafka.image.MetadataImage;
+import org.apache.kafka.image.TopicImage;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.server.immutable.ImmutableMap;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class InternalTopicManagerTest {
+
+    @Test
+    void testMissingTopics() {
+        MetadataImage metadataImage = mock(MetadataImage.class);
+        TopicsImage topicsImage = mock(TopicsImage.class);
+        when(metadataImage.topics()).thenReturn(topicsImage);
+        final TopicImage sourceTopic1 =
+            new TopicImage("source_topic1", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null)));
+        final TopicImage sourceTopic2 =
+            new TopicImage("source_topic2", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null)));
+        final TopicImage stateChangelogTopic2 = new TopicImage("state_changelog_topic2", Uuid.randomUuid(),
+            mkMap(mkEntry(0, null), mkEntry(1, null)));
+        when(topicsImage.topicsByName()).thenReturn(
+            ImmutableMap.singleton("source_topic1", sourceTopic1)
+                .updated("source_topic2", sourceTopic2)
+                .updated("state_changelog_topic2", stateChangelogTopic2)
+        );
+        when(topicsImage.getTopic(eq("source_topic1"))).thenReturn(sourceTopic1);
+        when(topicsImage.getTopic(eq("source_topic2"))).thenReturn(sourceTopic2);
+        when(topicsImage.getTopic(eq("state_changelog_topic2"))).thenReturn(stateChangelogTopic2);
+        Map<String, ConfiguredSubtopology> subtopologyMap = makeExpectedConfiguredTopology();
+
+        Map<String, CreatableTopic> missingTopics = InternalTopicManager.missingTopics(subtopologyMap, metadataImage);
+
+        assertEquals(2, missingTopics.size());
+        assertEquals(
+            new CreatableTopic()
+                .setName("repartition_topic")
+                .setNumPartitions(2)
+                .setReplicationFactor((short) 3),
+            missingTopics.get("repartition_topic")
+        );
+        assertEquals(
+            new CreatableTopic()
+                .setName("state_changelog_topic1")
+                .setNumPartitions(2)
+                .setReplicationFactor((short) -1)
+                .setConfigs(
+                    new CreatableTopicConfigCollection(
+                        Collections.singletonList(new CreatableTopicConfig().setName("cleanup.policy").setValue("compact")).iterator())
+                ),
+            missingTopics.get("state_changelog_topic1"));
+    }
+
+    @Test
+    void testConfigureTopics() {
+        MetadataImage metadataImage = mock(MetadataImage.class);
+        TopicsImage topicsImage = mock(TopicsImage.class);
+        when(metadataImage.topics()).thenReturn(topicsImage);
+        when(topicsImage.getTopic(eq("source_topic1"))).thenReturn(
+            new TopicImage("source_topic1", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null))));
+        when(topicsImage.getTopic(eq("source_topic2"))).thenReturn(
+            new TopicImage("source_topic2", Uuid.randomUuid(), mkMap(mkEntry(0, null), mkEntry(1, null))));
+        List<Subtopology> subtopologyList = makeTestTopology();
+
+        Map<String, ConfiguredSubtopology> configuredSubtopologies =
+            InternalTopicManager.configureTopics(new LogContext(), subtopologyList, metadataImage);
+
+        Map<String, ConfiguredSubtopology> expectedConfiguredSubtopologyMap = makeExpectedConfiguredTopology();
+        assertEquals(expectedConfiguredSubtopologyMap, configuredSubtopologies);
+    }
+
+    private static Map<String, ConfiguredSubtopology> makeExpectedConfiguredTopology() {
+        return mkMap(
+            mkEntry("subtopology1",
+                new ConfiguredSubtopology()
+                    .setSourceTopics(Set.of("source_topic1"))
+                    .setStateChangelogTopics(Collections.singletonMap("state_changelog_topic1",
+                        new ConfiguredInternalTopic("state_changelog_topic1",
+                            Collections.singletonMap("cleanup.policy", "compact"),
+                            Optional.empty(),
+                            Optional.empty()
+                        ).setNumberOfPartitions(2)))
+                    .setRepartitionSinkTopics(Set.of("repartition_topic"))
+            ),
+            mkEntry("subtopology2",
+                new ConfiguredSubtopology()
+                    .setSourceTopics(Set.of("source_topic2"))
+                    .setRepartitionSourceTopics(Collections.singletonMap("repartition_topic",
+                        new ConfiguredInternalTopic("repartition_topic",
+                            Collections.emptyMap(),
+                            Optional.empty(),
+                            Optional.of((short) 3)
+                        ).setNumberOfPartitions(2)
+                    ))
+                    .setStateChangelogTopics(Collections.singletonMap("state_changelog_topic2",
+                        new ConfiguredInternalTopic("state_changelog_topic2",
+                            Collections.emptyMap(),
+                            Optional.empty(),
+                            Optional.empty()
+                        ).setNumberOfPartitions(2)))
+            )
+        );
+    }
+
+    private static List<Subtopology> makeTestTopology() {
+        // Create a subtopology source -> repartition
+        Subtopology subtopology1 = new Subtopology()
+            .setSubtopologyId("subtopology1")
+            .setSourceTopics(Collections.singletonList("source_topic1"))
+            .setRepartitionSinkTopics(Collections.singletonList("repartition_topic"))
+            .setStateChangelogTopics(Collections.singletonList(
+                new StreamsGroupTopologyValue.TopicInfo()
+                    .setName("state_changelog_topic1")
+                    .setTopicConfigs(Collections.singletonList(
+                        new StreamsGroupTopologyValue.TopicConfig()
+                            .setKey("cleanup.policy")
+                            .setValue("compact")
+                    ))
+            ));
+        // Create a subtopology repartition/source2 -> sink (copartitioned)
+        Subtopology subtopology2 = new Subtopology()
+            .setSubtopologyId("subtopology2")
+            .setSourceTopics(Collections.singletonList("source_topic2"))
+            .setRepartitionSourceTopics(Collections.singletonList(
+                new StreamsGroupTopologyValue.TopicInfo()
+                    .setName("repartition_topic")
+                    .setReplicationFactor((short) 3)
+            ))
+            .setStateChangelogTopics(Collections.singletonList(
+                new StreamsGroupTopologyValue.TopicInfo()
+                    .setName("state_changelog_topic2")
+            ))
+            .setCopartitionGroups(Collections.singletonList(
+                new StreamsGroupTopologyValue.CopartitionGroup()
+                    .setSourceTopics(Collections.singletonList((short) 0))
+                    .setRepartitionSourceTopics(Collections.singletonList((short) 0))
+            ));
+        return Arrays.asList(subtopology1, subtopology2);
+    }
+
+}
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopicsTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopicsTest.java
new file mode 100644
index 00000000000..54f91508d2d
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/RepartitionTopicsTest.java
@@ -0,0 +1,239 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams.topics;
+
+import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Function;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class RepartitionTopicsTest {
+
+    private static final LogContext LOG_CONTEXT = new LogContext();
+    private static final String SOURCE_TOPIC_NAME1 = "source1";
+    private static final String SOURCE_TOPIC_NAME2 = "source2";
+    private static final String SINK_TOPIC_NAME1 = "sink1";
+    private static final String SINK_TOPIC_NAME2 = "sink2";
+    private static final String REPARTITION_TOPIC_NAME1 = "repartition1";
+    private static final String REPARTITION_TOPIC_NAME2 = "repartition2";
+    private static final String REPARTITION_WITHOUT_PARTITION_COUNT = "repartitionWithoutPartitionCount";
+    private static final Map<String, String> TOPIC_CONFIG1 = Collections.singletonMap("config1", "val1");
+    private static final Map<String, String> TOPIC_CONFIG2 = Collections.singletonMap("config2", "val2");
+    private static final Map<String, String> TOPIC_CONFIG5 = Collections.singletonMap("config5", "val5");
+    private static final ConfiguredInternalTopic REPARTITION_TOPIC_CONFIG1 =
+        new ConfiguredInternalTopic(REPARTITION_TOPIC_NAME1, TOPIC_CONFIG1, Optional.of(4), Optional.empty());
+    private static final ConfiguredInternalTopic REPARTITION_TOPIC_CONFIG2 =
+        new ConfiguredInternalTopic(REPARTITION_TOPIC_NAME2, TOPIC_CONFIG2, Optional.of(2), Optional.empty());
+    private static final ConfiguredInternalTopic REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT =
+        new ConfiguredInternalTopic(REPARTITION_WITHOUT_PARTITION_COUNT, TOPIC_CONFIG5);
+    private static final ConfiguredSubtopology TOPICS_INFO_WITHOUT_PARTITION_COUNT = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME2),
+        Set.of(REPARTITION_TOPIC_NAME1, REPARTITION_WITHOUT_PARTITION_COUNT),
+        mkMap(
+            mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+            mkEntry(REPARTITION_WITHOUT_PARTITION_COUNT, REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT)
+        ),
+        Collections.emptyMap()
+    );
+    private static final ConfiguredSubtopology TOPICS_INFO1 = new ConfiguredSubtopology(
+        Collections.singleton(REPARTITION_TOPIC_NAME1),
+        Set.of(SOURCE_TOPIC_NAME1, SOURCE_TOPIC_NAME2),
+        mkMap(
+            mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+            mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2)
+        ),
+        Collections.emptyMap()
+    );
+    private static final ConfiguredSubtopology TOPICS_INFO2 = new ConfiguredSubtopology(
+        Collections.singleton(SINK_TOPIC_NAME1),
+        Collections.singleton(REPARTITION_TOPIC_NAME1),
+        mkMap(mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1)),
+        Collections.emptyMap()
+    );
+    private static final Set<String> TOPICS = Set.of(
+        SOURCE_TOPIC_NAME1,
+        SOURCE_TOPIC_NAME2,
+        SINK_TOPIC_NAME1,
+        SINK_TOPIC_NAME2,
+        REPARTITION_TOPIC_NAME1,
+        REPARTITION_TOPIC_NAME2
+    );
+
+    @Test
+    public void shouldSetupRepartitionTopics() {
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(mkEntry("subtopology_0", TOPICS_INFO1),
+            mkEntry("subtopology_1", TOPICS_INFO2));
+        Function<String, Integer> topicPartitionCountProvider = s -> TOPICS.contains(s) ? 3 : null;
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        Map<String, ConfiguredInternalTopic> setup = repartitionTopics.setup();
+
+        assertEquals(
+            mkMap(
+                mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+                mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2)
+            ),
+            setup
+        );
+    }
+
+    @Test
+    public void shouldThrowStreamsMissingSourceTopicsExceptionIfMissingSourceTopics() {
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(mkEntry("subtopology_0", TOPICS_INFO1),
+            mkEntry("subtopology_1", TOPICS_INFO2));
+        Function<String, Integer> topicPartitionCountProvider = s -> Objects.equals(s, SOURCE_TOPIC_NAME1) ? null
+            : (TOPICS.contains(s) ? 3 : null);
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        final StreamsMissingSourceTopicsException exception = assertThrows(StreamsMissingSourceTopicsException.class,
+            repartitionTopics::setup);
+
+        assertNotNull(exception);
+        assertEquals("Missing source topics: source1", exception.getMessage());
+    }
+
+    @Test
+    public void shouldThrowStreamsMissingSourceTopicsExceptionIfPartitionCountCannotBeComputedForAllRepartitionTopics() {
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(
+            mkEntry("subtopology_0", TOPICS_INFO1),
+            mkEntry("subtopology_1", TOPICS_INFO_WITHOUT_PARTITION_COUNT)
+        );
+        Function<String, Integer> topicPartitionCountProvider = s -> TOPICS.contains(s) ? 3 : null;
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        StreamsMissingSourceTopicsException exception = assertThrows(StreamsMissingSourceTopicsException.class, repartitionTopics::setup);
+
+        assertEquals(
+            "Failed to compute number of partitions for all repartition topics, make sure all user input topics are created and all pattern subscriptions match at least one topic in the cluster",
+            exception.getMessage()
+        );
+    }
+
+    @Test
+    public void shouldSetRepartitionTopicPartitionCountFromUpstreamExternalSourceTopic() {
+        final ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(
+            Set.of(REPARTITION_TOPIC_NAME1, REPARTITION_WITHOUT_PARTITION_COUNT),
+            Set.of(SOURCE_TOPIC_NAME1, REPARTITION_TOPIC_NAME2),
+            mkMap(
+                mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+                mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2),
+                mkEntry(REPARTITION_WITHOUT_PARTITION_COUNT, REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT)
+            ),
+            Collections.emptyMap()
+        );
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(
+            mkEntry("subtopology_0", configuredSubtopology),
+            mkEntry("subtopology_1", TOPICS_INFO_WITHOUT_PARTITION_COUNT)
+        );
+        Function<String, Integer> topicPartitionCountProvider = s -> TOPICS.contains(s) ? 3 : null;
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        Map<String, ConfiguredInternalTopic> setup = repartitionTopics.setup();
+
+        assertEquals(mkMap(
+            mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+            mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2),
+            mkEntry(REPARTITION_WITHOUT_PARTITION_COUNT, REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT)
+        ), setup);
+    }
+
+    @Test
+    public void shouldSetRepartitionTopicPartitionCountFromUpstreamInternalRepartitionSourceTopic() {
+        final ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(
+            Set.of(REPARTITION_TOPIC_NAME2, REPARTITION_WITHOUT_PARTITION_COUNT),
+            Set.of(SOURCE_TOPIC_NAME1, REPARTITION_TOPIC_NAME1),
+            mkMap(
+                mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+                mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2),
+                mkEntry(REPARTITION_WITHOUT_PARTITION_COUNT, REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT)
+            ),
+            Collections.emptyMap()
+        );
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(
+            mkEntry("subtopology_0", configuredSubtopology),
+            mkEntry("subtopology_1", TOPICS_INFO_WITHOUT_PARTITION_COUNT)
+        );
+        Function<String, Integer> topicPartitionCountProvider = s -> TOPICS.contains(s) ? 3 : null;
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        Map<String, ConfiguredInternalTopic> setup = repartitionTopics.setup();
+
+        assertEquals(
+            mkMap(
+                mkEntry(REPARTITION_TOPIC_NAME1, REPARTITION_TOPIC_CONFIG1),
+                mkEntry(REPARTITION_TOPIC_NAME2, REPARTITION_TOPIC_CONFIG2),
+                mkEntry(REPARTITION_WITHOUT_PARTITION_COUNT, REPARTITION_TOPIC_CONFIG_WITHOUT_PARTITION_COUNT)
+            ),
+            setup
+        );
+    }
+
+    @Test
+    public void shouldNotSetupRepartitionTopicsWhenTopologyDoesNotContainAnyRepartitionTopics() {
+        final ConfiguredSubtopology configuredSubtopology = new ConfiguredSubtopology(
+            Collections.singleton(SINK_TOPIC_NAME1),
+            Collections.singleton(SOURCE_TOPIC_NAME1),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+        Map<String, ConfiguredSubtopology> subtopologyToConfiguredSubtopology = mkMap(mkEntry("subtopology_0", configuredSubtopology));
+        Function<String, Integer> topicPartitionCountProvider = s -> TOPICS.contains(s) ? 3 : null;
+        final RepartitionTopics repartitionTopics = new RepartitionTopics(
+            LOG_CONTEXT,
+            subtopologyToConfiguredSubtopology,
+            topicPartitionCountProvider
+        );
+
+        Map<String, ConfiguredInternalTopic> setup = repartitionTopics.setup();
+
+        assertEquals(Collections.emptyMap(), setup);
+    }
+
+}
\ No newline at end of file


(kafka) 36/42: Introduce the streams membership manager (#17564)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit dcb0c923ff7b28285cdb1ce692888de6cf4b47a2
Author: Bruno Cadonna <ca...@apache.org>
AuthorDate: Tue Oct 29 15:29:49 2024 +0100

    Introduce the streams membership manager (#17564)
    
    The streams membership manager manages the state of the member
    and is responsible for reconciling the received task assignment
    with the current task assignment of the member. Additionally,
    it requests the call of the callback that installs the
    reconciled task assignment in the Streams client.
---
 .../internals/StreamsAssignmentInterface.java      |  27 +-
 .../StreamsGroupHeartbeatRequestManager.java       |   4 +-
 .../internals/StreamsMembershipManager.java        | 832 +++++++++++++++++++
 .../internals/events/ApplicationEvent.java         |   1 +
 .../consumer/internals/events/BackgroundEvent.java |   3 +-
 .../StreamsOnAssignmentCallbackCompletedEvent.java |  51 ++
 .../StreamsOnAssignmentCallbackNeededEvent.java    |  42 +
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  12 +-
 .../internals/StreamsMembershipManagerTest.java    | 905 +++++++++++++++++++++
 .../streams/processor/internals/StreamThread.java  |   6 +-
 10 files changed, 1868 insertions(+), 15 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index cefe9175b68..650edaa2de2 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -200,10 +200,10 @@ public class StreamsAssignmentInterface {
         }
     }
 
-    public static class TaskId {
+    public static class TaskId implements Comparable<TaskId> {
 
-        public final String subtopologyId;
-        public final int partitionId;
+        private final String subtopologyId;
+        private final int partitionId;
 
         public int partitionId() {
             return partitionId;
@@ -218,6 +218,27 @@ public class StreamsAssignmentInterface {
             this.partitionId = partitionId;
         }
 
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            TaskId taskId = (TaskId) o;
+            return partitionId == taskId.partitionId && Objects.equals(subtopologyId, taskId.subtopologyId);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(subtopologyId, partitionId);
+        }
+
+        @Override
+        public int compareTo(TaskId taskId) {
+            if (subtopologyId.equals(taskId.subtopologyId)) {
+                return partitionId - taskId.partitionId;
+            }
+            return subtopologyId.compareTo(taskId.subtopologyId);
+        }
+
         @Override
         public String toString() {
             return "TaskId{" +
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 896800cff3c..5fc15b7e436 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -114,8 +114,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     @Override
     public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
-        if (!coordinatorRequestManager.coordinator().isPresent() ||
-            membershipManager.shouldSkipHeartbeat()) {
+        if (!coordinatorRequestManager.coordinator().isPresent() || membershipManager.shouldSkipHeartbeat()) {
             membershipManager.onHeartbeatRequestSkipped();
             return NetworkClientDelegate.PollResult.EMPTY;
         }
@@ -221,6 +220,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
     private void onFailure(final Throwable exception, final long responseTimeMs) {
         this.heartbeatRequestState.onFailedAttempt(responseTimeMs);
         this.heartbeatState.reset();
+        membershipManager.onHeartbeatFailure(exception instanceof RetriableException);
         if (exception instanceof RetriableException) {
             String message = String.format("StreamsGroupHeartbeatRequest failed because of the retriable exception. " +
                     "Will retry in %s ms: %s",
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
new file mode 100644
index 00000000000..ef39f661f67
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
@@ -0,0 +1,832 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackNeededEvent;
+import org.apache.kafka.clients.consumer.internals.metrics.ConsumerRebalanceMetricsManager;
+import org.apache.kafka.clients.consumer.internals.metrics.RebalanceMetricsManager;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
+import org.apache.kafka.common.telemetry.internals.ClientTelemetryProvider;
+import org.apache.kafka.common.telemetry.internals.ClientTelemetryReporter;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.slf4j.Logger;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Tracks state the state of a single member in relationship to a group:
+ * <p/>
+ * Responsible for:
+ * <ul>
+ *   <li>Keeping member state</li>
+ *   <li>Keeping assignment for the member</li>
+ *   <li>Computing assignment for the group if the member is required to do so</li>
+ * </ul>
+ */
+public class StreamsMembershipManager implements RequestManager {
+
+    /**
+     * A data structure to represent the current task assignment, and current target task assignment of a member in a
+     * streams group.
+     * <p/>
+     * Besides the assigned tasks, it contains a local epoch that is bumped whenever the assignment changes, to ensure
+     * that two assignments with the same tasks but different local epochs are not considered equal.
+     */
+    private static class LocalAssignment {
+        public static final long NONE_EPOCH = -1;
+        public static final LocalAssignment NONE = new LocalAssignment(
+            NONE_EPOCH,
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+
+        public final long localEpoch;
+        public final Map<String, SortedSet<Integer>> activeTasks;
+        public final Map<String, SortedSet<Integer>> standbyTasks;
+        public final Map<String, SortedSet<Integer>> warmupTasks;
+
+        public LocalAssignment(final long localEpoch,
+                               final Map<String, SortedSet<Integer>> activeTasks,
+                               final Map<String, SortedSet<Integer>> standbyTasks,
+                               final Map<String, SortedSet<Integer>> warmupTasks) {
+            this.localEpoch = localEpoch;
+            this.activeTasks = activeTasks;
+            this.standbyTasks = standbyTasks;
+            this.warmupTasks = warmupTasks;
+            if (localEpoch == NONE_EPOCH &&
+                (!activeTasks.isEmpty() || !standbyTasks.isEmpty() || !warmupTasks.isEmpty())) {
+                throw new IllegalArgumentException("Local epoch must be set if tasks are assigned.");
+            }
+        }
+
+        Optional<LocalAssignment> updateWith(final Map<String, SortedSet<Integer>> activeTasks,
+                                             final Map<String, SortedSet<Integer>> standbyTasks,
+                                             final Map<String, SortedSet<Integer>> warmupTasks) {
+            if (localEpoch != NONE_EPOCH) {
+                if (activeTasks.equals(this.activeTasks) &&
+                    standbyTasks.equals(this.standbyTasks) &&
+                    warmupTasks.equals(this.warmupTasks)) {
+
+                    return Optional.empty();
+                }
+            }
+
+            long nextLocalEpoch = localEpoch + 1;
+            return Optional.of(new LocalAssignment(nextLocalEpoch, activeTasks, standbyTasks, warmupTasks));
+        }
+
+        @Override
+        public String toString() {
+            return "LocalAssignment{" +
+                "localEpoch=" + localEpoch +
+                ", activeTasks=" + activeTasks +
+                ", standbyTasks=" + standbyTasks +
+                ", warmupTasks=" + warmupTasks +
+                '}';
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) return true;
+            if (o == null || getClass() != o.getClass()) return false;
+            LocalAssignment that = (LocalAssignment) o;
+            return localEpoch == that.localEpoch &&
+                Objects.equals(activeTasks, that.activeTasks) &&
+                Objects.equals(standbyTasks, that.standbyTasks) &&
+                Objects.equals(warmupTasks, that.warmupTasks);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(localEpoch, activeTasks, standbyTasks, warmupTasks);
+        }
+    }
+
+    static final Utils.TopicPartitionComparator TOPIC_PARTITION_COMPARATOR = new Utils.TopicPartitionComparator();
+
+    private final Logger log;
+
+    private final StreamsAssignmentInterface streamsAssignmentInterface;
+
+    private final SubscriptionState subscriptionState;
+
+    private final BackgroundEventHandler backgroundEventHandler;
+
+    private MemberState state;
+
+    private final String groupId;
+
+    private String memberId = "";
+
+    private final Optional<String> groupInstanceId = Optional.empty();
+
+    private int memberEpoch = 0;
+
+    private Optional<CompletableFuture<Void>> leaveGroupInProgress = Optional.empty();
+
+    private CompletableFuture<Void> staleMemberAssignmentRelease;
+
+    private boolean reconciliationInProgress;
+
+    private boolean rejoinedWhileReconciliationInProgress;
+
+    private final Optional<ClientTelemetryReporter> clientTelemetryReporter;
+
+    private LocalAssignment targetAssignment = LocalAssignment.NONE;
+
+    private LocalAssignment currentAssignment = LocalAssignment.NONE;
+
+    private final AtomicBoolean subscriptionUpdated = new AtomicBoolean(false);
+
+    private final RebalanceMetricsManager metricsManager;
+
+    private final Time time;
+
+    private boolean isPollTimerExpired;
+
+    public StreamsMembershipManager(final String groupId,
+                                    final StreamsAssignmentInterface streamsAssignmentInterface,
+                                    final SubscriptionState subscriptionState,
+                                    final LogContext logContext,
+                                    final Optional<ClientTelemetryReporter> clientTelemetryReporter,
+                                    final BackgroundEventHandler backgroundEventHandler,
+                                    final Time time,
+                                    final Metrics metrics) {
+        log = logContext.logger(StreamsMembershipManager.class);
+        this.state = MemberState.UNSUBSCRIBED;
+        this.groupId = groupId;
+        this.streamsAssignmentInterface = streamsAssignmentInterface;
+        this.subscriptionState = subscriptionState;
+        this.clientTelemetryReporter = clientTelemetryReporter;
+        this.backgroundEventHandler = backgroundEventHandler;
+        metricsManager = new ConsumerRebalanceMetricsManager(metrics);
+        this.time = time;
+    }
+
+    public String groupId() {
+        return groupId;
+    }
+
+    public String memberId() {
+        return memberId;
+    }
+
+    public Optional<String> groupInstanceId() {
+        return groupInstanceId;
+    }
+
+    public int memberEpoch() {
+        return memberEpoch;
+    }
+
+    public MemberState state() {
+        return state;
+    }
+
+    public boolean isLeavingGroup() {
+        MemberState state = state();
+        return state == MemberState.PREPARE_LEAVING || state == MemberState.LEAVING;
+    }
+
+    private boolean isNotInGroup() {
+        MemberState state = state();
+        return state == MemberState.UNSUBSCRIBED ||
+            state == MemberState.FENCED ||
+            state == MemberState.FATAL ||
+            state == MemberState.STALE;
+    }
+
+    private void transitionToJoining() {
+        if (state == MemberState.FATAL) {
+            log.warn("No action taken to join the group with the updated subscription because " +
+                "the member is in FATAL state");
+            return;
+        }
+        if (reconciliationInProgress) {
+            rejoinedWhileReconciliationInProgress = true;
+        }
+        resetEpoch();
+        transitionTo(MemberState.JOINING);
+        clearPendingTaskAssignment();
+    }
+
+    private void transitionToSendingLeaveGroup(boolean dueToExpiredPollTimer) {
+        if (state == MemberState.FATAL) {
+            log.warn("Member {} with epoch {} won't send leave group request because it is in " +
+                "FATAL state", memberIdInfoForLog(), memberEpoch);
+            return;
+        }
+        if (state == MemberState.UNSUBSCRIBED) {
+            log.warn("Member {} won't send leave group request because it is already out of the group.",
+                memberIdInfoForLog());
+            return;
+        }
+
+        if (dueToExpiredPollTimer) {
+            isPollTimerExpired = true;
+            // Briefly transition through prepare leaving. The member does not have to release
+            // any assignment before sending the leave group given that is stale. It will invoke
+            // onTaskAssignment with empty assignment after sending the leave group on the STALE state.
+            transitionTo(MemberState.PREPARE_LEAVING);
+        }
+        finalizeLeaving();
+        transitionTo(MemberState.LEAVING);
+    }
+
+    private void finalizeLeaving() {
+        updateMemberEpoch(StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH);
+        clearPendingTaskAssignment();
+    }
+
+    private void transitionToStale() {
+        transitionTo(MemberState.STALE);
+
+        CompletableFuture<Void> onAllTasksRevokedDone = invokeRevokingAllTasksCallback();
+        staleMemberAssignmentRelease = onAllTasksRevokedDone.whenComplete((result, error) -> {
+            if (error != null) {
+                log.error("Task revocation callback invocation failed " +
+                    "after member left group due to expired poll timer.", error);
+            }
+            clearTaskAndPartitionAssignment();
+            log.debug("Member {} sent leave group heartbeat and released its assignment. It will remain " +
+                    "in {} state until the poll timer is reset, and it will then rejoin the group",
+                memberIdInfoForLog(), MemberState.STALE);
+        });
+    }
+
+    public void transitionToFatal() {
+        MemberState previousState = state;
+        transitionTo(MemberState.FATAL);
+        log.error("Member {} with epoch {} transitioned to fatal state", memberIdInfoForLog(), memberEpoch);
+
+        if (previousState == MemberState.UNSUBSCRIBED) {
+            log.debug("Member {} with epoch {} got fatal error from the broker but it already " +
+                "left the group, so onTaskAssignment callback won't be triggered.", memberIdInfoForLog(), memberEpoch);
+            return;
+        }
+
+        if (previousState == MemberState.LEAVING || previousState == MemberState.PREPARE_LEAVING) {
+            log.info("Member {} with epoch {} was leaving the group with state {} when it got a " +
+                "fatal error from the broker. It will discard the ongoing leave and remain in " +
+                "fatal state.", memberIdInfoForLog(), memberEpoch, previousState);
+            maybeCompleteLeaveInProgress();
+            return;
+        }
+
+        CompletableFuture<Void> callbackResult = invokeRevokingAllTasksCallback();
+        callbackResult.whenComplete((result, error) -> {
+            if (error != null) {
+                log.error("onTaskAssignment callback invocation failed while releasing assignment" +
+                    "after member failed with fatal error.", error);
+            }
+            clearTaskAndPartitionAssignment();
+        });
+    }
+
+    public void transitionToUnsubscribeIfLeaving() {
+        if (state == MemberState.LEAVING) {
+            log.warn("Heartbeat to leave group cannot be sent (most probably due to coordinator " +
+                    "not known/available). Member {} with epoch {} will transition to {}.",
+                memberIdInfoForLog(), memberEpoch, MemberState.UNSUBSCRIBED);
+            transitionTo(MemberState.UNSUBSCRIBED);
+            maybeCompleteLeaveInProgress();
+        }
+    }
+
+    private void transitionTo(MemberState nextState) {
+        if (!state.equals(nextState) && !nextState.getPreviousValidStates().contains(state)) {
+            throw new IllegalStateException(String.format("Invalid state transition from %s to %s",
+                state, nextState));
+        }
+
+        if (isCompletingRebalance(state, nextState)) {
+            metricsManager.recordRebalanceEnded(time.milliseconds());
+        }
+        if (isStartingRebalance(state, nextState)) {
+            metricsManager.recordRebalanceStarted(time.milliseconds());
+        }
+
+        log.info("Member {} with epoch {} transitioned from {} to {}.", memberIdInfoForLog(), memberEpoch, state, nextState);
+        this.state = nextState;
+    }
+
+    private static boolean isCompletingRebalance(MemberState currentState, MemberState nextState) {
+        return currentState == MemberState.RECONCILING &&
+            (nextState == MemberState.STABLE || nextState == MemberState.ACKNOWLEDGING);
+    }
+
+    private static boolean isStartingRebalance(MemberState currentState, MemberState nextState) {
+        return currentState != MemberState.RECONCILING && nextState == MemberState.RECONCILING;
+    }
+
+    private void resetEpoch() {
+        updateMemberEpoch(StreamsGroupHeartbeatRequest.JOIN_GROUP_MEMBER_EPOCH);
+    }
+
+    private void updateMemberEpoch(int newEpoch) {
+        memberEpoch = newEpoch;
+    }
+
+    private void clearPendingTaskAssignment() {
+        currentAssignment = LocalAssignment.NONE;
+    }
+
+    private void clearTaskAndPartitionAssignment() {
+        subscriptionState.assignFromSubscribed(Collections.emptySet());
+        currentAssignment = LocalAssignment.NONE;
+        targetAssignment = LocalAssignment.NONE;
+    }
+
+    public boolean shouldSkipHeartbeat() {
+        return isNotInGroup();
+    }
+
+    public boolean shouldHeartbeatNow() {
+        MemberState state = state();
+        return state == MemberState.ACKNOWLEDGING || state == MemberState.LEAVING || state == MemberState.JOINING;
+    }
+
+    public void onSubscriptionUpdated() {
+        subscriptionUpdated.compareAndSet(false, true);
+    }
+
+    public void onConsumerPoll() {
+        if (subscriptionUpdated.compareAndSet(true, false) && state == MemberState.UNSUBSCRIBED) {
+            transitionToJoining();
+        }
+    }
+
+    public void onHeartbeatRequestGenerated() {
+        MemberState state = state();
+        if (state == MemberState.ACKNOWLEDGING) {
+            if (targetAssignmentReconciled()) {
+                transitionTo(MemberState.STABLE);
+            } else {
+                log.debug("Member {} with epoch {} transitioned to {} after a heartbeat was sent " +
+                    "to ack a previous reconciliation. New assignments are ready to " +
+                    "be reconciled.", memberIdInfoForLog(), memberEpoch, MemberState.RECONCILING);
+                transitionTo(MemberState.RECONCILING);
+            }
+        } else if (state == MemberState.LEAVING) {
+            if (isPollTimerExpired) {
+                log.debug("Member {} with epoch {} generated the heartbeat to leave due to expired poll timer. It will " +
+                    "remain stale (no heartbeat) until it rejoins the group on the next consumer " +
+                    "poll.", memberIdInfoForLog(), memberEpoch);
+                transitionToStale();
+            } else {
+                log.debug("Member {} with epoch {} generated the heartbeat to leave the group.", memberIdInfoForLog(), memberEpoch);
+                transitionTo(MemberState.UNSUBSCRIBED);
+            }
+        }
+    }
+
+    public void onHeartbeatSuccess(StreamsGroupHeartbeatResponse response) {
+        StreamsGroupHeartbeatResponseData responseData = response.data();
+        throwIfUnexpectedError(responseData);
+        if (state == MemberState.LEAVING) {
+            log.debug("Ignoring heartbeat response received from broker. Member {} with epoch {} is " +
+                "already leaving the group.", memberId, memberEpoch);
+            return;
+        }
+        if (state == MemberState.UNSUBSCRIBED && maybeCompleteLeaveInProgress()) {
+            log.debug("Member {} with epoch {} received a successful response to the heartbeat " +
+                "to leave the group and completed the leave operation. ", memberId, memberEpoch);
+            return;
+        }
+        if (isNotInGroup()) {
+            log.debug("Ignoring heartbeat response received from broker. Member {} is in {} state" +
+                " so it's not a member of the group. ", memberId, state);
+            return;
+        }
+
+        // Update the group member id label in the client telemetry reporter if the member id has
+        // changed. Initially the member id is empty, and it is updated when the member joins the
+        // group. This is done here to avoid updating the label on every heartbeat response. Also
+        // check if the member id is null, as the schema defines it as nullable.
+        if (responseData.memberId() != null && !responseData.memberId().equals(memberId)) {
+            clientTelemetryReporter.ifPresent(reporter -> reporter.updateMetricsLabels(
+                Collections.singletonMap(ClientTelemetryProvider.GROUP_MEMBER_ID, responseData.memberId())));
+        }
+
+        memberId = responseData.memberId();
+        updateMemberEpoch(responseData.memberEpoch());
+
+        final List<StreamsGroupHeartbeatResponseData.TaskIds> activeTasks = responseData.activeTasks();
+        final List<StreamsGroupHeartbeatResponseData.TaskIds> standbyTasks = responseData.standbyTasks();
+        final List<StreamsGroupHeartbeatResponseData.TaskIds> warmupTasks = responseData.warmupTasks();
+
+        if (activeTasks != null && standbyTasks != null && warmupTasks != null) {
+
+            if (!state.canHandleNewAssignment()) {
+                log.debug("Ignoring new assignment: active tasks {}, standby tasks {}, and warm-up tasks {} received " +
+                        "from server because member is in {} state.",
+                    activeTasks, standbyTasks, warmupTasks, state);
+                return;
+            }
+
+            processAssignmentReceived(
+                toTasksAssignment(activeTasks),
+                toTasksAssignment(standbyTasks),
+                toTasksAssignment(warmupTasks)
+            );
+        } else {
+            if (responseData.activeTasks() != null ||
+                responseData.standbyTasks() != null ||
+                responseData.warmupTasks() != null) {
+
+                throw new IllegalStateException("Invalid response data, task collections must be all null or all non-null: "
+                    + responseData);
+            }
+        }
+    }
+
+    public void onHeartbeatFailure(boolean retriable) {
+        if (!retriable) {
+            metricsManager.maybeRecordRebalanceFailed();
+        }
+        // The leave group request is sent out once (not retried), so we should complete the leave
+        // operation once the request completes, regardless of the response.
+        if (state == MemberState.UNSUBSCRIBED && maybeCompleteLeaveInProgress()) {
+            log.warn("Member {} with epoch {} received a failed response to the heartbeat to " +
+                "leave the group and completed the leave operation. ", memberIdInfoForLog(), memberEpoch);
+        }
+    }
+
+    public void onPollTimerExpired() {
+        transitionToSendingLeaveGroup(true);
+    }
+
+    public void onFenced() {
+        if (state == MemberState.PREPARE_LEAVING) {
+            log.info("Member {} with epoch {} got fenced but it is already preparing to leave " +
+                "the group, so it will stop sending heartbeat and won't attempt to send the " +
+                "leave request or rejoin.", memberIdInfoForLog(), memberEpoch);
+            finalizeLeaving();
+            transitionTo(MemberState.UNSUBSCRIBED);
+            maybeCompleteLeaveInProgress();
+            return;
+        }
+
+        if (state == MemberState.LEAVING) {
+            log.debug("Member {} with epoch {} got fenced before sending leave group heartbeat. " +
+                "It will not send the leave request and won't attempt to rejoin.", memberIdInfoForLog(), memberEpoch);
+            transitionTo(MemberState.UNSUBSCRIBED);
+            maybeCompleteLeaveInProgress();
+            return;
+        }
+        if (state == MemberState.UNSUBSCRIBED) {
+            log.debug("Member {} with epoch {} got fenced but it already left the group, so it " +
+                "won't attempt to rejoin.", memberIdInfoForLog(), memberEpoch);
+            return;
+        }
+        transitionTo(MemberState.FENCED);
+        resetEpoch();
+        log.debug("Member {} with epoch {} transitioned to {} state. It will release its " +
+            "assignment and rejoin the group.", memberIdInfoForLog(), memberEpoch, MemberState.FENCED);
+
+        CompletableFuture<Void> callbackResult = invokeRevokingAllTasksCallback();
+        callbackResult.whenComplete((result, error) -> {
+            if (error != null) {
+                log.error("onTaskAssignment callback invocation failed while releasing assignment" +
+                    " after member got fenced. Member will rejoin the group anyways.", error);
+            }
+            clearTaskAndPartitionAssignment();
+            if (state == MemberState.FENCED) {
+                transitionToJoining();
+            } else {
+                log.debug("Fenced member onTaskAssignment callback completed but the state has " +
+                    "already changed to {}, so the member won't rejoin the group", state);
+            }
+        });
+    }
+
+    private void throwIfUnexpectedError(StreamsGroupHeartbeatResponseData responseData) {
+        if (responseData.errorCode() != Errors.NONE.code()) {
+            String errorMessage = String.format(
+                "Unexpected error in Heartbeat response. Expected no error, but received: %s with message: '%s'",
+                Errors.forCode(responseData.errorCode()), responseData.errorMessage()
+            );
+            throw new IllegalArgumentException(errorMessage);
+        }
+    }
+
+    public void maybeRejoinStaleMember() {
+        isPollTimerExpired = false;
+        if (state == MemberState.STALE) {
+            log.debug("Expired poll timer has been reset so stale member {} will rejoin the group " +
+                "when it completes releasing its previous assignment.", memberIdInfoForLog());
+            staleMemberAssignmentRelease.whenComplete((__, error) -> transitionToJoining());
+        }
+    }
+
+    private boolean maybeCompleteLeaveInProgress() {
+        if (leaveGroupInProgress.isPresent()) {
+            leaveGroupInProgress.get().complete(null);
+            leaveGroupInProgress = Optional.empty();
+            return true;
+        }
+        return false;
+    }
+
+    private static SortedSet<StreamsAssignmentInterface.TaskId> toTaskIdSet(final Map<String, SortedSet<Integer>> tasks) {
+        SortedSet<StreamsAssignmentInterface.TaskId> taskIdSet = new TreeSet<>();
+        for (final Map.Entry<String, SortedSet<Integer>> task : tasks.entrySet()) {
+            final String subtopologyId = task.getKey();
+            final SortedSet<Integer> partitions = task.getValue();
+            for (final int partition : partitions) {
+                taskIdSet.add(new StreamsAssignmentInterface.TaskId(subtopologyId, partition));
+            }
+        }
+        return taskIdSet;
+    }
+
+    private static Map<String, SortedSet<Integer>> toTasksAssignment(final List<StreamsGroupHeartbeatResponseData.TaskIds> taskIds) {
+        return taskIds.stream()
+            .collect(Collectors.toMap(StreamsGroupHeartbeatResponseData.TaskIds::subtopologyId, taskId -> new TreeSet<>(taskId.partitions())));
+    }
+
+    /**
+     * Leaves the group.
+     *
+     * <p>
+     * This method does the following:
+     * <ol>
+     *     <li>Transitions member state to {@link MemberState#PREPARE_LEAVING}.</li>
+     *     <li>Requests the invocation of the revocation callback.</li>
+     *     <li>Once the revocation callback completes, it clears the current and target assignment, unsubscribes from
+     *     all topics and transitions the member state to {@link MemberState#LEAVING}.</li>
+     * </ol>
+     * States {@link MemberState#PREPARE_LEAVING} and {@link MemberState#LEAVING} cause the heartbeat request manager
+     * to send a leave group heartbeat.
+     * </p>
+     *
+     * @return future that will complete when the revocation callback execution completes and the heartbeat
+     *         to leave the group has been sent out.
+     */
+    public CompletableFuture<Void> leaveGroup() {
+        if (isNotInGroup()) {
+            if (state == MemberState.FENCED) {
+                clearTaskAndPartitionAssignment();
+                transitionTo(MemberState.UNSUBSCRIBED);
+            }
+            subscriptionState.unsubscribe();
+            return CompletableFuture.completedFuture(null);
+        }
+
+        if (state == MemberState.PREPARE_LEAVING || state == MemberState.LEAVING) {
+            log.debug("Leave group operation already in progress for member {}", memberIdInfoForLog());
+            return leaveGroupInProgress.get();
+        }
+
+        CompletableFuture<Void> onGroupLeft = new CompletableFuture<>();
+        leaveGroupInProgress = Optional.of(onGroupLeft);
+        CompletableFuture<Void> onAllTasksRevokedDone = prepareLeaving();
+        onAllTasksRevokedDone.whenComplete((__, callbackError) -> leaving(callbackError));
+
+        return onGroupLeft;
+    }
+
+    private CompletableFuture<Void> prepareLeaving() {
+        transitionTo(MemberState.PREPARE_LEAVING);
+        return invokeRevokingAllTasksCallback();
+    }
+
+    private void leaving(Throwable callbackError) {
+        if (callbackError != null) {
+            log.error("Member {} callback to revoke task assignment failed. It will proceed " +
+                    "to clear its assignment and send a leave group heartbeat",
+                memberIdInfoForLog(), callbackError);
+        } else {
+            log.info("Member {} completed callback to revoke task assignment. It will proceed " +
+                    "to clear its assignment and send a leave group heartbeat",
+                memberIdInfoForLog());
+        }
+        subscriptionState.unsubscribe();
+        clearTaskAndPartitionAssignment();
+        transitionToSendingLeaveGroup(false);
+    }
+
+    /**
+     * This will process the assignment received if it is different from the member's current
+     * assignment. If a new assignment is received, this will make sure reconciliation is attempted
+     * on the next call of `poll`. If another reconciliation is currently in process, the first `poll`
+     * after that reconciliation will trigger the new reconciliation.
+     *
+     * @param activeTasks Target active tasks assignment received from the broker.
+     * @param standbyTasks Target standby tasks assignment received from the broker.
+     * @param warmupTasks Target warm-up tasks assignment received from the broker.
+     */
+    private void processAssignmentReceived(Map<String, SortedSet<Integer>> activeTasks,
+                                           Map<String, SortedSet<Integer>> standbyTasks,
+                                           Map<String, SortedSet<Integer>> warmupTasks) {
+        replaceTargetAssignmentWithNewAssignment(activeTasks, standbyTasks, warmupTasks);
+        if (!targetAssignmentReconciled()) {
+            transitionTo(MemberState.RECONCILING);
+        } else {
+            log.debug("Target assignment {} received from the broker is equals to the member " +
+                    "current assignment {}. Nothing to reconcile.",
+                targetAssignment, currentAssignment);
+            // Make sure we transition the member back to STABLE if it was RECONCILING (ex.
+            // member was RECONCILING unresolved assignments that were just removed by the
+            // broker), or JOINING (member joining received empty assignment).
+            if (state == MemberState.RECONCILING || state == MemberState.JOINING) {
+                transitionTo(MemberState.STABLE);
+            }
+        }
+    }
+
+    private boolean targetAssignmentReconciled() {
+        return currentAssignment.equals(targetAssignment);
+    }
+
+    private void replaceTargetAssignmentWithNewAssignment(Map<String, SortedSet<Integer>> activeTasks,
+                                                          Map<String, SortedSet<Integer>> standbyTasks,
+                                                          Map<String, SortedSet<Integer>> warmupTasks) {
+        targetAssignment.updateWith(activeTasks, standbyTasks, warmupTasks)
+            .ifPresent(updatedAssignment -> {
+                log.debug("Target assignment updated from {} to {}. Member will reconcile it on the next poll.",
+                    targetAssignment, updatedAssignment);
+                targetAssignment = updatedAssignment;
+            });
+    }
+
+    @Override
+    public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
+        if (state == MemberState.RECONCILING) {
+            maybeReconcile();
+        }
+        return NetworkClientDelegate.PollResult.EMPTY;
+    }
+
+    private void maybeReconcile() {
+        if (targetAssignmentReconciled()) {
+            log.trace("Ignoring reconciliation attempt. Target assignment is equal to the " +
+                "current assignment.");
+            return;
+        }
+        if (reconciliationInProgress) {
+            log.trace("Ignoring reconciliation attempt. Another reconciliation is already in progress. Assignment " +
+                targetAssignment + " will be handled in the next reconciliation loop.");
+            return;
+        }
+
+        markReconciliationInProgress();
+
+        // ToDo: add standby and warmup tasks
+        SortedSet<StreamsAssignmentInterface.TaskId> assignedActiveTasks = toTaskIdSet(targetAssignment.activeTasks);
+
+        log.info("Assigned tasks with local epoch {}\n" +
+                "\tMember:                        {}\n" +
+                "\tActive tasks:                  {}\n",
+            targetAssignment.localEpoch,
+            memberIdInfoForLog(),
+            assignedActiveTasks
+        );
+
+        SortedSet<TopicPartition> ownedTopicPartitions = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
+        ownedTopicPartitions.addAll(subscriptionState.assignedPartitions());
+        SortedSet<TopicPartition> assignedTopicPartitions = topicPartitionsForActiveTasks(targetAssignment.activeTasks);
+        SortedSet<TopicPartition> assignedTopicPartitionsNotPreviouslyOwned =
+            assignedTopicPartitionsNotPreviouslyOwned(assignedTopicPartitions, ownedTopicPartitions);
+
+        subscriptionState.assignFromSubscribedAwaitingCallback(
+            assignedTopicPartitions,
+            assignedTopicPartitionsNotPreviouslyOwned
+        );
+
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            new StreamsOnAssignmentCallbackNeededEvent(new StreamsAssignmentInterface.Assignment(
+                assignedActiveTasks,
+                Collections.emptySet(),
+                Collections.emptySet()
+            ));
+        CompletableFuture<Void> onTasksAssignmentDone = onAssignmentCallbackNeededEvent.future();
+        backgroundEventHandler.add(onAssignmentCallbackNeededEvent);
+        // The current target assignment is captured to ensure that acknowledging the current assignment is done with
+        // the same target assignment that was used when this reconciliation was initiated.
+        LocalAssignment currentTargetAssignment = targetAssignment;
+        onTasksAssignmentDone.whenComplete((__, callbackError) -> {
+            if (callbackError != null) {
+                log.error("Reconciliation failed: onTasksAssignment callback invocation failed for tasks {}",
+                    targetAssignment, callbackError);
+                markReconciliationCompleted();
+            } else {
+                if (reconciliationInProgress && !maybeAbortReconciliation()) {
+                    subscriptionState.enablePartitionsAwaitingCallback(assignedTopicPartitionsNotPreviouslyOwned);
+                    currentAssignment = currentTargetAssignment;
+                    transitionTo(MemberState.ACKNOWLEDGING);
+                    markReconciliationCompleted();
+                }
+            }
+        });
+    }
+
+    private SortedSet<TopicPartition> assignedTopicPartitionsNotPreviouslyOwned(final SortedSet<TopicPartition> assignedTopicPartitions,
+                                                                                final SortedSet<TopicPartition> ownedTopicPartitions) {
+        SortedSet<TopicPartition> assignedPartitionsNotPreviouslyOwned = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
+        assignedPartitionsNotPreviouslyOwned.addAll(assignedTopicPartitions);
+        assignedPartitionsNotPreviouslyOwned.removeAll(ownedTopicPartitions);
+        return assignedPartitionsNotPreviouslyOwned;
+    }
+
+    private SortedSet<TopicPartition> topicPartitionsForActiveTasks(final Map<String, SortedSet<Integer>> activeTasks) {
+        final SortedSet<TopicPartition> topicPartitions = new TreeSet<>(TOPIC_PARTITION_COMPARATOR);
+        activeTasks.forEach((subtopologyId, partitionIds) ->
+            Stream.concat(
+                streamsAssignmentInterface.subtopologyMap().get(subtopologyId).sourceTopics.stream(),
+                streamsAssignmentInterface.subtopologyMap().get(subtopologyId).repartitionSourceTopics.keySet().stream()
+            ).forEach(topic -> {
+                for (final int partitionId : partitionIds) {
+                    topicPartitions.add(new TopicPartition(topic, partitionId));
+                }
+            })
+        );
+        return topicPartitions;
+    }
+
+    private void markReconciliationCompleted() {
+        reconciliationInProgress = false;
+        rejoinedWhileReconciliationInProgress = false;
+    }
+
+    private boolean maybeAbortReconciliation() {
+        boolean shouldAbort = state != MemberState.RECONCILING || rejoinedWhileReconciliationInProgress;
+        if (shouldAbort) {
+            String reason = rejoinedWhileReconciliationInProgress ?
+                "the member has re-joined the group" :
+                "the member already transitioned out of the reconciling state into " + state;
+            log.info("Interrupting reconciliation that is not relevant anymore because " + reason);
+            markReconciliationCompleted();
+        }
+        return shouldAbort;
+    }
+
+    private void markReconciliationInProgress() {
+        reconciliationInProgress = true;
+        rejoinedWhileReconciliationInProgress = false;
+    }
+
+    private CompletableFuture<Void> invokeRevokingAllTasksCallback() {
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            new StreamsOnAssignmentCallbackNeededEvent(new StreamsAssignmentInterface.Assignment(
+                Collections.emptySet(),
+                Collections.emptySet(),
+                Collections.emptySet()
+            ));
+        backgroundEventHandler.add(onAssignmentCallbackNeededEvent);
+        return onAssignmentCallbackNeededEvent.future();
+    }
+
+    public void onTaskAssignmentCallbackCompleted(StreamsOnAssignmentCallbackCompletedEvent event) {
+        Optional<KafkaException> error = event.error();
+        CompletableFuture<Void> future = event.future();
+
+        if (error.isPresent()) {
+            Exception e = error.get();
+            log.warn("The onTaskAssignment callback completed with an error ({}); " +
+                "signaling to continue to the next phase of rebalance", e.getMessage());
+            future.completeExceptionally(e);
+        } else {
+            log.debug("The onTaskAssignment callback completed successfully; signaling to continue to the next phase of rebalance");
+            future.complete(null);
+        }
+    }
+
+    private String memberIdInfoForLog() {
+        return (memberId == null || memberId.isEmpty()) ? "<no ID>" : memberId;
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
index 406ca55b79b..dc0c393e279 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEvent.java
@@ -40,6 +40,7 @@ public abstract class ApplicationEvent {
         SHARE_ACKNOWLEDGE_ON_CLOSE,
         SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK_REGISTRATION,
         SEEK_UNVALIDATED,
+        STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED,
     }
 
     private final Type type;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
index 7e9fdaed2d8..cffcca42f48 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/BackgroundEvent.java
@@ -27,7 +27,8 @@ import java.util.Objects;
 public abstract class BackgroundEvent {
 
     public enum Type {
-        ERROR, CONSUMER_REBALANCE_LISTENER_CALLBACK_NEEDED, SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK
+        ERROR, CONSUMER_REBALANCE_LISTENER_CALLBACK_NEEDED, SHARE_ACKNOWLEDGEMENT_COMMIT_CALLBACK,
+        STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED
     }
 
     private final Type type;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
new file mode 100644
index 00000000000..5b702efb62c
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackCompletedEvent.java
@@ -0,0 +1,51 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals.events;
+
+import org.apache.kafka.common.KafkaException;
+
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+
+public class StreamsOnAssignmentCallbackCompletedEvent extends ApplicationEvent {
+
+    private final CompletableFuture<Void> future;
+    private final Optional<KafkaException> error;
+
+    public StreamsOnAssignmentCallbackCompletedEvent(final CompletableFuture<Void> future,
+                                                     final Optional<KafkaException> error) {
+        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_COMPLETED);
+        this.future = Objects.requireNonNull(future);
+        this.error = Objects.requireNonNull(error);
+    }
+
+    public CompletableFuture<Void> future() {
+        return future;
+    }
+
+    public Optional<KafkaException> error() {
+        return error;
+    }
+
+    @Override
+    protected String toStringBase() {
+        return super.toStringBase() +
+            ", future=" + future +
+            ", error=" + error;
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
new file mode 100644
index 00000000000..8c2f5a3bc81
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
@@ -0,0 +1,42 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals.events;
+
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
+
+import java.util.Objects;
+
+public class StreamsOnAssignmentCallbackNeededEvent extends CompletableBackgroundEvent<Void> {
+
+    private final StreamsAssignmentInterface.Assignment assignment;
+
+    public StreamsOnAssignmentCallbackNeededEvent(StreamsAssignmentInterface.Assignment assignment) {
+        super(Type.STREAMS_ON_ASSIGNMENT_CALLBACK_NEEDED, Long.MAX_VALUE);
+        this.assignment = Objects.requireNonNull(assignment);
+    }
+
+    public StreamsAssignmentInterface.Assignment assignment() {
+        return assignment;
+    }
+
+    @Override
+    protected String toStringBase() {
+        return super.toStringBase() +
+            ", assignment=" + assignment;
+    }
+}
+
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index 193c901e3b7..bec93f98f22 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -303,18 +303,18 @@ class StreamsGroupHeartbeatRequestManagerTest {
         final Assignment targetAssignment = streamsAssignmentInterface.targetAssignment.get();
         assertEquals(1, targetAssignment.activeTasks.size());
         final TaskId activeTaskId = targetAssignment.activeTasks.stream().findFirst().get();
-        assertEquals(activeTaskId.subtopologyId, "0");
-        assertEquals(activeTaskId.partitionId, 0);
+        assertEquals(activeTaskId.subtopologyId(), "0");
+        assertEquals(activeTaskId.partitionId(), 0);
 
         assertEquals(1, targetAssignment.standbyTasks.size());
         final TaskId standbyTaskId = targetAssignment.standbyTasks.stream().findFirst().get();
-        assertEquals(standbyTaskId.subtopologyId, "1");
-        assertEquals(standbyTaskId.partitionId, 1);
+        assertEquals(standbyTaskId.subtopologyId(), "1");
+        assertEquals(standbyTaskId.partitionId(), 1);
 
         assertEquals(1, targetAssignment.warmupTasks.size());
         final TaskId warmupTaskId = targetAssignment.warmupTasks.stream().findFirst().get();
-        assertEquals(warmupTaskId.subtopologyId, "2");
-        assertEquals(warmupTaskId.partitionId, 2);
+        assertEquals(warmupTaskId.subtopologyId(), "2");
+        assertEquals(warmupTaskId.partitionId(), 2);
 
     }
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
new file mode 100644
index 00000000000..4965f05198b
--- /dev/null
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
@@ -0,0 +1,905 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEvent;
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackCompletedEvent;
+import org.apache.kafka.clients.consumer.internals.events.StreamsOnAssignmentCallbackNeededEvent;
+import org.apache.kafka.common.KafkaException;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
+import org.apache.kafka.common.utils.LogContext;
+
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.Time;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class StreamsMembershipManagerTest {
+
+    private static final String GROUP_ID = "test-group";
+    private static final String MEMBER_ID = "test-member-1";
+    private static final int MEMBER_EPOCH = 1;
+
+    private static final String SUB_TOPOLOGY_ID_0 = "subtopology-0";
+    private static final String SUB_TOPOLOGY_ID_1 = "subtopology-1";
+
+    private static final String TOPIC_0 = "topic-0";
+    private static final String TOPIC_1 = "topic-1";
+
+    private static final int PARTITION_0 = 0;
+    private static final int PARTITION_1 = 1;
+
+    private Time time = new MockTime(0);
+    private Metrics metrics = new Metrics(time);
+
+    private StreamsMembershipManager membershipManager;
+
+    @Mock
+    private SubscriptionState subscriptionState;
+
+    @Mock
+    private StreamsAssignmentInterface streamsAssignmentInterface;
+
+    private Queue<BackgroundEvent> backgroundEventQueue = new LinkedList<>();
+    private BackgroundEventHandler backgroundEventHandler = new BackgroundEventHandler(backgroundEventQueue);
+
+    @BeforeEach
+    public void setup() {
+        membershipManager = new StreamsMembershipManager(
+            GROUP_ID,
+            streamsAssignmentInterface,
+            subscriptionState,
+            new LogContext("test"),
+            Optional.empty(),
+            backgroundEventHandler,
+            time,
+            metrics
+        );
+        verifyInStateUnsubscribed(membershipManager);
+    }
+
+    @Test
+    public void testUnexpectedErrorInHeartbeatResponse() {
+        final String errorMessage = "Nobody expects the Spanish Inquisition!";
+        final StreamsGroupHeartbeatResponseData responseData = new StreamsGroupHeartbeatResponseData()
+            .setErrorCode(Errors.GROUP_AUTHORIZATION_FAILED.code())
+            .setErrorMessage(errorMessage);
+        final StreamsGroupHeartbeatResponse response = new StreamsGroupHeartbeatResponse(responseData);
+
+        final IllegalArgumentException exception = assertThrows(
+            IllegalArgumentException.class,
+            () -> membershipManager.onHeartbeatSuccess(response)
+        );
+
+        assertEquals(
+            "Unexpected error in Heartbeat response. Expected no error, but received: "
+                + Errors.GROUP_AUTHORIZATION_FAILED.name()
+                + " with message: '" + errorMessage + "'",
+            exception.getMessage()
+        );
+    }
+
+    @Test
+    public void testActiveTasksAreNullInHeartbeatResponse() {
+        joining();
+        final StreamsGroupHeartbeatResponse response = makeHeartbeatResponse(null);
+
+        final IllegalStateException exception = assertThrows(
+            IllegalStateException.class,
+            () -> membershipManager.onHeartbeatSuccess(response)
+        );
+
+        assertEquals(
+            "Invalid response data, task collections must be all null or all non-null: " + response.data(),
+            exception.getMessage()
+        );
+    }
+
+    @Test
+    public void testJoining() {
+        joining();
+
+        verifyInStateJoining(membershipManager);
+        assertEquals(StreamsGroupHeartbeatRequest.JOIN_GROUP_MEMBER_EPOCH, membershipManager.memberEpoch());
+    }
+
+    @Test
+    public void testReconcilingEmptyToSingleActiveTask() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        joining();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_0));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingActiveTaskToDifferentActiveTask() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        when(subscriptionState.assignedPartitions())
+            .thenReturn(Collections.emptySet())
+            .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0)));
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingSingleActiveTaskToAdditionalActiveTask() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        when(subscriptionState.assignedPartitions())
+            .thenReturn(Collections.emptySet())
+            .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0)));
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0, PARTITION_1)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
+            new TopicPartition(TOPIC_0, PARTITION_0),
+            new TopicPartition(TOPIC_0, PARTITION_1)
+        );
+        final Collection<TopicPartition> expectedAdditionalPartitionAssignment = Set.of(new TopicPartition(TOPIC_0, PARTITION_1));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(
+            expectedPartitionAssignment,
+            expectedAdditionalPartitionAssignment
+        );
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingMultipleActiveTaskToSingleActiveTask() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, TOPIC_0);
+        when(subscriptionState.assignedPartitions())
+            .thenReturn(Collections.emptySet())
+            .thenReturn(Set.of(new TopicPartition(TOPIC_0, PARTITION_0), new TopicPartition(TOPIC_0, PARTITION_1)));
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0, PARTITION_1)));
+        acknowledging();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
+            new TopicPartition(TOPIC_0, PARTITION_1)
+        );
+        final Collection<TopicPartition> expectedAdditionalPartitionAssignment = Collections.emptySet();
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(
+            expectedPartitionAssignment,
+            expectedAdditionalPartitionAssignment
+        );
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_1)
+        );
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedAdditionalPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingEmptyToMultipleActiveTaskOfDifferentSubtopologies() {
+        setupStreamsAssignmentInterfaceWithTwoSubtopologies(
+            SUB_TOPOLOGY_ID_0, TOPIC_0,
+            SUB_TOPOLOGY_ID_1, TOPIC_1
+        );
+        joining();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0), SUB_TOPOLOGY_ID_1, List.of(PARTITION_0)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
+            new TopicPartition(TOPIC_0, PARTITION_0),
+            new TopicPartition(TOPIC_1, PARTITION_0)
+        );
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_1, PARTITION_0)
+        );
+        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingEmptyToMultipleActiveTaskOfConcatenatedSubtopologies() {
+        setupStreamsAssignmentInterfaceWithTwoConcatenedSubtopologies(
+            SUB_TOPOLOGY_ID_0, TOPIC_0,
+            SUB_TOPOLOGY_ID_1, TOPIC_1
+        );
+        joining();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0), SUB_TOPOLOGY_ID_1, List.of(PARTITION_0)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(
+            new TopicPartition(TOPIC_0, PARTITION_0),
+            new TopicPartition(TOPIC_1, PARTITION_0)
+        );
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks = Set.of(
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0),
+            new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_1, PARTITION_0)
+        );
+        final StreamsAssignmentInterface.Assignment expectedTaskAssignment = makeTaskAssignment(activeTasks);
+        assertEquals(expectedTaskAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    @Test
+    public void testReconcilingAndAssignmentCallbackFails() {
+        final String topicName = "test_topic";
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, topicName);
+        final Set<StreamsAssignmentInterface.TaskId> activeTasks =
+            Set.of(new StreamsAssignmentInterface.TaskId(SUB_TOPOLOGY_ID_0, PARTITION_0));
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(activeTasks);
+        joining();
+
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+
+        final Collection<TopicPartition> expectedPartitionAssignment = Set.of(new TopicPartition(topicName, PARTITION_0));
+        verify(subscriptionState).assignFromSubscribedAwaitingCallback(expectedPartitionAssignment, expectedPartitionAssignment);
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+        verifyInStateReconciling(membershipManager);
+        onAssignmentCallbackNeededEvent.future().completeExceptionally(new RuntimeException("KABOOM!"));
+        verifyInStateReconciling(membershipManager);
+        verify(subscriptionState, never()).enablePartitionsAwaitingCallback(expectedPartitionAssignment);
+    }
+
+    @Test
+    public void testLeaveGroupWhenNotInGroup() {
+        final CompletableFuture<Void> future = membershipManager.leaveGroup();
+
+        assertFalse(membershipManager.isLeavingGroup());
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertFalse(future.isCompletedExceptionally());
+        verify(subscriptionState).unsubscribe();
+        verifyInStateUnsubscribed(membershipManager);
+    }
+
+    @Test
+    public void testLeaveGroupWhenNotInGroupAndFenced() {
+        joining();
+        fenced();
+        final CompletableFuture<Void> future = membershipManager.leaveGroup();
+
+        assertFalse(membershipManager.isLeavingGroup());
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertFalse(future.isCompletedExceptionally());
+        verify(subscriptionState).unsubscribe();
+        verify(subscriptionState).assignFromSubscribed(Collections.emptySet());
+        verifyInStateUnsubscribed(membershipManager);
+    }
+
+    @Test
+    public void testLeaveGroupWhenInGroupWithAssignment() {
+        final StreamsAssignmentInterface.Assignment emptyStreamsAssignment = makeTaskAssignment(Collections.emptySet());
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        final CompletableFuture<Void> future = membershipManager.leaveGroup();
+
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        assertEquals(emptyStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        verify(subscriptionState, never()).unsubscribe();
+        verifyInStatePrepareLeaving(membershipManager);
+        final CompletableFuture<Void> futureBeforeRevocationCallback = membershipManager.leaveGroup();
+        assertEquals(future, futureBeforeRevocationCallback);
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).unsubscribe();
+        assertFalse(future.isDone());
+        verifyInStateLeaving(membershipManager);
+        final CompletableFuture<Void> futureAfterRevocationCallback = membershipManager.leaveGroup();
+        assertEquals(future, futureAfterRevocationCallback);
+        membershipManager.transitionToUnsubscribeIfLeaving();
+        verifyInStateUnsubscribed(membershipManager);
+    }
+
+    @Test
+    public void testTransitionToUnsubscribeWhenInLeaving() {
+        final StreamsGroupHeartbeatResponse response = makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0));
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        joining();
+        reconcile(response);
+        acknowledging();
+        CompletableFuture<Void> future = leaving();
+
+        membershipManager.transitionToUnsubscribeIfLeaving();
+
+        verifyInStateUnsubscribed(membershipManager);
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertFalse(future.isCompletedExceptionally());
+    }
+
+    @Test
+    public void testOnPollTimerExpired() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        membershipManager.onPollTimerExpired();
+
+        verifyInStateLeaving(membershipManager);
+        assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH, membershipManager.memberEpoch());
+    }
+
+    @Test
+    public void testOnHeartbeatRequestGeneratedWhenInAcknowleding() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        membershipManager.onHeartbeatRequestGenerated();
+
+        verifyInStateStable(membershipManager);
+    }
+
+    @Test
+    public void testOnHeartbeatRequestGeneratedWhenInAcknowledgingAndNewTargetAssignment() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_1)));
+        acknowledging();
+
+        membershipManager.onHeartbeatRequestGenerated();
+
+        verifyInStateReconciling(membershipManager);
+    }
+
+    @Test
+    public void testOnHeartbeatRequestGeneratedWhenInLeaving() {
+        joining();
+        leaving();
+
+        membershipManager.onHeartbeatRequestGenerated();
+
+        verifyInStateUnsubscribed(membershipManager);
+    }
+
+    @Test
+    public void testOnHeartbeatRequestGeneratedWhenInLeavingAndPollTimerExpired() {
+        joining();
+        membershipManager.onPollTimerExpired();
+
+        membershipManager.onHeartbeatRequestGenerated();
+
+        verifyInStateStale(membershipManager);
+    }
+
+    @Test
+    public void testOnFencedWhenInJoining() {
+        joining();
+
+        testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testOnFencedWhenInReconciling() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        backgroundEventQueue.poll();
+
+        testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testOnFencedWhenInAcknowledging() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testOnFencedWhenInStable() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+        stable();
+
+        testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    private void testOnFencedWhenInJoiningOrReconcilingOrAcknowledgingOrStable() {
+        membershipManager.onFenced();
+
+        verifyInStateFenced(membershipManager);
+        assertEquals(StreamsGroupHeartbeatRequest.JOIN_GROUP_MEMBER_EPOCH, membershipManager.memberEpoch());
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(Collections.emptySet());
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).assignFromSubscribed(Collections.emptySet());
+        verifyInStateJoining(membershipManager);
+    }
+
+    @Test
+    public void testOnFencedWhenInPrepareLeaving() {
+        joining();
+
+        testOnFencedWhenInPrepareLeavingOrLeaving(prepareLeaving());
+    }
+
+    @Test
+    public void testOnFencedWhenInLeaving() {
+        joining();
+
+        testOnFencedWhenInPrepareLeavingOrLeaving(leaving());
+    }
+
+    private void testOnFencedWhenInPrepareLeavingOrLeaving(final CompletableFuture<Void> onGroupLeft) {
+        membershipManager.onFenced();
+
+        verifyInStateUnsubscribed(membershipManager);
+        assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH, membershipManager.memberEpoch());
+        assertTrue(onGroupLeft.isDone());
+        assertFalse(onGroupLeft.isCancelled());
+        assertFalse(onGroupLeft.isCompletedExceptionally());
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInPrepareLeaving() {
+        joining();
+
+        testTransitionToFatalWhenInPrepareLeavingOrLeaving(prepareLeaving());
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInLeaving() {
+        joining();
+
+        testTransitionToFatalWhenInPrepareLeavingOrLeaving(leaving());
+    }
+
+    private void testTransitionToFatalWhenInPrepareLeavingOrLeaving(final CompletableFuture<Void> onGroupLeft) {
+        membershipManager.transitionToFatal();
+
+        verifyInStateFatal(membershipManager);
+        assertTrue(onGroupLeft.isDone());
+        assertFalse(onGroupLeft.isCancelled());
+        assertFalse(onGroupLeft.isCompletedExceptionally());
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInJoining() {
+        joining();
+
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInReconciling() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        backgroundEventQueue.poll();
+
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInAcknowledging() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    @Test
+    public void testTransitionToFatalWhenInStable() {
+        setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(SUB_TOPOLOGY_ID_0, "topic0");
+        joining();
+        reconcile(makeHeartbeatResponse(SUB_TOPOLOGY_ID_0, List.of(PARTITION_0)));
+        acknowledging();
+        stable();
+
+        testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable();
+    }
+
+    private void testTransitionToFatalWhenInJoiningOrReconcilingOrAcknowledgingOrStable() {
+        membershipManager.transitionToFatal();
+
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        final StreamsAssignmentInterface.Assignment expectedStreamsAssignment = makeTaskAssignment(Collections.emptySet());
+        assertEquals(expectedStreamsAssignment, onAssignmentCallbackNeededEvent.assignment());
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verify(subscriptionState).assignFromSubscribed(Collections.emptySet());
+        verifyInStateFatal(membershipManager);
+    }
+
+    @Test
+    public void testOnTaskAssignmentCallbackCompleted() {
+        final CompletableFuture<Void> future = new CompletableFuture<>();
+        final StreamsOnAssignmentCallbackCompletedEvent event = new StreamsOnAssignmentCallbackCompletedEvent(
+            future,
+            Optional.empty()
+        );
+
+        membershipManager.onTaskAssignmentCallbackCompleted(event);
+
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertFalse(future.isCompletedExceptionally());
+    }
+
+    @Test
+    public void testOnTaskAssignmentCallbackCompletedWhenCallbackFails() {
+        final String errorMessage = "KABOOM!";
+        final CompletableFuture<Void> future = new CompletableFuture<>();
+        final StreamsOnAssignmentCallbackCompletedEvent event = new StreamsOnAssignmentCallbackCompletedEvent(
+            future,
+            Optional.of(new KafkaException(errorMessage))
+        );
+
+        membershipManager.onTaskAssignmentCallbackCompleted(event);
+
+        assertTrue(future.isDone());
+        assertFalse(future.isCancelled());
+        assertTrue(future.isCompletedExceptionally());
+        final ExecutionException executionException = assertThrows(ExecutionException.class, future::get);
+        assertInstanceOf(KafkaException.class, executionException.getCause());
+        assertEquals(errorMessage, executionException.getCause().getMessage());
+    }
+
+    private static void verifyInStateReconciling(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.RECONCILING, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateAcknowledging(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.ACKNOWLEDGING, membershipManager.state());
+        assertTrue(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateLeaving(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.LEAVING, membershipManager.state());
+        assertTrue(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertTrue(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStatePrepareLeaving(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.PREPARE_LEAVING, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertTrue(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateUnsubscribed(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.UNSUBSCRIBED, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertTrue(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateJoining(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.JOINING, membershipManager.state());
+        assertTrue(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateStable(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.STABLE, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertFalse(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateFenced(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.FENCED, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertTrue(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateFatal(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.FATAL, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertTrue(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private static void verifyInStateStale(final StreamsMembershipManager membershipManager) {
+        assertEquals(MemberState.STALE, membershipManager.state());
+        assertFalse(membershipManager.shouldHeartbeatNow());
+        assertTrue(membershipManager.shouldSkipHeartbeat());
+        assertFalse(membershipManager.isLeavingGroup());
+    }
+
+    private void setupStreamsAssignmentInterfaceWithOneSubtopologyOneSourceTopic(final String subtopologyId,
+                                                                                 final String topicName) {
+        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
+            mkMap(
+                mkEntry(
+                    subtopologyId,
+                    new StreamsAssignmentInterface.Subtopology(
+                        Set.of(topicName),
+                        Collections.emptySet(),
+                        Collections.emptyMap(),
+                        Collections.emptyMap(),
+                        Collections.emptyList()
+                    )
+                )
+            )
+        );
+    }
+
+    private void setupStreamsAssignmentInterfaceWithTwoSubtopologies(final String subtopologyId1,
+                                                                     final String topicName1,
+                                                                     final String subtopologyId2,
+                                                                     final String topicName2) {
+        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
+            mkMap(
+                mkEntry(
+                    subtopologyId1,
+                    new StreamsAssignmentInterface.Subtopology(
+                        Set.of(topicName1),
+                        Collections.emptySet(),
+                        Collections.emptyMap(),
+                        Collections.emptyMap(),
+                        Collections.emptyList()
+                    )
+                ),
+                mkEntry(
+                    subtopologyId2,
+                    new StreamsAssignmentInterface.Subtopology(
+                        Set.of(topicName2),
+                        Collections.emptySet(),
+                        Collections.emptyMap(),
+                        Collections.emptyMap(),
+                        Collections.emptyList()
+                    )
+                )
+            )
+        );
+    }
+
+    private void setupStreamsAssignmentInterfaceWithTwoConcatenedSubtopologies(final String subtopologyId1,
+                                                                               final String topicName1,
+                                                                               final String subtopologyId2,
+                                                                               final String topicName2) {
+        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
+            mkMap(
+                mkEntry(
+                    subtopologyId1,
+                    new StreamsAssignmentInterface.Subtopology(
+                        Set.of(topicName1),
+                        Collections.emptySet(),
+                        Collections.emptyMap(),
+                        Collections.emptyMap(),
+                        Collections.emptyList()
+                    )
+                ),
+                mkEntry(
+                    subtopologyId2,
+                    new StreamsAssignmentInterface.Subtopology(
+                        Set.of(topicName2),
+                        Collections.emptySet(),
+                        mkMap(mkEntry(
+                            topicName2,
+                            new StreamsAssignmentInterface.TopicInfo(
+                                Optional.empty(),
+                                Optional.empty(),
+                                Collections.emptyMap()
+                            )
+                        )),
+                        Collections.emptyMap(),
+                        Collections.emptyList()
+                    )
+                )
+            )
+        );
+    }
+
+    private StreamsGroupHeartbeatResponse makeHeartbeatResponse(final String subtopologyId,
+                                                                final List<Integer> partitions) {
+        return makeHeartbeatResponse(Collections.singletonList(
+            new StreamsGroupHeartbeatResponseData.TaskIds()
+                .setSubtopologyId(subtopologyId)
+                .setPartitions(partitions)
+        ));
+    }
+
+    private StreamsGroupHeartbeatResponse makeHeartbeatResponse(final String subtopologyId0,
+                                                                final List<Integer> partitions0,
+                                                                final String subtopologyId1,
+                                                                final List<Integer> partitions1) {
+        return makeHeartbeatResponse(List.of(
+            new StreamsGroupHeartbeatResponseData.TaskIds()
+                .setSubtopologyId(subtopologyId0)
+                .setPartitions(partitions0),
+            new StreamsGroupHeartbeatResponseData.TaskIds()
+                .setSubtopologyId(subtopologyId1)
+                .setPartitions(partitions1)
+        ));
+    }
+
+    private StreamsGroupHeartbeatResponse makeHeartbeatResponse(final List<StreamsGroupHeartbeatResponseData.TaskIds> activeTasks) {
+        final StreamsGroupHeartbeatResponseData responseData = new StreamsGroupHeartbeatResponseData()
+            .setErrorCode(Errors.NONE.code())
+            .setMemberId(MEMBER_ID)
+            .setMemberEpoch(MEMBER_EPOCH)
+            .setActiveTasks(activeTasks)
+            .setStandbyTasks(Collections.emptyList())
+            .setWarmupTasks(Collections.emptyList());
+        return new StreamsGroupHeartbeatResponse(responseData);
+    }
+
+    private StreamsAssignmentInterface.Assignment makeTaskAssignment(final Set<StreamsAssignmentInterface.TaskId> activeTasks) {
+        return new StreamsAssignmentInterface.Assignment(
+            activeTasks,
+            Collections.emptySet(),
+            Collections.emptySet()
+        );
+    }
+
+    private void joining() {
+        membershipManager.onSubscriptionUpdated();
+        membershipManager.onConsumerPoll();
+        verifyInStateJoining(membershipManager);
+    }
+
+    private void reconcile(final StreamsGroupHeartbeatResponse response) {
+        membershipManager.onHeartbeatSuccess(response);
+        membershipManager.poll(time.milliseconds());
+        verifyInStateReconciling(membershipManager);
+
+    }
+
+    private void acknowledging() {
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verifyInStateAcknowledging(membershipManager);
+    }
+
+    private CompletableFuture<Void> prepareLeaving() {
+        final CompletableFuture<Void> onGroupLeft = membershipManager.leaveGroup();
+        verifyInStatePrepareLeaving(membershipManager);
+        return onGroupLeft;
+    }
+
+    private CompletableFuture<Void> leaving() {
+        final CompletableFuture<Void> future = prepareLeaving();
+        final StreamsOnAssignmentCallbackNeededEvent onAssignmentCallbackNeededEvent =
+            (StreamsOnAssignmentCallbackNeededEvent) backgroundEventQueue.poll();
+        onAssignmentCallbackNeededEvent.future().complete(null);
+        verifyInStateLeaving(membershipManager);
+        return future;
+    }
+
+    private void stable() {
+        membershipManager.onHeartbeatRequestGenerated();
+    }
+
+    private void fenced() {
+        membershipManager.onFenced();
+    }
+}
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index 27e709490be..90e17194b6f 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -1447,12 +1447,12 @@ public class StreamThread extends Thread implements ProcessingThread {
         return taskIdStream
             .collect(Collectors.toMap(
                 this::toTaskId,
-                task -> toTopicPartitions(task, streamsAssignmentInterface.subtopologyMap().get(task.subtopologyId))
+                task -> toTopicPartitions(task, streamsAssignmentInterface.subtopologyMap().get(task.subtopologyId()))
             ));
     }
 
     private TaskId toTaskId(final StreamsAssignmentInterface.TaskId task) {
-        return new TaskId(Integer.parseInt(task.subtopologyId), task.partitionId);
+        return new TaskId(Integer.parseInt(task.subtopologyId()), task.partitionId());
     }
 
     private Set<TopicPartition> toTopicPartitions(final StreamsAssignmentInterface.TaskId task,
@@ -1462,7 +1462,7 @@ public class StreamThread extends Thread implements ProcessingThread {
                 subTopology.sourceTopics.stream(),
                 subTopology.repartitionSourceTopics.keySet().stream()
             )
-            .map(t -> new TopicPartition(t, task.partitionId))
+            .map(t -> new TopicPartition(t, task.partitionId()))
             .collect(Collectors.toSet());
     }
 


(kafka) 04/42: Resolve merge conflict from 11/25 rebase - Specify AsyncKafkaConsumer interface with Streams for the Rebalance PoC

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 9e3ba3e0f5a88b6d5c4af7fcb0e9aa563366c861
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Thu May 16 22:27:46 2024 +0200

    Resolve merge conflict from 11/25 rebase - Specify AsyncKafkaConsumer interface with Streams for the Rebalance PoC
    
    Extend internal AsyncKafkaConsumer interface to exchange rebalance information with Streams.
    
    See https://github.com/lucasbru/kafka/pull/9
---
 .../consumer/internals/AsyncKafkaConsumer.java     |  25 ++-
 .../internals/ConsumerDelegateCreator.java         |   6 +-
 .../consumer/internals/RequestManagers.java        |  31 ++-
 .../internals/StreamsAssignmentInterface.java      | 216 +++++++++++++++++++++
 .../internals/StreamsHeartbeatRequestManager.java  |  68 +++++++
 .../internals/StreamsInitializeRequestManager.java |  38 ++++
 .../StreamsInstallAssignmentRequestManager.java    |  34 ++++
 .../StreamsPrepareAssignmentRequestManager.java    |  37 ++++
 .../consumer/internals/AsyncKafkaConsumerTest.java |   6 +-
 .../consumer/internals/RequestManagersTest.java    |   3 +-
 .../events/ApplicationEventProcessorTest.java      |   8 +-
 .../apache/kafka/streams/KafkaClientSupplier.java  |  11 ++
 .../internals/DefaultKafkaClientSupplier.java      |  12 ++
 .../streams/processor/internals/StreamThread.java  |  86 +++++++-
 .../org/apache/kafka/test/MockClientSupplier.java  |   5 +
 .../apache/kafka/streams/TopologyTestDriver.java   |   2 +
 16 files changed, 570 insertions(+), 18 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
index 32e5fe32f48..807c900f6b9 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
@@ -275,9 +275,10 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
         }
     };
 
-    AsyncKafkaConsumer(final ConsumerConfig config,
-                       final Deserializer<K> keyDeserializer,
-                       final Deserializer<V> valueDeserializer) {
+   public AsyncKafkaConsumer(final ConsumerConfig config,
+                              final Deserializer<K> keyDeserializer,
+                              final Deserializer<V> valueDeserializer,
+                              final Optional<StreamsAssignmentInterface> streamsAssignmentInterface) {
         this(
             config,
             keyDeserializer,
@@ -287,7 +288,8 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
             CompletableEventReaper::new,
             FetchCollector::new,
             ConsumerMetadata::new,
-            new LinkedBlockingQueue<>()
+            new LinkedBlockingQueue<>(),
+            streamsAssignmentInterface
         );
     }
 
@@ -300,7 +302,9 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                        final CompletableEventReaperFactory backgroundEventReaperFactory,
                        final FetchCollectorFactory<K, V> fetchCollectorFactory,
                        final ConsumerMetadataFactory metadataFactory,
-                       final LinkedBlockingQueue<BackgroundEvent> backgroundEventQueue) {
+                       final LinkedBlockingQueue<BackgroundEvent> backgroundEventQueue,
+                       final Optional<StreamsAssignmentInterface> streamsAssignmentInterface
+                       ) {
         try {
             GroupRebalanceConfig groupRebalanceConfig = new GroupRebalanceConfig(
                 config,
@@ -367,7 +371,9 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                     clientTelemetryReporter,
                     metrics,
                     offsetCommitCallbackInvoker,
-                    memberStateListener
+                    memberStateListener,
+                    this::updateGroupMetadata,
+                    streamsAssignmentInterface
             );
             final Supplier<ApplicationEventProcessor> applicationEventProcessorSupplier = ApplicationEventProcessor.supplier(logContext,
                     metadata,
@@ -471,7 +477,8 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                        Deserializer<V> valueDeserializer,
                        KafkaClient client,
                        SubscriptionState subscriptions,
-                       ConsumerMetadata metadata) {
+                       ConsumerMetadata metadata,
+                       Optional<StreamsAssignmentInterface> streamsInstanceMetadata) {
         this.log = logContext.logger(getClass());
         this.subscriptions = subscriptions;
         this.clientId = config.getString(ConsumerConfig.CLIENT_ID_CONFIG);
@@ -539,7 +546,9 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
             clientTelemetryReporter,
             metrics,
             offsetCommitCallbackInvoker,
-            memberStateListener
+            memberStateListener,
+            this::updateGroupMetadata,
+            streamsInstanceMetadata
         );
         Supplier<ApplicationEventProcessor> applicationEventProcessorSupplier = ApplicationEventProcessor.supplier(
                 logContext,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
index 74592972b9d..3f5926080fc 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/ConsumerDelegateCreator.java
@@ -29,6 +29,7 @@ import org.apache.kafka.common.utils.Time;
 
 import java.util.List;
 import java.util.Locale;
+import java.util.Optional;
 
 /**
  * {@code ConsumerDelegateCreator} implements a quasi-factory pattern to allow the caller to remain unaware of the
@@ -60,7 +61,7 @@ public class ConsumerDelegateCreator {
             GroupProtocol groupProtocol = GroupProtocol.valueOf(config.getString(ConsumerConfig.GROUP_PROTOCOL_CONFIG).toUpperCase(Locale.ROOT));
 
             if (groupProtocol == GroupProtocol.CONSUMER)
-                return new AsyncKafkaConsumer<>(config, keyDeserializer, valueDeserializer);
+                return new AsyncKafkaConsumer<>(config, keyDeserializer, valueDeserializer, Optional.empty());
             else
                 return new ClassicKafkaConsumer<>(config, keyDeserializer, valueDeserializer);
         } catch (KafkaException e) {
@@ -91,7 +92,8 @@ public class ConsumerDelegateCreator {
                     valueDeserializer,
                     client,
                     subscriptions,
-                    metadata
+                    metadata,
+                    Optional.empty()
                 );
             else
                 return new ClassicKafkaConsumer<>(
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 304f0fffd4a..5045743848d 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -58,6 +58,9 @@ public class RequestManagers implements Closeable {
     public final TopicMetadataRequestManager topicMetadataRequestManager;
     public final FetchRequestManager fetchRequestManager;
     public final Optional<ShareConsumeRequestManager> shareConsumeRequestManager;
+    public final Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager;
+    public final Optional<StreamsPrepareAssignmentRequestManager> streamsPrepareAssignmentRequestManager;
+    public final Optional<StreamsInstallAssignmentRequestManager> streamsInstallAssignmentRequestManager;
     private final List<Optional<? extends RequestManager>> entries;
     private final IdempotentCloser closer = new IdempotentCloser();
 
@@ -69,6 +72,10 @@ public class RequestManagers implements Closeable {
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
                            Optional<ConsumerMembershipManager> membershipManager) {
+                           Optional<StreamsHeartbeatRequestManager> streamsHeartbeatRequestManager,
+                           Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager,
+                           Optional<StreamsPrepareAssignmentRequestManager> streamsPrepareAssignmentRequestManager,
+                           Optional<StreamsInstallAssignmentRequestManager> streamsInstallAssignmentRequestManager) {
         this.log = logContext.logger(RequestManagers.class);
         this.offsetsRequestManager = requireNonNull(offsetsRequestManager, "OffsetsRequestManager cannot be null");
         this.coordinatorRequestManager = coordinatorRequestManager;
@@ -80,6 +87,10 @@ public class RequestManagers implements Closeable {
         this.shareHeartbeatRequestManager = Optional.empty();
         this.consumerMembershipManager = membershipManager;
         this.shareMembershipManager = Optional.empty();
+        this.streamsHeartbeatRequestManager = streamsHeartbeatRequestManager;
+        this.streamsInitializeRequestManager = streamsInitializeRequestManager;
+        this.streamsPrepareAssignmentRequestManager = streamsPrepareAssignmentRequestManager;
+        this.streamsInstallAssignmentRequestManager = streamsInstallAssignmentRequestManager;
 
         List<Optional<? extends RequestManager>> list = new ArrayList<>();
         list.add(coordinatorRequestManager);
@@ -89,6 +100,10 @@ public class RequestManagers implements Closeable {
         list.add(Optional.of(offsetsRequestManager));
         list.add(Optional.of(topicMetadataRequestManager));
         list.add(Optional.of(fetchRequestManager));
+        list.add(streamsHeartbeatRequestManager);
+        list.add(streamsInitializeRequestManager);
+        list.add(streamsPrepareAssignmentRequestManager);
+        list.add(streamsInstallAssignmentRequestManager);
         entries = Collections.unmodifiableList(list);
     }
 
@@ -158,7 +173,8 @@ public class RequestManagers implements Closeable {
                                                      final Optional<ClientTelemetryReporter> clientTelemetryReporter,
                                                      final Metrics metrics,
                                                      final OffsetCommitCallbackInvoker offsetCommitCallbackInvoker,
-                                                     final MemberStateListener applicationThreadMemberStateListener
+                                                     final MemberStateListener applicationThreadMemberStateListener,
+                                                     final Optional<StreamsAssignmentInterface> streamsInstanceMetadata
                                                      ) {
         return new CachedSupplier<>() {
             @Override
@@ -187,6 +203,10 @@ public class RequestManagers implements Closeable {
                 ConsumerMembershipManager membershipManager = null;
                 CoordinatorRequestManager coordinator = null;
                 CommitRequestManager commitRequestManager = null;
+                StreamsHeartbeatRequestManager streamsHeartbeatRequestManager = null;
+                StreamsInitializeRequestManager streamsInitializeRequestManager = null;
+                StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager = null;
+                StreamsInstallAssignmentRequestManager streamsInstallAssignmentRequestManager = null;
 
                 if (groupRebalanceConfig != null && groupRebalanceConfig.groupId != null) {
                     Optional<String> serverAssignor = Optional.ofNullable(config.getString(ConsumerConfig.GROUP_REMOTE_ASSIGNOR_CONFIG));
@@ -230,7 +250,7 @@ public class RequestManagers implements Closeable {
 
                     membershipManager.registerStateListener(commitRequestManager);
                     membershipManager.registerStateListener(applicationThreadMemberStateListener);
-                    heartbeatRequestManager = new ConsumerHeartbeatRequestManager(
+
                             logContext,
                             time,
                             config,
@@ -239,6 +259,7 @@ public class RequestManagers implements Closeable {
                             membershipManager,
                             backgroundEventHandler,
                             metrics);
+                    }
                 }
 
                 final OffsetsRequestManager listOffsets = new OffsetsRequestManager(subscriptions,
@@ -261,7 +282,11 @@ public class RequestManagers implements Closeable {
                         Optional.ofNullable(coordinator),
                         Optional.ofNullable(commitRequestManager),
                         Optional.ofNullable(heartbeatRequestManager),
-                        Optional.ofNullable(membershipManager)
+                        Optional.ofNullable(membershipManager),
+                        Optional.ofNullable(streamsHeartbeatRequestManager),
+                        Optional.ofNullable(streamsInitializeRequestManager),
+                        Optional.ofNullable(streamsPrepareAssignmentRequestManager),
+                        Optional.ofNullable(streamsInstallAssignmentRequestManager)
                 );
             }
         };
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
new file mode 100644
index 00000000000..acc7e314362
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -0,0 +1,216 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Defines a self-contained object to exchange assignment-related metadata with the Kafka Streams instance.
+ *
+ * It's used to exchange information between the streams module and the clients module, and should be mostly self-contained
+ */
+public class StreamsAssignmentInterface {
+
+    private UUID processID;
+
+    private String userEndPointHost;
+
+    private int userEndPointPort;
+
+    private Map<String, SubTopology> subtopologyMap;
+
+    private Map<String, Object> assignmentConfiguration;
+
+    private Map<TaskId, Long> taskLags;
+
+    private AtomicBoolean shutdownRequested;
+
+    private Map<String, String> clientTags;
+
+    public UUID processID() {
+        return processID;
+    }
+
+    public String userEndPointHost() {
+        return userEndPointHost;
+    }
+
+    public int userEndPointPort() {
+        return userEndPointPort;
+    }
+
+    public Map<String, SubTopology> subtopologyMap() {
+        return subtopologyMap;
+    }
+
+    public Map<String, Object> assignmentConfiguration() {
+        return assignmentConfiguration;
+    }
+
+    public Map<TaskId, Long> taskLags() {
+        return taskLags;
+    }
+
+    public byte[] computeTopologyHash() {
+        // TODO
+        return new byte[0];
+    }
+
+    public Map<String, String> clientTags() {
+        return clientTags;
+    }
+
+    public void requestShutdown() {
+        shutdownRequested.set(true);
+    }
+
+    public boolean shutdownRequested() {
+        return shutdownRequested.get();
+    }
+
+    public void setTaskLags(Map<TaskId, Long> taskLags) {
+        this.taskLags = taskLags;
+    }
+
+    // TODO: Reconciled assignment updated by the stream thread
+    public final Assignment reconciledAssignment = new Assignment();
+
+    // TODO: Target assignment read by the stream thread
+    public final Assignment targetAssignment = new Assignment();
+
+    public static class Assignment {
+
+        public final Set<TaskId> activeTasks = new HashSet<>();
+
+        public final Set<TaskId> standbyTasks = new HashSet<>();
+
+        public final Set<TaskId> warmupTasks = new HashSet<>();
+
+    }
+
+    public static class TopicInfo {
+
+        public final Optional<Integer> numPartitions;
+        public final Map<String, String> topicConfigs;
+
+        public TopicInfo(final Optional<Integer> numPartitions,
+                         final Map<String, String> topicConfigs) {
+            this.numPartitions = numPartitions;
+            this.topicConfigs = topicConfigs;
+        }
+
+        @Override
+        public String toString() {
+            return "TopicInfo{" +
+                "numPartitions=" + numPartitions +
+                ", topicConfigs=" + topicConfigs +
+                '}';
+        }
+
+    }
+
+    public static class TaskId {
+        public final String subtopologyId;
+        public final int taskId;
+
+        public int taskId() {
+            return taskId;
+        }
+
+        public String subtopologyId() {
+            return subtopologyId;
+        }
+
+        public TaskId(final String subtopologyId, final int taskId) {
+            this.subtopologyId = subtopologyId;
+            this.taskId = taskId;
+        }
+
+        @Override
+        public String toString() {
+            return "TaskId{" +
+                "subtopologyId=" + subtopologyId +
+                ", taskId=" + taskId +
+                '}';
+        }
+    }
+
+    public static class SubTopology {
+
+        public final Set<String> sinkTopics;
+        public final Set<String> sourceTopics;
+        public final Map<String, TopicInfo> stateChangelogTopics;
+        public final Map<String, TopicInfo> repartitionSourceTopics;
+
+       public SubTopology(final Set<String> sinkTopics,
+                          final Set<String> sourceTopics,
+                          final Map<String, TopicInfo> repartitionSourceTopics,
+                          final Map<String, TopicInfo> stateChangelogTopics) {
+            this.sinkTopics = sinkTopics;
+            this.sourceTopics = sourceTopics;
+            this.stateChangelogTopics = stateChangelogTopics;
+            this.repartitionSourceTopics = repartitionSourceTopics;
+        }
+
+        @Override
+        public String toString() {
+            return "SubTopology{" +
+                "sinkTopics=" + sinkTopics +
+                ", sourceTopics=" + sourceTopics +
+                ", stateChangelogTopics=" + stateChangelogTopics +
+                ", repartitionSourceTopics=" + repartitionSourceTopics +
+                '}';
+        }
+    }
+
+    public StreamsAssignmentInterface(UUID processID,
+                                      String userEndPointHost,
+                                      int userEndPointPort,
+                                      Map<String, SubTopology> subtopologyMap,
+                                      Map<String, Object> assignmentConfiguration,
+                                      Map<String, String> clientTags
+                                      ) {
+        this.processID = processID;
+        this.userEndPointHost = userEndPointHost;
+        this.userEndPointPort = userEndPointPort;
+        this.subtopologyMap = subtopologyMap;
+        this.assignmentConfiguration = assignmentConfiguration;
+        this.taskLags = new HashMap<>();
+        this.shutdownRequested = new AtomicBoolean(false);
+        this.clientTags = clientTags;
+    }
+
+    @Override
+    public String toString() {
+        return "StreamsAssignmentMetadata{" +
+            "processID=" + processID +
+            ", userEndPointHost='" + userEndPointHost + '\'' +
+            ", userEndPointPort=" + userEndPointPort +
+            ", subtopologyMap=" + subtopologyMap +
+            ", assignmentConfiguration=" + assignmentConfiguration +
+            ", taskLags=" + taskLags +
+            ", clientTags=" + clientTags +
+            '}';
+    }
+
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
new file mode 100644
index 00000000000..685ab28da69
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
@@ -0,0 +1,68 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
+import org.apache.kafka.clients.consumer.internals.events.ErrorEvent;
+import org.apache.kafka.clients.consumer.internals.metrics.HeartbeatMetricsManager;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.GroupAuthorizationException;
+import org.apache.kafka.common.errors.RetriableException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskId;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.StreamsHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsHeartbeatResponse;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.common.utils.Timer;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class StreamsHeartbeatRequestManager implements RequestManager {
+
+    private StreamsAssignmentInterface streamsInterface;
+
+    public StreamsHeartbeatRequestManager(
+        final StreamsInitializeRequestManager streamsInitializeRequestManager,
+        final StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager,
+        final StreamsAssignmentInterface streamsAssignmentInterface
+    ) {
+        this.streamsInterface = streamsAssignmentInterface;
+    }
+
+    @Override
+    public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
+        return null;
+    }
+
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
new file mode 100644
index 00000000000..73d2955ef2f
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -0,0 +1,38 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
+
+public class StreamsInitializeRequestManager implements RequestManager {
+
+    private final StreamsAssignmentInterface streamsAssignmentInterface;
+
+    StreamsInitializeRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
+        this.streamsAssignmentInterface = streamsAssignmentInterface;
+    }
+
+    @Override
+    public PollResult poll(final long currentTimeMs) {
+        // TODO: Return an initalize request
+        return PollResult.EMPTY;
+    }
+
+    public void initialize() {
+        // TODO: Create a `StreamsInitializeRequest`
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
new file mode 100644
index 00000000000..7936e885b56
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
@@ -0,0 +1,34 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
+
+public class StreamsInstallAssignmentRequestManager implements RequestManager {
+
+    private final StreamsAssignmentInterface streamsAssignmentInterface;
+
+    StreamsInstallAssignmentRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
+        this.streamsAssignmentInterface = streamsAssignmentInterface;
+    }
+
+    @Override
+    public PollResult poll(final long currentTimeMs) {
+        return null;
+    }
+
+}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
new file mode 100644
index 00000000000..069661f4893
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
@@ -0,0 +1,37 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
+
+public class StreamsPrepareAssignmentRequestManager implements RequestManager {
+
+    private final StreamsAssignmentInterface streamsAssignmentInterface;
+
+    StreamsPrepareAssignmentRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
+        this.streamsAssignmentInterface = streamsAssignmentInterface;
+    }
+
+    @Override
+    public PollResult poll(final long currentTimeMs) {
+        return null;
+    }
+
+    public void prepareAssignment() {
+        // TODO: Create a `StreamsPrepareAssignmentRequest`
+    }
+}
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
index 0f87fb9037c..3ba8e2a1cab 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
@@ -218,7 +218,8 @@ public class AsyncKafkaConsumerTest {
             a -> backgroundEventReaper,
             (a, b, c, d, e, f, g) -> fetchCollector,
             (a, b, c, d) -> metadata,
-            backgroundEventQueue
+            backgroundEventQueue,
+            Optional.empty()
         );
     }
 
@@ -1320,7 +1321,8 @@ public class AsyncKafkaConsumerTest {
             any(),
             any(),
             any(),
-            applicationThreadMemberStateListener.capture()
+            applicationThreadMemberStateListener.capture(),
+            any()
         ));
         return applicationThreadMemberStateListener.getValue();
     }
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/RequestManagersTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/RequestManagersTest.java
index 405ecabcf16..499c7f8f39d 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/RequestManagersTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/RequestManagersTest.java
@@ -62,7 +62,8 @@ public class RequestManagersTest {
             Optional.empty(),
             new Metrics(),
             mock(OffsetCommitCallbackInvoker.class),
-            listener
+            listener,
+            Optional.empty()
         ).get();
         requestManagers.consumerMembershipManager.ifPresent(
             membershipManager -> assertTrue(membershipManager.stateListeners().contains(listener))
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
index bdbda721b00..28f938c2657 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
@@ -95,7 +95,13 @@ public class ApplicationEventProcessorTest {
                 withGroupId ? Optional.of(mock(CoordinatorRequestManager.class)) : Optional.empty(),
                 withGroupId ? Optional.of(commitRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(heartbeatRequestManager) : Optional.empty(),
-                withGroupId ? Optional.of(membershipManager) : Optional.empty());
+                withGroupId ? Optional.of(membershipManager) : Optional.empty(),
+                Optional.empty(),
+                Optional.empty(),
+                Optional.empty(),
+                Optional.empty()
+        );
+
         processor = new ApplicationEventProcessor(
                 new LogContext(),
                 requestManagers,
diff --git a/streams/src/main/java/org/apache/kafka/streams/KafkaClientSupplier.java b/streams/src/main/java/org/apache/kafka/streams/KafkaClientSupplier.java
index fc96ca701c6..43065467f67 100644
--- a/streams/src/main/java/org/apache/kafka/streams/KafkaClientSupplier.java
+++ b/streams/src/main/java/org/apache/kafka/streams/KafkaClientSupplier.java
@@ -18,6 +18,7 @@ package org.apache.kafka.streams;
 
 import org.apache.kafka.clients.admin.Admin;
 import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.producer.Producer;
 import org.apache.kafka.streams.kstream.GlobalKTable;
 import org.apache.kafka.streams.processor.StateStore;
@@ -58,6 +59,16 @@ public interface KafkaClientSupplier {
      */
     Consumer<byte[], byte[]> getConsumer(final Map<String, Object> config);
 
+    /**
+     * Create a {@link Consumer} which is used to read records of source topics.
+     *
+     * @param config {@link StreamsConfig#getMainConsumerConfigs(String, String, int) consumer config} which is
+     *               supplied by the {@link java.util.Properties} given to the {@link KafkaStreams} instance
+     * @param assignmentInterface the assignment interface to take part in the streams rebalance protocol.
+     * @return an instance of Kafka consumer
+     */
+    Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config, StreamsAssignmentInterface assignmentInterface);
+
     /**
      * Create a {@link Consumer} which is used to read records to restore {@link StateStore}s.
      *
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
index a6419f1dba7..71ac9982d67 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
@@ -16,9 +16,13 @@
  */
 package org.apache.kafka.streams.processor.internals;
 
+import java.util.Optional;
 import org.apache.kafka.clients.admin.Admin;
 import org.apache.kafka.clients.consumer.Consumer;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.internals.AsyncKafkaConsumer;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
 import org.apache.kafka.common.serialization.ByteArrayDeserializer;
@@ -44,6 +48,14 @@ public class DefaultKafkaClientSupplier implements KafkaClientSupplier {
         return new KafkaConsumer<>(config, new ByteArrayDeserializer(), new ByteArrayDeserializer());
     }
 
+    @Override
+    public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config, StreamsAssignmentInterface assignmentInterface) {
+        ByteArrayDeserializer keyDeserializer = new ByteArrayDeserializer();
+        ByteArrayDeserializer valueDeserializer = new ByteArrayDeserializer();
+        return new AsyncKafkaConsumer<>(new ConsumerConfig(ConsumerConfig.appendDeserializerToConfig(config, keyDeserializer, valueDeserializer)),
+            keyDeserializer, valueDeserializer, Optional.of(assignmentInterface));
+    }
+
     @Override
     public Consumer<byte[], byte[]> getRestoreConsumer(final Map<String, Object> config) {
         return new KafkaConsumer<>(config, new ByteArrayDeserializer(), new ByteArrayDeserializer());
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index ceb2c403c3e..7433896fab8 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -22,8 +22,12 @@ import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.GroupProtocol;
 import org.apache.kafka.clients.consumer.InvalidOffsetException;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
+import org.apache.kafka.clients.consumer.OffsetResetStrategy;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.SubTopology;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.KafkaFuture;
 import org.apache.kafka.common.Metric;
@@ -52,12 +56,15 @@ import org.apache.kafka.streams.processor.StandbyUpdateListener;
 import org.apache.kafka.streams.processor.StateRestoreListener;
 import org.apache.kafka.streams.processor.TaskId;
 import org.apache.kafka.streams.processor.assignment.ProcessId;
+import org.apache.kafka.streams.processor.internals.InternalTopologyBuilder.TopicsInfo;
+import org.apache.kafka.streams.processor.internals.TopologyMetadata.Subtopology;
 import org.apache.kafka.streams.processor.internals.assignment.AssignorError;
 import org.apache.kafka.streams.processor.internals.assignment.ReferenceContainer;
 import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
 import org.apache.kafka.streams.processor.internals.metrics.ThreadMetrics;
 import org.apache.kafka.streams.processor.internals.tasks.DefaultTaskManager;
 import org.apache.kafka.streams.processor.internals.tasks.DefaultTaskManager.DefaultTaskExecutorCreator;
+import org.apache.kafka.streams.state.HostInfo;
 import org.apache.kafka.streams.state.internals.ThreadCache;
 
 import org.slf4j.Logger;
@@ -475,7 +482,25 @@ public class StreamThread extends Thread implements ProcessingThread {
             consumerConfigs.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "none");
         }
 
-        final Consumer<byte[], byte[]> mainConsumer = clientSupplier.getConsumer(consumerConfigs);
+        final Consumer<byte[], byte[]> mainConsumer;
+        if (consumerConfigs.containsKey(ConsumerConfig.GROUP_PROTOCOL_CONFIG) &&
+            consumerConfigs.get(ConsumerConfig.GROUP_PROTOCOL_CONFIG).toString().equalsIgnoreCase(GroupProtocol.CONSUMER.name)) {
+            if (topologyMetadata.hasNamedTopologies()) {
+                throw new IllegalStateException("Named topologies and the CONSUMER protocol cannot be used at the same time.");
+            }
+            log.info("Streams rebalance protocol enabled");
+
+            StreamsAssignmentInterface streamsAssignmentInterface =
+                initAssignmentInterface(processId,
+                config,
+                parseHostInfo(config.getString(StreamsConfig.APPLICATION_SERVER_CONFIG)),
+                topologyMetadata);
+
+            mainConsumer = clientSupplier.getStreamsRebalanceProtocolConsumer(consumerConfigs, streamsAssignmentInterface);
+        } else {
+            mainConsumer = clientSupplier.getConsumer(consumerConfigs);
+        }
+
         taskManager.setMainConsumer(mainConsumer);
         referenceContainer.mainConsumer = mainConsumer;
 
@@ -507,6 +532,65 @@ public class StreamThread extends Thread implements ProcessingThread {
         return streamThread.updateThreadMetadata(adminClientId(clientId));
     }
 
+    private static HostInfo parseHostInfo(final String endPoint) {
+        final HostInfo hostInfo = HostInfo.buildFromEndpoint(endPoint);
+        if (hostInfo == null) {
+            return StreamsMetadataState.UNKNOWN_HOST;
+        } else {
+            return hostInfo;
+        }
+    }
+
+    private static StreamsAssignmentInterface initAssignmentInterface(UUID processId,
+                                                                      StreamsConfig config,
+                                                                      HostInfo hostInfo,
+                                                                      final TopologyMetadata topologyMetadata) {
+        final InternalTopologyBuilder internalTopologyBuilder = topologyMetadata.lookupBuilderForNamedTopology(null);
+
+        Map<String, SubTopology> subtopologyMap = new HashMap<>();
+        for (Map.Entry<Subtopology, TopicsInfo> topicsInfoEntry: internalTopologyBuilder.subtopologyToTopicsInfo().entrySet()) {
+            subtopologyMap.put(
+                String.valueOf(topicsInfoEntry.getKey().nodeGroupId),
+                new SubTopology(
+                    topicsInfoEntry.getValue().sourceTopics,
+                    topicsInfoEntry.getValue().sinkTopics,
+                    topicsInfoEntry.getValue().repartitionSourceTopics.entrySet()
+                        .stream()
+                        .collect(Collectors.toMap(Map.Entry::getKey , e->
+                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs))),
+                    topicsInfoEntry.getValue().stateChangelogTopics.entrySet()
+                        .stream()
+                        .collect(Collectors.toMap(Map.Entry::getKey , e->
+                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs)))
+
+                )
+            );
+        }
+
+        // TODO: Which of these are actually needed?
+        // TODO: Maybe we want to split this into assignment properties and internal topic configuration properties
+        HashMap<String, Object> assignmentProperties = new HashMap<>();
+        assignmentProperties.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, config.getInt(StreamsConfig.REPLICATION_FACTOR_CONFIG));
+        assignmentProperties.put(StreamsConfig.APPLICATION_SERVER_CONFIG, config.getString(StreamsConfig.APPLICATION_SERVER_CONFIG));
+        assignmentProperties.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, config.getInt(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG));
+        assignmentProperties.put(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG, config.getLong(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG));
+        assignmentProperties.put(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG, config.getInt(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG));
+        assignmentProperties.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG, config.getLong(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG, config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG, config.getString(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG, config.getList(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG, config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG));
+
+        return new StreamsAssignmentInterface(
+            processId,
+            hostInfo.host(),
+            hostInfo.port(),
+            subtopologyMap,
+            assignmentProperties,
+            config.getClientTags()
+        );
+    }
+
     private static DefaultTaskManager maybeCreateSchedulingTaskManager(final boolean processingThreadsEnabled,
                                                                        final boolean stateUpdaterEnabled,
                                                                        final TopologyMetadata topologyMetadata,
diff --git a/streams/src/test/java/org/apache/kafka/test/MockClientSupplier.java b/streams/src/test/java/org/apache/kafka/test/MockClientSupplier.java
index 37723f1e7cc..c25a6c3bb06 100644
--- a/streams/src/test/java/org/apache/kafka/test/MockClientSupplier.java
+++ b/streams/src/test/java/org/apache/kafka/test/MockClientSupplier.java
@@ -20,6 +20,7 @@ import org.apache.kafka.clients.admin.Admin;
 import org.apache.kafka.clients.admin.MockAdminClient;
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.consumer.MockConsumer;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.clients.producer.MockProducer;
 import org.apache.kafka.clients.producer.Producer;
@@ -89,6 +90,10 @@ public class MockClientSupplier implements KafkaClientSupplier {
     public Consumer<byte[], byte[]> getConsumer(final Map<String, Object> config) {
         return consumer;
     }
+    @Override
+    public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config, StreamsAssignmentInterface assignmentInterface) {
+        throw new IllegalArgumentException("Should not be called");
+    }
 
     @Override
     public Consumer<byte[], byte[]> getRestoreConsumer(final Map<String, Object> config) {
diff --git a/streams/test-utils/src/main/java/org/apache/kafka/streams/TopologyTestDriver.java b/streams/test-utils/src/main/java/org/apache/kafka/streams/TopologyTestDriver.java
index 525e01f151c..64eec4c7b27 100644
--- a/streams/test-utils/src/main/java/org/apache/kafka/streams/TopologyTestDriver.java
+++ b/streams/test-utils/src/main/java/org/apache/kafka/streams/TopologyTestDriver.java
@@ -21,6 +21,8 @@ import org.apache.kafka.clients.consumer.ConsumerGroupMetadata;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.MockConsumer;
 import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.consumer.OffsetResetStrategy;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.clients.producer.MockProducer;
 import org.apache.kafka.clients.producer.Producer;


(kafka) 19/42: Resovle conflicts from 11/25 trunk rebase - Update RPCs

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 2dd10b7147ec2c925264f57c93e1341549ca1f0a
Author: Bruno Cadonna <ca...@apache.org>
AuthorDate: Mon Aug 12 17:24:26 2024 +0200

    Resovle conflicts from 11/25 trunk rebase - Update RPCs
    
    Updates RPCs from KIP-1071
---
 checkstyle/suppressions.xml                        |   2 +-
 .../consumer/internals/RequestManagers.java        |  30 +-
 .../internals/StreamsAssignmentInterface.java      |  12 +-
 ...va => StreamsGroupHeartbeatRequestManager.java} | 132 +++----
 .../internals/StreamsInitializeRequestManager.java |  50 +--
 .../StreamsInstallAssignmentRequestManager.java    |  34 --
 .../StreamsPrepareAssignmentRequestManager.java    |  37 --
 .../org/apache/kafka/common/protocol/ApiKeys.java  |   4 +-
 .../org/apache/kafka/common/protocol/Errors.java   |   1 -
 .../kafka/common/requests/AbstractRequest.java     |   8 +-
 .../kafka/common/requests/AbstractResponse.java    |   8 +-
 ...uest.java => StreamsGroupHeartbeatRequest.java} |  36 +-
 ...nse.java => StreamsGroupHeartbeatResponse.java} |  28 +-
 ...est.java => StreamsGroupInitializeRequest.java} |  36 +-
 ...se.java => StreamsGroupInitializeResponse.java} |  16 +-
 .../message/StreamsGroupDescribeRequest.json       |   2 +-
 .../message/StreamsGroupDescribeResponse.json      |  61 ++-
 .../message/StreamsGroupHeartbeatRequest.json      |  89 +++++
 ...nse.json => StreamsGroupHeartbeatResponse.json} |  64 +--
 ...est.json => StreamsGroupInitializeRequest.json} |  16 +-
 ...se.json => StreamsGroupInitializeResponse.json} |   7 +-
 .../common/message/StreamsHeartbeatRequest.json    |  99 -----
 ...> StreamsGroupHeartbeatRequestManagerTest.java} |  72 ++--
 ... StreamsGroupInitializeRequestManagerTest.java} |  30 +-
 .../kafka/common/requests/RequestResponseTest.java |  24 +-
 .../group/GroupCoordinatorAdapter.scala            |  14 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   |  12 +-
 .../group/GroupCoordinatorAdapterTest.scala        |  10 +-
 .../scala/unit/kafka/server/KafkaApisTest.scala    |  48 +--
 .../kafka/coordinator/group/GroupCoordinator.java  |  16 +-
 .../group/GroupCoordinatorRecordHelpers.java       | 401 -------------------
 .../coordinator/group/GroupCoordinatorService.java |  28 +-
 .../coordinator/group/GroupCoordinatorShard.java   |  16 +-
 .../coordinator/group/GroupMetadataManager.java    | 130 +++----
 .../group/metrics/GroupCoordinatorMetrics.java     |   4 +-
 .../streams/CoordinatorStreamsRecordHelpers.java   | 427 +++++++++++++++++++++
 .../group/streams/CurrentAssignmentBuilder.java    |  18 +-
 .../coordinator/group/streams/MemberState.java     |   2 +-
 .../coordinator/group/streams/StreamsGroup.java    |  29 +-
 .../group/streams/StreamsGroupMember.java          | 130 ++-----
 .../coordinator/group/streams/StreamsTopology.java |  19 +-
 .../group/streams/TargetAssignmentBuilder.java     |  10 +-
 .../group/taskassignor/AssignmentMemberSpec.java   |  14 -
 .../StreamsGroupCurrentMemberAssignmentValue.json  |   4 +-
 .../message/StreamsGroupMemberMetadataValue.json   |  33 +-
 .../StreamsGroupTargetAssignmentMemberValue.json   |   2 +-
 .../common/message/StreamsGroupTopologyValue.json  |  12 +-
 .../group/GroupCoordinatorRecordHelpersTest.java   |  82 ----
 .../group/GroupCoordinatorServiceTest.java         |  60 +--
 .../group/GroupCoordinatorShardTest.java           |  24 +-
 .../group/GroupMetadataManagerTest.java            |  20 +-
 .../group/GroupMetadataManagerTestContext.java     |  28 +-
 .../CoordinatorStreamsRecordHelpersTest.java       | 110 ++++++
 .../streams/CurrentAssignmentBuilderTest.java      |  22 +-
 .../group/streams/StreamsGroupMemberTest.java      |  59 +--
 .../group/streams/StreamsGroupTest.java            |   1 -
 .../group/streams/TargetAssignmentBuilderTest.java |  40 +-
 .../group/taskassignor/GroupSpecImplTest.java      |   1 -
 .../group/taskassignor/MockAssignorTest.java       |   5 -
 .../SmokeTestDriverIntegrationTest.java            |   2 +
 .../streams/processor/internals/StreamThread.java  |  17 +-
 61 files changed, 1261 insertions(+), 1487 deletions(-)

diff --git a/checkstyle/suppressions.xml b/checkstyle/suppressions.xml
index 4563e985467..c17c9882f00 100644
--- a/checkstyle/suppressions.xml
+++ b/checkstyle/suppressions.xml
@@ -322,7 +322,7 @@
     <suppress checks="(NPathComplexity|MethodLength)"
               files="(GroupMetadataManager|ConsumerGroupTest|ShareGroupTest|GroupMetadataManagerTest|GroupMetadataManagerTestContext|GeneralUniformAssignmentBuilder).java"/>
     <suppress checks="ClassFanOutComplexity"
-              files="(GroupMetadataManager|GroupMetadataManagerTest|GroupMetadataManagerTestContext|GroupCoordinatorService|GroupCoordinatorServiceTest).java"/>
+              files="(GroupMetadataManager|GroupMetadataManagerTest|GroupMetadataManagerTestContext|GroupCoordinatorService|GroupCoordinatorServiceTest|GroupCoordinatorShardTest).java"/>
     <suppress checks="ParameterNumber"
               files="(ConsumerGroupMember|GroupMetadataManager|GroupCoordinatorConfig).java"/>
     <suppress checks="ClassDataAbstractionCouplingCheck"
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index f370cf15c67..0f7e7cf1178 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -58,9 +58,8 @@ public class RequestManagers implements Closeable {
     public final TopicMetadataRequestManager topicMetadataRequestManager;
     public final FetchRequestManager fetchRequestManager;
     public final Optional<ShareConsumeRequestManager> shareConsumeRequestManager;
+    public final Optional<StreamsGroupHeartbeatRequestManager> streamsHeartbeatRequestManager;
     public final Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager;
-    public final Optional<StreamsPrepareAssignmentRequestManager> streamsPrepareAssignmentRequestManager;
-    public final Optional<StreamsInstallAssignmentRequestManager> streamsInstallAssignmentRequestManager;
     private final List<Optional<? extends RequestManager>> entries;
     private final IdempotentCloser closer = new IdempotentCloser();
 
@@ -72,10 +71,8 @@ public class RequestManagers implements Closeable {
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
                            Optional<ConsumerMembershipManager> membershipManager) {
-                           Optional<StreamsHeartbeatRequestManager> streamsHeartbeatRequestManager,
-                           Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager,
-                           Optional<StreamsPrepareAssignmentRequestManager> streamsPrepareAssignmentRequestManager,
-                           Optional<StreamsInstallAssignmentRequestManager> streamsInstallAssignmentRequestManager) {
+                           Optional<StreamsGroupHeartbeatRequestManager> streamsHeartbeatRequestManager,
+                           Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager) {
         this.log = logContext.logger(RequestManagers.class);
         this.offsetsRequestManager = requireNonNull(offsetsRequestManager, "OffsetsRequestManager cannot be null");
         this.coordinatorRequestManager = coordinatorRequestManager;
@@ -89,8 +86,6 @@ public class RequestManagers implements Closeable {
         this.shareMembershipManager = Optional.empty();
         this.streamsHeartbeatRequestManager = streamsHeartbeatRequestManager;
         this.streamsInitializeRequestManager = streamsInitializeRequestManager;
-        this.streamsPrepareAssignmentRequestManager = streamsPrepareAssignmentRequestManager;
-        this.streamsInstallAssignmentRequestManager = streamsInstallAssignmentRequestManager;
 
         List<Optional<? extends RequestManager>> list = new ArrayList<>();
         list.add(coordinatorRequestManager);
@@ -102,8 +97,6 @@ public class RequestManagers implements Closeable {
         list.add(Optional.of(fetchRequestManager));
         list.add(streamsHeartbeatRequestManager);
         list.add(streamsInitializeRequestManager);
-        list.add(streamsPrepareAssignmentRequestManager);
-        list.add(streamsInstallAssignmentRequestManager);
         entries = Collections.unmodifiableList(list);
     }
 
@@ -203,10 +196,8 @@ public class RequestManagers implements Closeable {
                 ConsumerMembershipManager membershipManager = null;
                 CoordinatorRequestManager coordinator = null;
                 CommitRequestManager commitRequestManager = null;
-                StreamsHeartbeatRequestManager streamsHeartbeatRequestManager = null;
+                StreamsGroupHeartbeatRequestManager streamsGroupHeartbeatRequestManager = null;
                 StreamsInitializeRequestManager streamsInitializeRequestManager = null;
-                StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager = null;
-                StreamsInstallAssignmentRequestManager streamsInstallAssignmentRequestManager = null;
 
                 if (groupRebalanceConfig != null && groupRebalanceConfig.groupId != null) {
                     Optional<String> serverAssignor = Optional.ofNullable(config.getString(ConsumerConfig.GROUP_REMOTE_ASSIGNOR_CONFIG));
@@ -257,17 +248,12 @@ public class RequestManagers implements Closeable {
                             groupRebalanceConfig.groupId,
                             streamsInstanceMetadata.get(),
                             coordinator);
-                        streamsPrepareAssignmentRequestManager = new StreamsPrepareAssignmentRequestManager(
-                            streamsInstanceMetadata.get());
-                        streamsInstallAssignmentRequestManager = new StreamsInstallAssignmentRequestManager(
-                            streamsInstanceMetadata.get());
-                        streamsHeartbeatRequestManager = new StreamsHeartbeatRequestManager(
+                        streamsGroupHeartbeatRequestManager = new StreamsGroupHeartbeatRequestManager(
                             logContext,
                             time,
                             config,
                             coordinator,
                             streamsInitializeRequestManager,
-                            streamsPrepareAssignmentRequestManager,
                             membershipManager,
                             backgroundEventHandler,
                             metrics,
@@ -308,10 +294,8 @@ public class RequestManagers implements Closeable {
                         Optional.ofNullable(commitRequestManager),
                         Optional.ofNullable(heartbeatRequestManager),
                         Optional.ofNullable(membershipManager),
-                        Optional.ofNullable(streamsHeartbeatRequestManager),
-                        Optional.ofNullable(streamsInitializeRequestManager),
-                        Optional.ofNullable(streamsPrepareAssignmentRequestManager),
-                        Optional.ofNullable(streamsInstallAssignmentRequestManager)
+                        Optional.ofNullable(streamsGroupHeartbeatRequestManager),
+                        Optional.ofNullable(streamsInitializeRequestManager)
                 );
             }
         };
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index 27450041b95..5793ffec2aa 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -39,7 +39,7 @@ public class StreamsAssignmentInterface {
 
     private UUID processID;
 
-    private HostInfo endPoint;
+    private Optional<HostInfo> endpoint;
 
     private String assignor;
 
@@ -57,8 +57,8 @@ public class StreamsAssignmentInterface {
         return processID;
     }
 
-    public HostInfo endPoint() {
-        return endPoint;
+    public Optional<HostInfo> endpoint() {
+        return endpoint;
     }
 
     public String assignor() {
@@ -264,14 +264,14 @@ public class StreamsAssignmentInterface {
     }
 
     public StreamsAssignmentInterface(UUID processID,
-                                      HostInfo endPoint,
+                                      Optional<HostInfo> endpoint,
                                       String assignor,
                                       Map<String, Subtopology> subtopologyMap,
                                       Map<String, Object> assignmentConfiguration,
                                       Map<String, String> clientTags
     ) {
         this.processID = processID;
-        this.endPoint = endPoint;
+        this.endpoint = endpoint;
         this.assignor = assignor;
         this.subtopologyMap = subtopologyMap;
         this.assignmentConfiguration = assignmentConfiguration;
@@ -284,7 +284,7 @@ public class StreamsAssignmentInterface {
     public String toString() {
         return "StreamsAssignmentMetadata{" +
             "processID=" + processID +
-            ", endPoint='" + endPoint + '\'' +
+            ", endpoint='" + endpoint + '\'' +
             ", assignor='" + assignor + '\'' +
             ", subtopologyMap=" + subtopologyMap +
             ", assignmentConfiguration=" + assignmentConfiguration +
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
similarity index 83%
rename from clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
rename to clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 5600d550187..7b3713b4131 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -28,14 +28,14 @@ import org.apache.kafka.common.errors.GroupAuthorizationException;
 import org.apache.kafka.common.errors.RetriableException;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskIds;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskIds;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData.Endpoint;
 import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.common.requests.StreamsHeartbeatRequest;
-import org.apache.kafka.common.requests.StreamsHeartbeatResponse;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
 import org.apache.kafka.common.utils.Timer;
@@ -51,20 +51,18 @@ import java.util.Set;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
-public class StreamsHeartbeatRequestManager implements RequestManager {
+public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final Logger logger;
 
     private final CoordinatorRequestManager coordinatorRequestManager;
 
-    private final StreamsHeartbeatRequestManager.HeartbeatRequestState heartbeatRequestState;
+    private final StreamsGroupHeartbeatRequestManager.HeartbeatRequestState heartbeatRequestState;
 
-    private final StreamsHeartbeatRequestManager.HeartbeatState heartbeatState;
+    private final StreamsGroupHeartbeatRequestManager.HeartbeatState heartbeatState;
 
     private final MembershipManager membershipManager;
 
-    private final StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager;
-
     private final StreamsInitializeRequestManager streamsInitializeRequestManager;
 
     private final BackgroundEventHandler backgroundEventHandler;
@@ -79,13 +77,12 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
 
     private final ConsumerMetadata metadata;
 
-    public StreamsHeartbeatRequestManager(
+    public StreamsGroupHeartbeatRequestManager(
         final LogContext logContext,
         final Time time,
         final ConsumerConfig config,
         final CoordinatorRequestManager coordinatorRequestManager,
         final StreamsInitializeRequestManager streamsInitializeRequestManager,
-        final StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager,
         final MembershipManager membershipManager,
         final BackgroundEventHandler backgroundEventHandler,
         final Metrics metrics,
@@ -96,14 +93,13 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         this.logger = logContext.logger(getClass());
         this.membershipManager = membershipManager;
         this.streamsInitializeRequestManager = streamsInitializeRequestManager;
-        this.streamsPrepareAssignmentRequestManager = streamsPrepareAssignmentRequestManager;
         this.backgroundEventHandler = backgroundEventHandler;
         int maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
         long retryBackoffMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG);
         long retryBackoffMaxMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MAX_MS_CONFIG);
-        this.heartbeatState = new StreamsHeartbeatRequestManager.HeartbeatState(streamsAssignmentInterface, membershipManager,
+        this.heartbeatState = new StreamsGroupHeartbeatRequestManager.HeartbeatState(streamsAssignmentInterface, membershipManager,
             maxPollIntervalMs);
-        this.heartbeatRequestState = new StreamsHeartbeatRequestManager.HeartbeatRequestState(logContext, time, 0, retryBackoffMs,
+        this.heartbeatRequestState = new StreamsGroupHeartbeatRequestManager.HeartbeatRequestState(logContext, time, 0, retryBackoffMs,
             retryBackoffMaxMs, maxPollIntervalMs);
         this.pollTimer = time.timer(maxPollIntervalMs);
         this.metricsManager = new HeartbeatMetricsManager(metrics);
@@ -169,7 +165,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
 
     private NetworkClientDelegate.UnsentRequest makeHeartbeatRequest(final boolean ignoreResponse) {
         NetworkClientDelegate.UnsentRequest request = new NetworkClientDelegate.UnsentRequest(
-            new StreamsHeartbeatRequest.Builder(this.heartbeatState.buildRequestData()),
+            new StreamsGroupHeartbeatRequest.Builder(this.heartbeatState.buildRequestData()),
             coordinatorRequestManager.coordinator());
         if (ignoreResponse) {
             return logResponse(request);
@@ -178,7 +174,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
                 long completionTimeMs = request.handler().completionTimeMs();
                 if (response != null) {
                     metricsManager.recordRequestLatency(response.requestLatencyMs());
-                    onResponse((StreamsHeartbeatResponse) response.responseBody(), completionTimeMs);
+                    onResponse((StreamsGroupHeartbeatResponse) response.responseBody(), completionTimeMs);
                 } else {
                     onFailure(exception, completionTimeMs);
                 }
@@ -191,7 +187,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             if (response != null) {
                 metricsManager.recordRequestLatency(response.requestLatencyMs());
                 Errors error =
-                    Errors.forCode(((StreamsHeartbeatResponse) response.responseBody()).data().errorCode());
+                    Errors.forCode(((StreamsGroupHeartbeatResponse) response.responseBody()).data().errorCode());
                 if (error == Errors.NONE) {
                     logger.debug("StreamsHeartbeat responded successfully: {}", response);
                 } else {
@@ -218,7 +214,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         }
     }
 
-    private void onResponse(final StreamsHeartbeatResponse response, long currentTimeMs) {
+    private void onResponse(final StreamsGroupHeartbeatResponse response, long currentTimeMs) {
         if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
             onSuccessResponse(response, currentTimeMs);
         } else {
@@ -226,8 +222,8 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         }
     }
 
-    private void onSuccessResponse(final StreamsHeartbeatResponse response, final long currentTimeMs) {
-        final StreamsHeartbeatResponseData data = response.data();
+    private void onSuccessResponse(final StreamsGroupHeartbeatResponse response, final long currentTimeMs) {
+        final StreamsGroupHeartbeatResponseData data = response.data();
 
         heartbeatRequestState.updateHeartbeatIntervalMs(data.heartbeatIntervalMs());
         heartbeatRequestState.onSuccessfulAttempt(currentTimeMs);
@@ -236,10 +232,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         if (data.shouldInitializeTopology()) {
             streamsInitializeRequestManager.initialize();
         }
-        if (data.shouldComputeAssignment()) {
-            streamsPrepareAssignmentRequestManager.prepareAssignment();
-        }
-        if (data.partitionsByHost() != null) {
+        if (data.partitionsByUserEndpoint() != null) {
             streamsInterface.partitionsByHost.set(convertHostInfoMap(data));
         }
 
@@ -251,19 +244,13 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         cgData.setThrottleTimeMs(data.throttleTimeMs());
         cgData.setHeartbeatIntervalMs(data.heartbeatIntervalMs());
 
-        Errors assignmentError = response.assignmentError();
-        String assignmentErrorMessage = response.data().errorMessage();
-        if (assignmentError != Errors.NONE) {
-            logger.warn("Assignment incomplete. {}. {}", assignmentError.message(), assignmentErrorMessage);
-            switch (assignmentError) {
-                case STREAMS_SHUTDOWN_APPLICATION:
-                    streamsInterface.requestShutdown();
-                    break;
-                case STREAMS_INCONSISTENT_TOPOLOGY:
-                case STREAMS_MISSING_SOURCE_TOPICS:
-                case STREAMS_GROUP_UNINITIALIZED:
-                    break;
-            }
+        List<StreamsGroupHeartbeatResponseData.Status> statuses = data.status();
+
+        if (statuses != null && !statuses.isEmpty()) {
+            String statusDetails = statuses.stream()
+                .map(status -> "(" + status.statusCode() + ") " + status.statusDetail())
+                .collect(Collectors.joining(", "));
+            logger.warn("Membership is in the following statuses: {}.", statusDetails);
         }
 
         if (data.activeTasks() != null && data.standbyTasks() != null && data.warmupTasks() != null) {
@@ -280,7 +267,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         membershipManager.onHeartbeatSuccess(cgData);
     }
 
-    private void setTargetAssignmentForConsumerGroup(final StreamsHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
+    private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
         Map<String, TopicPartitions> tps = new HashMap<>();
         data.activeTasks().forEach(taskId -> Stream.concat(
                 streamsInterface.subtopologyMap().get(taskId.subtopology()).sourceTopics.stream(),
@@ -307,7 +294,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         cgData.setAssignment(cgAssignment);
     }
 
-    private void setTargetAssignment(final StreamsHeartbeatResponseData data) {
+    private void setTargetAssignment(final StreamsGroupHeartbeatResponseData data) {
         Assignment targetAssignment = new Assignment();
         updateTaskIdCollection(data.activeTasks(), targetAssignment.activeTasks);
         updateTaskIdCollection(data.standbyTasks(), targetAssignment.standbyTasks);
@@ -315,21 +302,21 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         streamsInterface.targetAssignment.set(targetAssignment);
     }
 
-    private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(
-        final StreamsHeartbeatResponseData data) {
+    private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(final StreamsGroupHeartbeatResponseData data) {
         Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> partitionsByHost = new HashMap<>();
-        data.partitionsByHost().forEach(hostInfo -> {
-            List<TopicPartition> topicPartitions = hostInfo.partitions().stream()
+        data.partitionsByUserEndpoint().forEach(endpoint -> {
+            List<TopicPartition> topicPartitions = endpoint.partitions().stream()
                 .flatMap(partition ->
                     partition.partitions().stream().map(partitionId -> new TopicPartition(partition.topic(), partitionId)))
                 .collect(Collectors.toList());
-            partitionsByHost.put(new StreamsAssignmentInterface.HostInfo(hostInfo.host(), hostInfo.port()), topicPartitions);
+            Endpoint userEndpoint = endpoint.userEndpoint();
+            partitionsByHost.put(new StreamsAssignmentInterface.HostInfo(userEndpoint.host(), userEndpoint.port()), topicPartitions);
         });
         return partitionsByHost;
     }
 
     private void updateTaskIdCollection(
-        final List<StreamsHeartbeatResponseData.TaskIds> source,
+        final List<StreamsGroupHeartbeatResponseData.TaskIds> source,
         final Set<StreamsAssignmentInterface.TaskId> target
     ) {
         target.clear();
@@ -340,7 +327,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
         });
     }
 
-    private void onErrorResponse(final StreamsHeartbeatResponse response,
+    private void onErrorResponse(final StreamsGroupHeartbeatResponse response,
                                  final long currentTimeMs) {
         Errors error = Errors.forCode(response.data().errorCode());
         String errorMessage = response.data().errorMessage();
@@ -428,7 +415,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
     }
 
     private void logInfo(final String message,
-                         final StreamsHeartbeatResponse response,
+                         final StreamsGroupHeartbeatResponse response,
                          final long currentTimeMs) {
         logger.info("{} in {}ms: {}",
             message,
@@ -464,7 +451,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             final long retryBackoffMs,
             final long retryBackoffMaxMs,
             final double jitter) {
-            super(logContext, StreamsHeartbeatRequestManager.HeartbeatRequestState.class.getName(), retryBackoffMs, 2, retryBackoffMaxMs,
+            super(logContext, StreamsGroupHeartbeatRequestManager.HeartbeatRequestState.class.getName(), retryBackoffMs, 2, retryBackoffMaxMs,
                 jitter);
             this.heartbeatIntervalMs = heartbeatIntervalMs;
             this.heartbeatTimer = time.timer(heartbeatIntervalMs);
@@ -518,7 +505,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
 
         private final MembershipManager membershipManager;
         private final int rebalanceTimeoutMs;
-        private final StreamsHeartbeatRequestManager.HeartbeatState.SentFields sentFields;
+        private final StreamsGroupHeartbeatRequestManager.HeartbeatState.SentFields sentFields;
 
         /*
          * StreamsGroupMetadata holds the metadata for the streams group
@@ -531,7 +518,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             final int rebalanceTimeoutMs) {
             this.membershipManager = membershipManager;
             this.rebalanceTimeoutMs = rebalanceTimeoutMs;
-            this.sentFields = new StreamsHeartbeatRequestManager.HeartbeatState.SentFields();
+            this.sentFields = new StreamsGroupHeartbeatRequestManager.HeartbeatState.SentFields();
             this.streamsInterface = streamsInterface;
         }
 
@@ -539,8 +526,8 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             sentFields.reset();
         }
 
-        public StreamsHeartbeatRequestData buildRequestData() {
-            StreamsHeartbeatRequestData data = new StreamsHeartbeatRequestData();
+        public StreamsGroupHeartbeatRequestData buildRequestData() {
+            StreamsGroupHeartbeatRequestData data = new StreamsGroupHeartbeatRequestData();
 
             // GroupId - always sent
             data.setGroupId(membershipManager.groupId());
@@ -565,28 +552,21 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             // Immutable -- only sent when joining
             if (joining) {
                 data.setProcessId(streamsInterface.processID().toString());
-                HostInfo hostInfo = new HostInfo();
-                hostInfo.setHost(streamsInterface.endPoint().host);
-                hostInfo.setPort(streamsInterface.endPoint().port);
-                data.setHostInfo(hostInfo);
-                data.setAssignor(streamsInterface.assignor());
-                data.setClientTags(streamsInterface.clientTags().entrySet().stream().map(entry -> {
-                    StreamsHeartbeatRequestData.KeyValue tag = new StreamsHeartbeatRequestData.KeyValue();
-                    tag.setKey(entry.getKey());
-                    tag.setValue(entry.getValue());
-                    return tag;
-                }).collect(Collectors.toList()));
-                data.setAssignmentConfigs(streamsInterface.assignmentConfiguration().entrySet().stream().filter(
-                    entry -> entry.getValue() != null
-                ).map(entry -> {
-                    StreamsHeartbeatRequestData.KeyValue config = new StreamsHeartbeatRequestData.KeyValue();
-                    config.setKey(entry.getKey());
-                    config.setValue(entry.getValue().toString());
-                    return config;
-                }).collect(Collectors.toList()));
-            } else {
-                // FIXME: This seems to be a bug in the RPC serialization code. The default should be null, but it's empty.
-                data.setAssignor(null);
+//                data.setActiveTasks(Collections.emptyList());
+//                data.setStandbyTasks(Collections.emptyList());
+//                data.setWarmupTasks(Collections.emptyList());
+                streamsInterface.endpoint().ifPresent(streamsEndpoint -> {
+                    data.setUserEndpoint(new StreamsGroupHeartbeatRequestData.Endpoint()
+                        .setHost(streamsEndpoint.host)
+                        .setPort(streamsEndpoint.port)
+                    );
+                });
+                data.setClientTags(streamsInterface.clientTags().entrySet().stream()
+                    .map(entry -> new StreamsGroupHeartbeatRequestData.KeyValue()
+                        .setKey(entry.getKey())
+                        .setValue(entry.getValue())
+                    )
+                    .collect(Collectors.toList()));
             }
 
             if (streamsInterface.shutdownRequested()) {
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
index 07b6dee16bd..c0d2d9f9124 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -18,10 +18,10 @@ package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.common.requests.StreamsInitializeRequest;
-import org.apache.kafka.common.requests.StreamsInitializeResponse;
+import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
+import org.apache.kafka.common.requests.StreamsGroupInitializeResponse;
 import org.apache.kafka.common.utils.LogContext;
 import org.slf4j.Logger;
 
@@ -66,12 +66,12 @@ public class StreamsInitializeRequestManager implements RequestManager {
     }
 
     private NetworkClientDelegate.UnsentRequest makeRequest() {
-        final StreamsInitializeRequestData streamsInitializeRequestData = new StreamsInitializeRequestData();
-        streamsInitializeRequestData.setGroupId(groupId);
-        final List<StreamsInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
-        streamsInitializeRequestData.setTopology(topology);
-        final StreamsInitializeRequest.Builder streamsInitializeRequestBuilder = new StreamsInitializeRequest.Builder(
-            streamsInitializeRequestData
+        final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = new StreamsGroupInitializeRequestData();
+        streamsGroupInitializeRequestData.setGroupId(groupId);
+        final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
+        streamsGroupInitializeRequestData.setTopology(topology);
+        final StreamsGroupInitializeRequest.Builder streamsInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
+            streamsGroupInitializeRequestData
         );
         return new NetworkClientDelegate.UnsentRequest(
             streamsInitializeRequestBuilder,
@@ -79,30 +79,30 @@ public class StreamsInitializeRequestManager implements RequestManager {
         );
     }
 
-    private List<StreamsInitializeRequestData.Subtopology> getTopologyFromStreams() {
+    private List<StreamsGroupInitializeRequestData.Subtopology> getTopologyFromStreams() {
         final Map<String, StreamsAssignmentInterface.Subtopology> subTopologyMap = streamsAssignmentInterface.subtopologyMap();
-        final List<StreamsInitializeRequestData.Subtopology> topology = new ArrayList<>(subTopologyMap.size());
+        final List<StreamsGroupInitializeRequestData.Subtopology> topology = new ArrayList<>(subTopologyMap.size());
         for (final Map.Entry<String, StreamsAssignmentInterface.Subtopology> subtopology : subTopologyMap.entrySet()) {
             topology.add(getSubtopologyFromStreams(subtopology.getKey(), subtopology.getValue()));
         }
         return topology;
     }
 
-    private static StreamsInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
-                                                                                      final StreamsAssignmentInterface.Subtopology subtopology) {
-        final StreamsInitializeRequestData.Subtopology subtopologyData = new StreamsInitializeRequestData.Subtopology();
+    private static StreamsGroupInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
+                                                                                           final StreamsAssignmentInterface.Subtopology subtopology) {
+        final StreamsGroupInitializeRequestData.Subtopology subtopologyData = new StreamsGroupInitializeRequestData.Subtopology();
         subtopologyData.setSubtopology(subtopologyName);
         subtopologyData.setSourceTopics(new ArrayList<>(subtopology.sourceTopics));
-        subtopologyData.setSinkTopics(new ArrayList<>(subtopology.sinkTopics));
+        subtopologyData.setRepartitionSinkTopics(new ArrayList<>(subtopology.sinkTopics));
         subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
         subtopologyData.setStateChangelogTopics(getChangelogTopicsInfoFromStreams(subtopology));
         return subtopologyData;
     }
 
-    private static List<StreamsInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
-        final List<StreamsInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
+    private static List<StreamsGroupInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
+        final List<StreamsGroupInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
-            final StreamsInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsInitializeRequestData.TopicInfo();
+            final StreamsGroupInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
             repartitionTopicInfo.setName(repartitionTopic.getKey());
             repartitionTopic.getValue().numPartitions.ifPresent(repartitionTopicInfo::setPartitions);
             repartitionTopicsInfo.add(repartitionTopicInfo);
@@ -110,10 +110,10 @@ public class StreamsInitializeRequestManager implements RequestManager {
         return repartitionTopicsInfo;
     }
 
-    private static List<StreamsInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
-        final List<StreamsInitializeRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
+    private static List<StreamsGroupInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
+        final List<StreamsGroupInitializeRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
-            final StreamsInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsInitializeRequestData.TopicInfo();
+            final StreamsGroupInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
             changelogTopicInfo.setName(changelogTopic.getKey());
             changelogTopicsInfo.add(changelogTopicInfo);
         }
@@ -125,11 +125,11 @@ public class StreamsInitializeRequestManager implements RequestManager {
             // todo: handle error
             logger.error("Error during Streams initialization: ", exception);
         } else {
-            onResponse((StreamsInitializeResponse) response.responseBody());
+            onResponse((StreamsGroupInitializeResponse) response.responseBody());
         }
     }
 
-    private void onResponse(final StreamsInitializeResponse response) {
+    private void onResponse(final StreamsGroupInitializeResponse response) {
         if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
             onSuccessResponse(response);
         } else {
@@ -137,12 +137,12 @@ public class StreamsInitializeRequestManager implements RequestManager {
         }
     }
 
-    private void onErrorResponse(final StreamsInitializeResponse response) {
+    private void onErrorResponse(final StreamsGroupInitializeResponse response) {
         // todo: handle error
         logger.error("Error during Streams initialization: {}", response);
     }
 
-    private void onSuccessResponse(final StreamsInitializeResponse response) {
+    private void onSuccessResponse(final StreamsGroupInitializeResponse response) {
         // todo: handle success
         logger.info("Streams initialization successful {}", response);
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
deleted file mode 100644
index b47572637bb..00000000000
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 org.apache.kafka.clients.consumer.internals;
-
-import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
-
-public class StreamsInstallAssignmentRequestManager implements RequestManager {
-
-    private final StreamsAssignmentInterface streamsAssignmentInterface;
-
-    StreamsInstallAssignmentRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
-        this.streamsAssignmentInterface = streamsAssignmentInterface;
-    }
-
-    @Override
-    public PollResult poll(final long currentTimeMs) {
-        return PollResult.EMPTY;
-    }
-
-}
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
deleted file mode 100644
index fb4f59cdf96..00000000000
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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 org.apache.kafka.clients.consumer.internals;
-
-import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
-
-public class StreamsPrepareAssignmentRequestManager implements RequestManager {
-
-    private final StreamsAssignmentInterface streamsAssignmentInterface;
-
-    StreamsPrepareAssignmentRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
-        this.streamsAssignmentInterface = streamsAssignmentInterface;
-    }
-
-    @Override
-    public PollResult poll(final long currentTimeMs) {
-        return PollResult.EMPTY;
-    }
-
-    public void prepareAssignment() {
-        // TODO: Create a `StreamsPrepareAssignmentRequest`
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index 35548b52ebf..a53b082c997 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -131,8 +131,8 @@ public enum ApiKeys {
     WRITE_SHARE_GROUP_STATE(ApiMessageType.WRITE_SHARE_GROUP_STATE, true),
     DELETE_SHARE_GROUP_STATE(ApiMessageType.DELETE_SHARE_GROUP_STATE, true),
     READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
-    STREAMS_HEARTBEAT(ApiMessageType.STREAMS_HEARTBEAT),
-    STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE),
+    STREAMS_GROUP_HEARTBEAT(ApiMessageType.STREAMS_GROUP_HEARTBEAT),
+    STREAMS_GROUP_INITIALIZE(ApiMessageType.STREAMS_GROUP_INITIALIZE),
     STREAMS_GROUP_DESCRIBE(ApiMessageType.STREAMS_GROUP_DESCRIBE);
     
 
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index f9f063051b7..00ed250ec73 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -21,7 +21,6 @@ import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.BrokerIdNotRegisteredException;
 import org.apache.kafka.common.errors.BrokerNotAvailableException;
 import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
-import org.apache.kafka.common.errors.StreamsInvalidAssignmentException;
 import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
 import org.apache.kafka.common.errors.StreamsGroupUninitializedException;
 import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
index e0cb5e97b5d..3d99419987d 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
@@ -350,10 +350,10 @@ public abstract class AbstractRequest implements AbstractRequestResponse {
                 return DeleteShareGroupStateRequest.parse(buffer, apiVersion);
             case READ_SHARE_GROUP_STATE_SUMMARY:
                 return ReadShareGroupStateSummaryRequest.parse(buffer, apiVersion);
-            case STREAMS_HEARTBEAT:
-                return StreamsHeartbeatRequest.parse(buffer, apiVersion);
-            case STREAMS_INITIALIZE:
-                return StreamsInitializeRequest.parse(buffer, apiVersion);
+            case STREAMS_GROUP_HEARTBEAT:
+                return StreamsGroupHeartbeatRequest.parse(buffer, apiVersion);
+            case STREAMS_GROUP_INITIALIZE:
+                return StreamsGroupInitializeRequest.parse(buffer, apiVersion);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseRequest`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
index cc3d3384a27..9e25cfd99da 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
@@ -287,10 +287,10 @@ public abstract class AbstractResponse implements AbstractRequestResponse {
                 return DeleteShareGroupStateResponse.parse(responseBuffer, version);
             case READ_SHARE_GROUP_STATE_SUMMARY:
                 return ReadShareGroupStateSummaryResponse.parse(responseBuffer, version);
-            case STREAMS_HEARTBEAT:
-                return StreamsHeartbeatResponse.parse(responseBuffer, version);
-            case STREAMS_INITIALIZE:
-                return StreamsInitializeResponse.parse(responseBuffer, version);
+            case STREAMS_GROUP_HEARTBEAT:
+                return StreamsGroupHeartbeatResponse.parse(responseBuffer, version);
+            case STREAMS_GROUP_INITIALIZE:
+                return StreamsGroupInitializeResponse.parse(responseBuffer, version);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseResponse`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatRequest.java
similarity index 62%
rename from clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java
rename to clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatRequest.java
index 0e552934c4f..51ef4069089 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatRequest.java
@@ -16,15 +16,15 @@
  */
 package org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
 import java.nio.ByteBuffer;
 
-public class StreamsHeartbeatRequest extends AbstractRequest {
+public class StreamsGroupHeartbeatRequest extends AbstractRequest {
 
     /**
      * A member epoch of <code>-1</code> means that the member wants to leave the group.
@@ -37,21 +37,21 @@ public class StreamsHeartbeatRequest extends AbstractRequest {
      */
     public static final int JOIN_GROUP_MEMBER_EPOCH = 0;
 
-    public static class Builder extends AbstractRequest.Builder<StreamsHeartbeatRequest> {
-        private final StreamsHeartbeatRequestData data;
+    public static class Builder extends AbstractRequest.Builder<StreamsGroupHeartbeatRequest> {
+        private final StreamsGroupHeartbeatRequestData data;
 
-        public Builder(StreamsHeartbeatRequestData data) {
+        public Builder(StreamsGroupHeartbeatRequestData data) {
             this(data, false);
         }
 
-        public Builder(StreamsHeartbeatRequestData data, boolean enableUnstableLastVersion) {
-            super(ApiKeys.STREAMS_HEARTBEAT, enableUnstableLastVersion);
+        public Builder(StreamsGroupHeartbeatRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_GROUP_HEARTBEAT, enableUnstableLastVersion);
             this.data = data;
         }
 
         @Override
-        public StreamsHeartbeatRequest build(short version) {
-            return new StreamsHeartbeatRequest(data, version);
+        public StreamsGroupHeartbeatRequest build(short version) {
+            return new StreamsGroupHeartbeatRequest(data, version);
         }
 
         @Override
@@ -60,29 +60,29 @@ public class StreamsHeartbeatRequest extends AbstractRequest {
         }
     }
 
-    private final StreamsHeartbeatRequestData data;
+    private final StreamsGroupHeartbeatRequestData data;
 
-    public StreamsHeartbeatRequest(StreamsHeartbeatRequestData data, short version) {
-        super(ApiKeys.STREAMS_HEARTBEAT, version);
+    public StreamsGroupHeartbeatRequest(StreamsGroupHeartbeatRequestData data, short version) {
+        super(ApiKeys.STREAMS_GROUP_HEARTBEAT, version);
         this.data = data;
     }
 
     @Override
     public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
-        return new StreamsHeartbeatResponse(
-            new StreamsHeartbeatResponseData()
+        return new StreamsGroupHeartbeatResponse(
+            new StreamsGroupHeartbeatResponseData()
                 .setThrottleTimeMs(throttleTimeMs)
                 .setErrorCode(Errors.forException(e).code())
         );
     }
 
     @Override
-    public StreamsHeartbeatRequestData data() {
+    public StreamsGroupHeartbeatRequestData data() {
         return data;
     }
 
-    public static StreamsHeartbeatRequest parse(ByteBuffer buffer, short version) {
-        return new StreamsHeartbeatRequest(new StreamsHeartbeatRequestData(
+    public static StreamsGroupHeartbeatRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupHeartbeatRequest(new StreamsGroupHeartbeatRequestData(
             new ByteBufferAccessor(buffer), version), version);
     }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
similarity index 71%
rename from clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
rename to clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
index 835fec5c8ff..2785bef35f7 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupHeartbeatResponse.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
@@ -43,16 +43,16 @@ import java.util.Map;
  * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
  * - {@link Errors#STREAMS_GROUP_UNINITIALIZED}
  */
-public class StreamsHeartbeatResponse extends AbstractResponse {
-    private final StreamsHeartbeatResponseData data;
+public class StreamsGroupHeartbeatResponse extends AbstractResponse {
+    private final StreamsGroupHeartbeatResponseData data;
 
-    public StreamsHeartbeatResponse(StreamsHeartbeatResponseData data) {
-        super(ApiKeys.STREAMS_HEARTBEAT);
+    public StreamsGroupHeartbeatResponse(StreamsGroupHeartbeatResponseData data) {
+        super(ApiKeys.STREAMS_GROUP_HEARTBEAT);
         this.data = data;
     }
 
     @Override
-    public StreamsHeartbeatResponseData data() {
+    public StreamsGroupHeartbeatResponseData data() {
         return data;
     }
 
@@ -71,20 +71,8 @@ public class StreamsHeartbeatResponse extends AbstractResponse {
         data.setThrottleTimeMs(throttleTimeMs);
     }
 
-    /**
-     * Possible error codes.
-     *
-     * - {@link Errors#STREAMS_SHUTDOWN_APPLICATION}
-     * - {@link Errors#STREAMS_INCONSISTENT_TOPOLOGY}
-     * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
-     * - {@link Errors#STREAMS_GROUP_UNINITIALIZED}
-     */
-    public Errors assignmentError() {
-        return Errors.forCode(data.assignmentErrorCode());
-    }
-
-    public static StreamsHeartbeatResponse parse(ByteBuffer buffer, short version) {
-        return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData(
+    public static StreamsGroupHeartbeatResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupHeartbeatResponse(new StreamsGroupHeartbeatResponseData(
             new ByteBufferAccessor(buffer), version));
     }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java
similarity index 57%
rename from clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
rename to clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java
index 5f150053798..bebcf103cf9 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeRequest.java
@@ -16,31 +16,31 @@
  */
 package org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
 import java.nio.ByteBuffer;
 
-public class StreamsInitializeRequest extends AbstractRequest {
+public class StreamsGroupInitializeRequest extends AbstractRequest {
 
-    public static class Builder extends AbstractRequest.Builder<StreamsInitializeRequest> {
-        private final StreamsInitializeRequestData data;
+    public static class Builder extends AbstractRequest.Builder<StreamsGroupInitializeRequest> {
+        private final StreamsGroupInitializeRequestData data;
 
-        public Builder(StreamsInitializeRequestData data) {
+        public Builder(StreamsGroupInitializeRequestData data) {
             this(data, false);
         }
 
-        public Builder(StreamsInitializeRequestData data, boolean enableUnstableLastVersion) {
-            super(ApiKeys.STREAMS_INITIALIZE, enableUnstableLastVersion);
+        public Builder(StreamsGroupInitializeRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_GROUP_INITIALIZE, enableUnstableLastVersion);
             this.data = data;
         }
 
         @Override
-        public StreamsInitializeRequest build(short version) {
-            return new StreamsInitializeRequest(data, version);
+        public StreamsGroupInitializeRequest build(short version) {
+            return new StreamsGroupInitializeRequest(data, version);
         }
 
         @Override
@@ -49,29 +49,29 @@ public class StreamsInitializeRequest extends AbstractRequest {
         }
     }
 
-    private final StreamsInitializeRequestData data;
+    private final StreamsGroupInitializeRequestData data;
 
-    public StreamsInitializeRequest(StreamsInitializeRequestData data, short version) {
-        super(ApiKeys.STREAMS_INITIALIZE, version);
+    public StreamsGroupInitializeRequest(StreamsGroupInitializeRequestData data, short version) {
+        super(ApiKeys.STREAMS_GROUP_INITIALIZE, version);
         this.data = data;
     }
 
     @Override
     public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
-        return new StreamsInitializeResponse(
-            new StreamsInitializeResponseData()
+        return new StreamsGroupInitializeResponse(
+            new StreamsGroupInitializeResponseData()
                 .setThrottleTimeMs(throttleTimeMs)
                 .setErrorCode(Errors.forException(e).code())
         );
     }
 
     @Override
-    public StreamsInitializeRequestData data() {
+    public StreamsGroupInitializeRequestData data() {
         return data;
     }
 
-    public static StreamsInitializeRequest parse(ByteBuffer buffer, short version) {
-        return new StreamsInitializeRequest(new StreamsInitializeRequestData(
+    public static StreamsGroupInitializeRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupInitializeRequest(new StreamsGroupInitializeRequestData(
             new ByteBufferAccessor(buffer), version), version);
     }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java
similarity index 76%
rename from clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
rename to clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java
index 050b28b02af..cb224b3c6d7 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupInitializeResponse.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
@@ -35,17 +35,17 @@ import java.util.Map;
  * - {@link Errors#INVALID_REQUEST}
  * - {@link Errors#STREAMS_INVALID_TOPOLOGY}
  */
-public class StreamsInitializeResponse extends AbstractResponse {
+public class StreamsGroupInitializeResponse extends AbstractResponse {
 
-    private final StreamsInitializeResponseData data;
+    private final StreamsGroupInitializeResponseData data;
 
-    public StreamsInitializeResponse(StreamsInitializeResponseData data) {
-        super(ApiKeys.STREAMS_INITIALIZE);
+    public StreamsGroupInitializeResponse(StreamsGroupInitializeResponseData data) {
+        super(ApiKeys.STREAMS_GROUP_INITIALIZE);
         this.data = data;
     }
 
     @Override
-    public StreamsInitializeResponseData data() {
+    public StreamsGroupInitializeResponseData data() {
         return data;
     }
 
@@ -64,8 +64,8 @@ public class StreamsInitializeResponse extends AbstractResponse {
         data.setThrottleTimeMs(throttleTimeMs);
     }
 
-    public static StreamsInitializeResponse parse(ByteBuffer buffer, short version) {
-        return new StreamsInitializeResponse(new StreamsInitializeResponseData(
+    public static StreamsGroupInitializeResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupInitializeResponse(new StreamsGroupInitializeResponseData(
             new ByteBufferAccessor(buffer), version));
     }
 }
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
index 2c828455a67..17b4abac9d2 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
@@ -16,7 +16,7 @@
 {
   "apiKey": 90,
   "type": "request",
-  "listeners": ["zkBroker", "broker"],
+  "listeners": ["broker"],
   "name": "StreamsGroupDescribeRequest",
   "validVersions": "0",
   "flexibleVersions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index ae4b3f8ea35..1093100992f 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -45,13 +45,11 @@
           "about": "The group epoch." },
         { "name": "AssignmentEpoch", "type": "int32", "versions": "0+",
           "about": "The assignment epoch." },
-        { "name": "AssignorName", "type": "string", "versions": "0+",
-          "about": "The selected assignor." },
         { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
           "about": "The sub-topologies of the streams application.",
           "fields": [
             { "name": "Subtopology", "type": "string", "versions": "0+",
-              "about": "String to uniquely identify the subtopology." },
+              "about": "String to uniquely identify the sub-topology." },
             { "name": "SourceTopics", "type": "[]string", "versions": "0+",
               "about": "The topics the topology reads from." },
             { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
@@ -59,7 +57,7 @@
             { "name": "SinkTopics", "type": "[]string", "versions": "0+",
               "about": "The topics the topology writes to." },
             { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-              "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
+              "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
             { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
               "about": "The set of source topics that are internally created repartition topics. Created automatically." }
           ]
@@ -81,30 +79,17 @@
             { "name": "ClientHost", "type": "string", "versions": "0+",
               "about": "The client host." },
 
-            { "name": "TopologyHash", "type": "bytes", "versions": "0+",
-              "about": "The hash of the topology." },
+            { "name": "TopologyId", "type": "string", "versions": "0+",
+              "about": "The ID of the topology. Must be non-empty." },
 
             { "name": "ProcessId", "type": "uuid", "versions": "0+",
               "about": "Identity of the streams instance that may have multiple clients. " },
             { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
               "about": "Used for rack-aware assignment algorithm." },
-            { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
-              "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
-            { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
-              "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
-              "fields": [
-                { "name": "Subtopology", "type": "string", "versions": "0+",
-                  "about": "A unique identifier of the subtopology." },
-                { "name": "Partition", "type": "int32", "versions": "0+",
-                  "about": "The partition of the input topics." },
-                { "name": "Offset", "type": "int64", "versions": "0+",
-                  "about": "The cumulative offset for the task" }
-              ]
-            },
-            { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
-              "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
-            { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
-              "about": "Generic array of assignment configuration strings."},
+            { "name": "TaskOffsets", "type": "[]TaskOffset", "versions": "0+",
+              "about": "Cumulative offsets for tasks." },
+            { "name": "TaskEndOffsets", "type": "[]TaskOffset", "versions": "0+",
+              "about": "Cumulative end offsets for tasks." },
 
             { "name": "Assignment", "type": "Assignment", "versions": "0+",
               "about": "The current assignment." },
@@ -117,19 +102,35 @@
     }
   ],
   "commonStructs": [
+    { "name": "TaskOffset", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "The sub-topology identifier." },
+      { "name": "Partition", "type": "int32", "versions": "0+",
+        "about": "The partition." },
+      { "name": "Offset", "type": "int64", "versions": "0+",
+        "about": "The offset." }
+    ]},
+    { "name": "TopicPartitions", "versions": "0+", "fields": [
+      { "name": "TopicId", "type": "uuid", "versions": "0+",
+        "about": "The topic ID." },
+      { "name": "TopicName", "type": "string", "versions": "0+", "entityType": "topicName",
+        "about": "The topic name." },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "The partitions." }
+    ]},
     { "name": "Assignment", "versions": "0+", "fields": [
       { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Active tasks for this client." },
       { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Standby tasks for this client." },
       { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Warming up tasks for this client. " }
+        "about": "Warm-up tasks for this client. " }
     ]},
     { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "subtopology ID" },
+        "about": "The sub-topology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "partitions" }
+        "about": "The partitions of the input topics processed by this member." }
     ]},
     { "name": "KeyValue", "versions": "0+", "fields": [
       { "name": "Key", "type": "string", "versions": "0+",
@@ -137,18 +138,12 @@
       { "name": "Value", "type": "string", "versions": "0+",
         "about": "value of the config" }
     ]},
-    { "name": "TopicConfig", "versions": "0+", "fields": [
-      { "name": "key", "type": "string", "versions": "0+",
-        "about": "The key of the topic-level configuration." },
-      { "name": "value", "type": "string", "versions": "0+",
-        "about": "The value of the topic-level configuration," }
-    ]},
     { "name": "TopicInfo", "versions": "0+", "fields": [
       { "name": "Name", "type": "string", "versions": "0+",
         "about": "The name of the topic." },
       { "name": "Partitions", "type": "int32", "versions": "0+",
         "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
-      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      { "name": "TopicConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
         "about": "Topic-level configurations as key-value pairs."
       }
     ]}
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
new file mode 100644
index 00000000000..ac765b2269c
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
@@ -0,0 +1,89 @@
+// 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.
+
+{
+  "apiKey": 89,
+  "type": "request",
+  "listeners": ["broker"],
+  "name": "StreamsGroupHeartbeatRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+      "about": "The group identifier." },
+    { "name": "MemberId", "type": "string", "versions": "0+",
+      "about": "The member id generated by the coordinator. The member id must be kept during the entire lifetime of the member." },
+    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+      "about": "The current member epoch; 0 to join the group; -1 to leave the group; -2 to indicate that the static member will rejoin." },
+    { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "null if not provided or if it didn't change since the last heartbeat; the instance Id otherwise." },
+    { "name": "RackId", "type": "string", "versions": "0+",  "nullableVersions": "0+", "default": "null",
+      "about": "null if not provided or if it didn't change since the last heartbeat; the rack ID of consumer otherwise." },
+    { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
+      "about": "-1 if it didn't change since the last heartbeat; the maximum time in milliseconds that the coordinator will wait on the member to revoke its partitions otherwise." },
+
+    { "name": "TopologyId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
+      "about": "The ID of the topology. Only sent when memberEpoch = 0, must be non-empty. Null otherwise. Used to check if topology corresponds to server-topology. " },
+
+    { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Currently owned active tasks for this client. Null if unchanged since last heartbeat." },
+    { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Currently owned standby tasks for this client. Null if unchanged since last heartbeat." },
+    { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Currently owned warm-up tasks for this client. Null if unchanged since last heartbeat." },
+
+    { "name": "ProcessId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Identity of the streams instance that may have multiple consumers. Null if unchanged since last heartbeat." },
+    { "name": "UserEndpoint", "type": "Endpoint", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "User-defined endpoint for Interactive Queries. Null if unchanged since last heartbeat." },
+    { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
+
+    { "name": "TaskOffsets", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Cumulative offsets for tasks. Only updated when a warm up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
+    { "name": "TaskEndOffsets", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Cumulative end-offsets for tasks. Only updated when a warm up task has caught up, and according to the task offset interval. Null if unchanged since last heartbeat." },
+    { "name": "ShutdownApplication", "type": "bool", "versions": "0+", "default": false,
+      "about": "Whether all Streams clients in the group should shut down. Can only be defined if memberEpoch = -1" }
+  ],
+  "commonStructs": [
+    { "name": "Endpoint", "versions": "0+", "fields": [
+      { "name": "Host", "type": "string", "versions": "0+",
+        "about": "host of the endpoint" },
+      { "name": "Port", "type": "uint16", "versions": "0+",
+        "about": "port of the endpoint" }
+    ]},
+    { "name": "KeyValue", "versions": "0+", "fields": [
+      { "name": "Key", "type": "string", "versions": "0+",
+        "about": "key of the config" },
+      { "name": "Value", "type": "string", "versions": "0+",
+        "about": "value of the config" }
+    ]},
+    { "name": "TaskOffset", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "The sub-topology identifier." },
+      { "name": "Partition", "type": "int32", "versions": "0+",
+        "about": "The partition." },
+      { "name": "Offset", "type": "int64", "versions": "0+",
+        "about": "The offset." }
+    ]},
+    { "name": "TaskIds", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "The sub-topology identifier." },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "The partitions of the input topics processed by this member." }
+    ]}
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
similarity index 57%
rename from clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
rename to clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
index 9cbbdee2a58..ac11b3d8264 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
@@ -16,7 +16,7 @@
 {
   "apiKey": 89,
   "type": "response",
-  "name": "StreamsHeartbeatResponse",
+  "name": "StreamsGroupHeartbeatResponse",
   "validVersions": "0",
   "flexibleVersions": "0+",
   // Supported errors:
@@ -27,7 +27,6 @@
   // - INVALID_REQUEST (version 0+)
   // - UNKNOWN_MEMBER_ID (version 0+)
   // - FENCED_MEMBER_EPOCH (version 0+)
-  // - UNSUPPORTED_ASSIGNOR (version 0+)
   // - UNRELEASED_INSTANCE_ID (version 0+)
   // - GROUP_MAX_SIZE_REACHED (version 0+)
   "fields": [
@@ -44,45 +43,52 @@
       "about": "The member epoch." },
     { "name": "HeartbeatIntervalMs", "type": "int32", "versions": "0+",
       "about": "The heartbeat interval in milliseconds." },
+    { "name": "AcceptableRecoveryLag", "type": "int32", "versions": "0+",
+      "about": "The maximal lag a warm-up task can have to be considered caught-up." },
+    { "name": "TaskOffsetIntervalMs", "type": "int32", "versions": "0+",
+      "about": "The interval in which the changelog task offsets on a client are updated on the broker. The offsets are sent with the next heartbeat after this time has passed." },
 
-    // Assigning specific roles to the consumer
-    { "name": "ShouldComputeAssignment", "type":  "bool", "versions":  "0+", "default": false,
-      "about": "true if this streams application should compute the next assignment." },
+    // Topology updating
     { "name": "ShouldInitializeTopology", "type":  "bool", "versions":  "0+", "default": false,
       "about": "true if this streams application should initialize the topology on the broker" },
+    { "name": "GroupTopologyId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
+      "about": "The current ID of the topology for the group. Null if unchanged since last heartbeat, empty if group is unitialized." },
 
-    // Possible errors:
-    // - STREAMS_INCONSISTENT_TOPOLOGY (version 0+)
-    // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
-    // - STREAMS_SHUTDOWN_APPLICATION (version 0+)
-    // - STREAMS_GROUP_UNITIALIZED (version 0+)
-    { "name": "AssignmentErrorCode", "type":  "int16", "versions":  "0+", "default": 0,
-      "about": "An error code relating to the current state of the assignment to this member." },
-    { "name": "AssignmentErrorMessage", "type":  "string", "versions":  "0+", "default": "",
-      "about": "An error message relating to the current state of the assignment to this member." },
+    { "name": "Status", "type":  "[]Status", "versions":  "0+",  "nullableVersions": "0+", "default": "null",
+      "about": "Indicate zero or more status for the group.  Null if unchanged since last heartbeat." },
 
     // The streams app knows which partitions to fetch from given this information
     { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
+      "about": "Assigned active tasks for this client. Null if unchanged since last heartbeat." },
     { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
+      "about": "Assigned standby tasks for this client. Null if unchanged since last heartbeat." },
     { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
+      "about": "Assigned warm-up tasks for this client. Null if unchanged since last heartbeat." },
 
     // IQ-related information
-    { "name": "PartitionsByHost", "type": "[]HostInfo", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "PartitionsByUserEndpoint", "type": "[]EndpointToPartitions", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Global assignment information used for IQ. Null if unchanged since last heartbeat." ,
       "fields": [
-        { "name": "Host", "type": "string", "versions": "0+",
-          "about": "Hostname of the node" },
-        { "name": "Port", "type": "int32", "versions": "0+",
-          "about": "Port of the node" },
+        { "name": "UserEndpoint", "type": "Endpoint", "versions": "0+",
+          "about": "User-defined endpoint to connect to the node" },
         { "name": "Partitions", "type": "[]TopicPartition", "versions": "0+",
           "about": "All partitions available on the node" }
       ]
     }
   ],
   "commonStructs": [
+    { "name": "Status", "versions": "0+", "fields": [
+      // Possible status codes
+      //  0 - UNITIALIZED_TOPOLOGY    - The group is not initialized.
+      //  1 - INCONSISTENT_TOPOLOGY   - The topology ID supplied is inconsistent with the topology for this streams group.
+      //  2 - MISSING_SOURCE_TOPICS   - One or more source topics do not exist. Missing topics are indicated in the StatusDetail.
+      //  3 - MISSING_INTERNAL_TOPICS - One or more internal topics do not exist. Missing topics are indicated in the StatusDetail.
+      //  4 - SHUTDOWN_APPLICATION    - A client requested the shutdown of the whole application.
+      { "name": "StatusCode", "type": "int8", "versions": "0+",
+        "about": "A code to indicate that a particular status is active for the group membership" },
+      { "name": "StatusDetail", "type": "string", "versions": "0+",
+        "about": "A string representation of the status." }
+    ]},
     { "name": "TopicPartition", "versions": "0+", "fields": [
       { "name": "Topic", "type": "string", "versions": "0+",
         "about": "topic name" },
@@ -90,12 +96,16 @@
         "about": "partitions" }
     ]},
     { "name": "TaskIds", "versions": "0+", "fields": [
-      // We are using strings here, to avoid fixing a structure on task IDs which will
-      // allow introducing stable naming for subtopologies in the future.
       { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "subtopology ID" },
+        "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "partitions" }
+        "about": "The partitions of the input topics processed by this member." }
+    ]},
+    { "name": "Endpoint", "versions": "0+", "fields": [
+      { "name": "Host", "type": "string", "versions": "0+",
+        "about": "host of the endpoint" },
+      { "name": "Port", "type": "uint16", "versions": "0+",
+        "about": "port of the endpoint" }
     ]}
   ]
-}
+}
\ No newline at end of file
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
similarity index 85%
rename from clients/src/main/resources/common/message/StreamsInitializeRequest.json
rename to clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
index b93fd3d7a7f..169629fb2c0 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
@@ -16,8 +16,8 @@
 {
   "apiKey": 88,
   "type": "request",
-  "listeners": ["zkBroker", "broker"],
-  "name": "StreamsInitializeRequest",
+  "listeners": ["broker"],
+  "name": "StreamsGroupInitializeRequest",
   "validVersions": "0",
   "flexibleVersions": "0+",
   "fields": [
@@ -27,15 +27,15 @@
       "about": "The sub-topologies of the streams application.",
       "fields": [
         { "name": "Subtopology", "type": "string", "versions": "0+",
-          "about": "String to uniquely identify the subtopology." },
+          "about": "String to uniquely identify the sub-topology. Deterministically generated from the topology" },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
-        { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
-          "about": "The regular expressions identifying topics the topology reads from." },
-        { "name": "SinkTopics", "type": "[]string", "versions": "0+",
-          "about": "The topics the topology writes to." },
+        { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+          "about": "The regular expressions identifying topics the sub-topology reads from." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
+          "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
+        { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
+          "about": "The repartition topics the sub-topology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of source topics that are internally created repartition topics. Created automatically." }
       ]
diff --git a/clients/src/main/resources/common/message/StreamsInitializeResponse.json b/clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json
similarity index 85%
rename from clients/src/main/resources/common/message/StreamsInitializeResponse.json
rename to clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json
index 2b4be5f778d..327548577ea 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeResponse.json
@@ -16,16 +16,21 @@
 {
   "apiKey": 88,
   "type": "response",
-  "name": "StreamsInitializeResponse",
+  "name": "StreamsGroupInitializeResponse",
   "validVersions": "0",
   "flexibleVersions": "0+",
   // Supported errors:
   // - GROUP_AUTHORIZATION_FAILED (version 0+)
+  // - GROUP_ID_NOT_FOUND (version 0+)
   // - NOT_COORDINATOR (version 0+)
   // - COORDINATOR_NOT_AVAILABLE (version 0+)
   // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
   // - INVALID_REQUEST (version 0+)
+  // - TOPIC_AUTHORIZATION_FAILED (version 0+)
+  // - CLUSTER_AUTHORIZATION_FAILED (version 0+)
   // - STREAMS_INVALID_TOPOLOGY (version 0+)
+  // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
+  // - STREAMS_INCONSISTENT_INTERNAL_TOPICS (version 0+)
   "fields": [
     { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
       "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
deleted file mode 100644
index 4121133c73c..00000000000
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ /dev/null
@@ -1,99 +0,0 @@
-// 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.
-
-{
-  "apiKey": 89,
-  "type": "request",
-  "listeners": ["zkBroker", "broker"],
-  "name": "StreamsHeartbeatRequest",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  "fields": [
-    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
-      "about": "The group identifier." },
-    { "name": "MemberId", "type": "string", "versions": "0+",
-      "about": "The member id generated by the coordinator. The member id must be kept during the entire lifetime of the member." },
-    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
-      "about": "The current member epoch; 0 to join the group; -1 to leave the group; -2 to indicate that the static member will rejoin." },
-    { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "null if not provided or if it didn't change since the last heartbeat; the instance Id otherwise." },
-    { "name": "RackId", "type": "string", "versions": "0+",  "nullableVersions": "0+", "default": "null",
-      "about": "null if not provided or if it didn't change since the last heartbeat; the rack ID of consumer otherwise." },
-    { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
-      "about": "-1 if it didn't change since the last heartbeat; the maximum time in milliseconds that the coordinator will wait on the member to revoke its partitions otherwise." },
-
-    { "name": "TopologyHash", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": null,
-      "about": "The hash of the topology. Only sent when memberEpoch = 0. Null otherwise. Used to check if topology corresponds to server-topology. " },
-    { "name": "Assignor", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
-      "about": "The desired assignor. Picked by majority vote among clients. If null, the client votes for the broker to pick the assignor." },
-
-    { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
-
-    { "name": "ProcessId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Identity of the streams instance that may have multiple consumers. Null if unchanged since last heartbeat." },
-    { "name": "HostInfo", "type": "HostInfo", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Host information for running interactive queries on this instance. Null if unchanged since last heartbeat.",
-      "fields": [
-        { "name": "Host", "type": "string", "versions": "0+",
-          "about": "Host for running interactive queries on this instance." },
-        { "name": "Port", "type": "int32", "versions": "0+",
-          "about": "Port for running interactive queries on this instance." }
-      ]
-    },
-    { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
-
-    { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
-      "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
-    { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
-      "fields": [
-        { "name": "Subtopology", "type": "string", "versions": "0+",
-          "about": "A unique identifier of the subtopology." },
-        { "name": "Partition", "type": "int32", "versions": "0+",
-          "about": "The partition of the input topics." },
-        { "name": "Offset", "type": "int64", "versions": "0+",
-          "about": "The cumulative offset for the task" }
-      ]
-    },
-    { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
-    { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat." },
-    { "name": "ShutdownApplication", "type": "bool", "versions": "0+", "default": false,
-      "about": "Whether all Streams clients in the group should shut down." }
-  ],
-  "commonStructs": [
-    { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "A unique identifier of the subtopology." },
-      { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "The partition of the input topics." }
-    ]},
-    { "name": "KeyValue", "versions": "0+",
-      "fields": [
-        { "name": "Key", "type": "string", "versions": "0+",
-          "about": "key of the config" },
-        { "name": "Value", "type": "string", "versions": "0+",
-          "about": "value of the config" }
-      ]
-    }
-  ]
-}
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
similarity index 82%
rename from clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
rename to clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index 37e89bfdd69..bc91fc5df83 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -20,7 +20,6 @@ import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.HostInfo;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TaskId;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TopicInfo;
@@ -29,13 +28,13 @@ import org.apache.kafka.common.Node;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.metrics.Sensor;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.RequestHeader;
-import org.apache.kafka.common.requests.StreamsHeartbeatRequest;
-import org.apache.kafka.common.requests.StreamsHeartbeatResponse;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.serialization.StringDeserializer;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
@@ -68,14 +67,14 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-class StreamsHeartbeatRequestManagerTest {
+class StreamsGroupHeartbeatRequestManagerTest {
 
     public static final String TEST_GROUP_ID = "testGroupId";
     public static final String TEST_MEMBER_ID = "testMemberId";
     public static final int TEST_MEMBER_EPOCH = 5;
     public static final String TEST_INSTANCE_ID = "instanceId";
     public static final int TEST_THROTTLE_TIME_MS = 5;
-    private StreamsHeartbeatRequestManager heartbeatRequestManager;
+    private StreamsGroupHeartbeatRequestManager heartbeatRequestManager;
 
     private Time time;
 
@@ -89,9 +88,6 @@ class StreamsHeartbeatRequestManagerTest {
     @Mock
     private StreamsInitializeRequestManager streamsInitializeRequestManager;
 
-    @Mock
-    private StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager;
-
     @Mock
     private MembershipManager membershipManager;
 
@@ -107,7 +103,7 @@ class StreamsHeartbeatRequestManagerTest {
     // Static data for testing
     private final UUID processID = new UUID(1, 1);
 
-    private final HostInfo endPoint = new HostInfo("localhost", 9092);
+    private final StreamsAssignmentInterface.HostInfo endPoint = new StreamsAssignmentInterface.HostInfo("localhost", 8080);
 
     private final String assignor = "test";
 
@@ -129,7 +125,7 @@ class StreamsHeartbeatRequestManagerTest {
         streamsAssignmentInterface =
             new StreamsAssignmentInterface(
                 processID,
-                endPoint,
+                Optional.of(endPoint),
                 assignor,
                 subtopologyMap,
                 assignmentConfiguration,
@@ -140,13 +136,12 @@ class StreamsHeartbeatRequestManagerTest {
 
         MockitoAnnotations.openMocks(this);
         when(metrics.sensor(anyString())).thenReturn(mock(Sensor.class));
-        heartbeatRequestManager = new StreamsHeartbeatRequestManager(
+        heartbeatRequestManager = new StreamsGroupHeartbeatRequestManager(
             logContext,
             time,
             config,
             coordinatorRequestManager,
             streamsInitializeRequestManager,
-            streamsPrepareAssignmentRequestManager,
             membershipManager,
             backgroundEventHandler,
             metrics,
@@ -192,7 +187,7 @@ class StreamsHeartbeatRequestManagerTest {
         assertEquals(1, result.unsentRequests.size());
         assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
 
-        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+        StreamsGroupHeartbeatRequest request = (StreamsGroupHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
 
         assertEquals(TEST_GROUP_ID, request.data().groupId());
         assertEquals(TEST_MEMBER_ID, request.data().memberId());
@@ -201,9 +196,7 @@ class StreamsHeartbeatRequestManagerTest {
 
         // Static information is null
         assertNull(request.data().processId());
-        assertNull(request.data().hostInfo());
-        assertNull(request.data().assignor());
-        assertNull(request.data().assignmentConfigs());
+        assertNull(request.data().userEndpoint());
         assertNull(request.data().clientTags());
     }
 
@@ -218,15 +211,10 @@ class StreamsHeartbeatRequestManagerTest {
         assertEquals(1, result.unsentRequests.size());
         assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
 
-        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+        StreamsGroupHeartbeatRequest request = (StreamsGroupHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
 
         assertEquals(processID.toString(), request.data().processId());
-        assertEquals(endPoint.host, request.data().hostInfo().host());
-        assertEquals(endPoint.port, request.data().hostInfo().port());
-        assertEquals(assignor, request.data().assignor());
-        assertEquals(1, request.data().assignmentConfigs().size());
-        assertEquals("config1", request.data().assignmentConfigs().get(0).key());
-        assertEquals("value1", request.data().assignmentConfigs().get(0).value());
+        assertEquals(endPoint, request.data().userEndpoint());
         assertEquals(1, request.data().clientTags().size());
         assertEquals("clientTag1", request.data().clientTags().get(0).key());
         assertEquals("value2", request.data().clientTags().get(0).value());
@@ -242,7 +230,7 @@ class StreamsHeartbeatRequestManagerTest {
         assertEquals(1, result.unsentRequests.size());
         assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
 
-        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+        StreamsGroupHeartbeatRequest request = (StreamsGroupHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
 
         assertEquals(true, request.data().shutdownApplication());
     }
@@ -284,7 +272,7 @@ class StreamsHeartbeatRequestManagerTest {
                 Collections.singletonMap("changelog2", emptyTopicInfo)
             ));
 
-        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
+        StreamsGroupHeartbeatResponseData data = new StreamsGroupHeartbeatResponseData()
             .setErrorCode(Errors.NONE.code())
             .setThrottleTimeMs(0)
             .setMemberId(TEST_MEMBER_ID)
@@ -292,11 +280,11 @@ class StreamsHeartbeatRequestManagerTest {
             .setThrottleTimeMs(TEST_THROTTLE_TIME_MS)
             .setHeartbeatIntervalMs(1000)
             .setActiveTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("0").setPartitions(Collections.singletonList(0))))
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("0").setPartitions(Collections.singletonList(0))))
             .setStandbyTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("1").setPartitions(Collections.singletonList(1))))
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("1").setPartitions(Collections.singletonList(1))))
             .setWarmupTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("2").setPartitions(Collections.singletonList(2))));
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("2").setPartitions(Collections.singletonList(2))));
 
         mockResponse(data);
 
@@ -332,27 +320,11 @@ class StreamsHeartbeatRequestManagerTest {
 
     }
 
-
-    @Test
-    void testPrepareAssignment() {
-        mockJoiningState();
-
-        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
-            .setErrorCode(Errors.NONE.code())
-            .setThrottleTimeMs(0)
-            .setMemberEpoch(TEST_MEMBER_EPOCH)
-            .setShouldComputeAssignment(true);
-
-        mockResponse(data);
-
-        verify(streamsPrepareAssignmentRequestManager).prepareAssignment();
-    }
-
     @Test
     void testInitializeTopology() {
         mockJoiningState();
 
-        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
+        StreamsGroupHeartbeatResponseData data = new StreamsGroupHeartbeatResponseData()
             .setErrorCode(Errors.NONE.code())
             .setThrottleTimeMs(0)
             .setMemberEpoch(TEST_MEMBER_EPOCH)
@@ -363,7 +335,7 @@ class StreamsHeartbeatRequestManagerTest {
         verify(streamsInitializeRequestManager).initialize();
     }
 
-    private void mockResponse(final StreamsHeartbeatResponseData data) {
+    private void mockResponse(final StreamsGroupHeartbeatResponseData data) {
 
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
 
@@ -383,11 +355,11 @@ class StreamsHeartbeatRequestManagerTest {
 
     private ClientResponse createHeartbeatResponse(
         final NetworkClientDelegate.UnsentRequest request,
-        final StreamsHeartbeatResponseData data
+        final StreamsGroupHeartbeatResponseData data
     ) {
-        StreamsHeartbeatResponse response = new StreamsHeartbeatResponse(data);
+        StreamsGroupHeartbeatResponse response = new StreamsGroupHeartbeatResponse(data);
         return new ClientResponse(
-            new RequestHeader(ApiKeys.STREAMS_HEARTBEAT, ApiKeys.STREAMS_HEARTBEAT.latestVersion(), "client-id", 1),
+            new RequestHeader(ApiKeys.STREAMS_GROUP_HEARTBEAT, ApiKeys.STREAMS_GROUP_HEARTBEAT.latestVersion(), "client-id", 1),
             request.handler(),
             "0",
             time.milliseconds(),
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
similarity index 81%
rename from clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
rename to clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index 6aebd48efec..dd708c8d79a 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -17,9 +17,9 @@
 package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.common.Node;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.requests.StreamsInitializeRequest;
+import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
 import org.apache.kafka.common.utils.LogContext;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
@@ -42,10 +42,10 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 @ExtendWith(MockitoExtension.class)
-class StreamsInitializeRequestManagerTest {
+class StreamsGroupInitializeRequestManagerTest {
 
-    final private String groupId = "groupId";
-    final private LogContext logContext = new LogContext("test");
+    private final String groupId = "groupId";
+    private final LogContext logContext = new LogContext("test");
 
     @Test
     public void shouldPollEmptyResult() {
@@ -104,19 +104,19 @@ class StreamsInitializeRequestManagerTest {
         final NetworkClientDelegate.UnsentRequest unsentRequest = pollResult.unsentRequests.get(0);
         assertTrue(unsentRequest.node().isPresent());
         assertEquals(node, unsentRequest.node().get());
-        assertEquals(ApiKeys.STREAMS_INITIALIZE, unsentRequest.requestBuilder().apiKey());
-        final StreamsInitializeRequest.Builder streamsInitializeRequestBuilder = (StreamsInitializeRequest.Builder) unsentRequest.requestBuilder();
-        final StreamsInitializeRequest streamsInitializeRequest = streamsInitializeRequestBuilder.build();
-        final StreamsInitializeRequestData streamsInitializeRequestData = streamsInitializeRequest.data();
-        assertEquals(ApiKeys.STREAMS_INITIALIZE.id, streamsInitializeRequestData.apiKey());
-        assertEquals(groupId, streamsInitializeRequestData.groupId());
-        assertNotNull(streamsInitializeRequestData.topology());
-        final List<StreamsInitializeRequestData.Subtopology> subtopologies = streamsInitializeRequestData.topology();
+        assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE, unsentRequest.requestBuilder().apiKey());
+        final StreamsGroupInitializeRequest.Builder streamsInitializeRequestBuilder = (StreamsGroupInitializeRequest.Builder) unsentRequest.requestBuilder();
+        final StreamsGroupInitializeRequest streamsGroupInitializeRequest = streamsInitializeRequestBuilder.build();
+        final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = streamsGroupInitializeRequest.data();
+        assertEquals(ApiKeys.STREAMS_GROUP_INITIALIZE.id, streamsGroupInitializeRequestData.apiKey());
+        assertEquals(groupId, streamsGroupInitializeRequestData.groupId());
+        assertNotNull(streamsGroupInitializeRequestData.topology());
+        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = streamsGroupInitializeRequestData.topology();
         assertEquals(1, subtopologies.size());
-        final StreamsInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
+        final StreamsGroupInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
         assertEquals(subtopologyName1, subtopology.subtopology());
         assertEquals(new ArrayList<>(sourceTopics), subtopology.sourceTopics());
-        assertEquals(new ArrayList<>(sinkTopics), subtopology.sinkTopics());
+        assertEquals(new ArrayList<>(sinkTopics), subtopology.repartitionSinkTopics());
         assertEquals(repartitionTopics.size(), subtopology.repartitionSourceTopics().size());
         subtopology.repartitionSourceTopics().forEach(topicInfo -> {
             final StreamsAssignmentInterface.TopicInfo repartitionTopic = repartitionTopics.get(topicInfo.name());
diff --git a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
index 1772de05e85..5bf5baf7c8b 100644
--- a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
@@ -234,10 +234,10 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaPartitionState;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaTopicState;
 import org.apache.kafka.common.message.StopReplicaResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -1127,8 +1127,8 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateRequest(version);
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateRequest(version);
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryRequest(version);
-            case STREAMS_HEARTBEAT: return createStreamsHeartbeatRequest(version);
-            case STREAMS_INITIALIZE: return createStreamsInitializeRequest(version);
+            case STREAMS_GROUP_HEARTBEAT: return createStreamsHeartbeatRequest(version);
+            case STREAMS_GROUP_INITIALIZE: return createStreamsInitializeRequest(version);
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -1223,8 +1223,8 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateResponse();
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateResponse();
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryResponse();
-            case STREAMS_HEARTBEAT: return createStreamsHeartbeatResponse();
-            case STREAMS_INITIALIZE: return createStreamsInitializeResponse();
+            case STREAMS_GROUP_HEARTBEAT: return createStreamsHeartbeatResponse();
+            case STREAMS_GROUP_INITIALIZE: return createStreamsInitializeResponse();
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -4032,11 +4032,11 @@ public class RequestResponseTest {
 //    }
 
     private AbstractRequest createStreamsInitializeRequest(final short version) {
-        return new StreamsInitializeRequest.Builder(new StreamsInitializeRequestData()).build(version);
+        return new StreamsGroupInitializeRequest.Builder(new StreamsGroupInitializeRequestData()).build(version);
     }
 
     private AbstractRequest createStreamsHeartbeatRequest(final short version) {
-        return new StreamsHeartbeatRequest.Builder(new StreamsHeartbeatRequestData()).build(version);
+        return new StreamsGroupHeartbeatRequest.Builder(new StreamsGroupHeartbeatRequestData()).build(version);
     }
 
 //    private AbstractResponse createStreamsPrepareAssignmentResponse() {
@@ -4048,11 +4048,11 @@ public class RequestResponseTest {
 //    }
 //
     private AbstractResponse createStreamsInitializeResponse() {
-        return new StreamsInitializeResponse(new StreamsInitializeResponseData());
+        return new StreamsGroupInitializeResponse(new StreamsGroupInitializeResponseData());
     }
 
     private AbstractResponse createStreamsHeartbeatResponse() {
-        return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData());
+        return new StreamsGroupHeartbeatResponse(new StreamsGroupHeartbeatResponseData());
     }
 
     @Test
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index f7b456699d0..74f30f0d765 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,7 +18,7 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
@@ -79,19 +79,19 @@ private[group] class GroupCoordinatorAdapter(
 
   override def streamsInitialize(
                                    context: RequestContext,
-                                   request: StreamsInitializeRequestData
-                                 ): CompletableFuture[StreamsInitializeResponseData] = {
+                                   request: StreamsGroupInitializeRequestData
+                                 ): CompletableFuture[StreamsGroupInitializeResponseData] = {
     FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
-      s"The old group coordinator does not support ${ApiKeys.STREAMS_INITIALIZE.name} API."
+      s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_INITIALIZE.name} API."
     ))
   }
 
   override def streamsHeartbeat(
                                  context: RequestContext,
-                                 request: StreamsHeartbeatRequestData
-                               ): CompletableFuture[StreamsHeartbeatResponseData] = {
+                                 request: StreamsGroupHeartbeatRequestData
+                               ): CompletableFuture[StreamsGroupHeartbeatResponseData] = {
     FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
-      s"The old group coordinator does not support ${ApiKeys.STREAMS_HEARTBEAT.name} API."
+      s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_HEARTBEAT.name} API."
     ))
   }
 
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index f47a67e5104..9b22b16a55f 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -276,8 +276,8 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.WRITE_SHARE_GROUP_STATE => handleWriteShareGroupStateRequest(request)
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
-        case ApiKeys.STREAMS_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
-        case ApiKeys.STREAMS_HEARTBEAT => handleStreamsHeartbeat(request).exceptionally(handleError)
+        case ApiKeys.STREAMS_GROUP_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
+        case ApiKeys.STREAMS_GROUP_HEARTBEAT => handleStreamsHeartbeat(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
       }
     } catch {
@@ -3886,7 +3886,7 @@ class KafkaApis(val requestChannel: RequestChannel,
   }
 
   def handleStreamsInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    val streamsInitializeRequest = request.body[StreamsInitializeRequest]
+    val streamsInitializeRequest = request.body[StreamsGroupInitializeRequest]
 
     // TODO: Check ACLs on CREATE TOPIC & DESCRIBE_CONFIGS
 
@@ -3906,14 +3906,14 @@ class KafkaApis(val requestChannel: RequestChannel,
         if (exception != null) {
           requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(exception))
         } else {
-          requestHelper.sendMaybeThrottle(request, new StreamsInitializeResponse(response))
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(response))
         }
       }
     }
   }
 
   def handleStreamsHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
-    val streamsHeartbeatRequest = request.body[StreamsHeartbeatRequest]
+    val streamsHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
 
     if (!config.isNewGroupCoordinatorEnabled) {
       // The API is not supported by the "old" group coordinator (the default). If the
@@ -3931,7 +3931,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         if (exception != null) {
           requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(exception))
         } else {
-          requestHelper.sendMaybeThrottle(request, new StreamsHeartbeatResponse(response))
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupHeartbeatResponse(response))
         }
       }
     }
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index 1c6c66b9bcd..d2c2a2ac487 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -19,7 +19,7 @@ package kafka.coordinator.group
 import kafka.coordinator.group.GroupCoordinatorConcurrencyTest.{JoinGroupCallback, SyncGroupCallback}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
 import org.apache.kafka.common.errors.{InvalidGroupIdException, UnsupportedVersionException}
-import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
+import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol
 import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
 import org.apache.kafka.common.message.OffsetDeleteRequestData.{OffsetDeleteRequestPartition, OffsetDeleteRequestTopic, OffsetDeleteRequestTopicCollection}
@@ -83,8 +83,8 @@ class GroupCoordinatorAdapterTest {
     val groupCoordinator = mock(classOf[GroupCoordinator])
     val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
 
-    val ctx = makeContext(ApiKeys.STREAMS_INITIALIZE, ApiKeys.STREAMS_INITIALIZE.latestVersion)
-    val request = new StreamsInitializeRequestData()
+    val ctx = makeContext(ApiKeys.STREAMS_GROUP_INITIALIZE, ApiKeys.STREAMS_GROUP_INITIALIZE.latestVersion)
+    val request = new StreamsGroupInitializeRequestData()
       .setGroupId("group")
 
     val future = adapter.streamsInitialize(ctx, request)
@@ -99,8 +99,8 @@ class GroupCoordinatorAdapterTest {
     val groupCoordinator = mock(classOf[GroupCoordinator])
     val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
 
-    val ctx = makeContext(ApiKeys.STREAMS_HEARTBEAT, ApiKeys.STREAMS_HEARTBEAT.latestVersion)
-    val request = new StreamsHeartbeatRequestData()
+    val ctx = makeContext(ApiKeys.STREAMS_GROUP_HEARTBEAT, ApiKeys.STREAMS_GROUP_HEARTBEAT.latestVersion)
+    val request = new StreamsGroupHeartbeatRequestData()
       .setGroupId("group")
 
     val future = adapter.streamsHeartbeat(ctx, request)
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index c0bfa5d0f31..917c47aeea2 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11236,11 +11236,11 @@ class KafkaApisTest extends Logging {
 
   @Test
   def testStreamsInitializeRequest(): Unit = {
-    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
 
-    val future = new CompletableFuture[StreamsInitializeResponseData]()
+    val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
     when(groupCoordinator.streamsInitialize(
       requestChannelRequest.context,
       streamsInitializeRequest
@@ -11250,20 +11250,20 @@ class KafkaApisTest extends Logging {
     ))
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val streamsInitializeResponse = new StreamsInitializeResponseData()
+    val streamsInitializeResponse = new StreamsGroupInitializeResponseData()
 
     future.complete(streamsInitializeResponse)
-    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
     assertEquals(streamsInitializeResponse, response.data)
   }
 
   @Test
   def testStreamsInitializeRequestFutureFailed(): Unit = {
-    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
 
-    val future = new CompletableFuture[StreamsInitializeResponseData]()
+    val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
     when(groupCoordinator.streamsInitialize(
       requestChannelRequest.context,
       streamsInitializeRequest
@@ -11274,15 +11274,15 @@ class KafkaApisTest extends Logging {
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
-    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
     assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
   }
 
   @Test
   def testStreamsInitializeRequestAuthorizationFailed(): Unit = {
-    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
 
     val authorizer: Authorizer = mock(classOf[Authorizer])
     when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
@@ -11293,18 +11293,18 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
 
 
   @Test
   def testStreamsHeartbeatRequest(): Unit = {
-    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsHeartbeatResponseData]()
+    val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
     when(groupCoordinator.streamsHeartbeat(
       requestChannelRequest.context,
       streamsHeartbeatRequest
@@ -11314,21 +11314,21 @@ class KafkaApisTest extends Logging {
     ))
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val streamsHeartbeatResponse = new StreamsHeartbeatResponseData()
+    val streamsHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
       .setMemberId("member")
 
     future.complete(streamsHeartbeatResponse)
-    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(streamsHeartbeatResponse, response.data)
   }
 
   @Test
   def testStreamsHeartbeatRequestFutureFailed(): Unit = {
-    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
 
-    val future = new CompletableFuture[StreamsHeartbeatResponseData]()
+    val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
     when(groupCoordinator.streamsHeartbeat(
       requestChannelRequest.context,
       streamsHeartbeatRequest
@@ -11339,15 +11339,15 @@ class KafkaApisTest extends Logging {
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
-    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
   }
 
   @Test
   def testStreamsHeartbeatRequestAuthorizationFailed(): Unit = {
-    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
 
     val authorizer: Authorizer = mock(classOf[Authorizer])
     when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
@@ -11358,7 +11358,7 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index 900a789f2c0..f25b5c39461 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -39,10 +39,10 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -95,9 +95,9 @@ public interface GroupCoordinator {
      * @return  A future yielding the response.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsInitializeResponseData> streamsInitialize(
+    CompletableFuture<StreamsGroupInitializeResponseData> streamsInitialize(
         RequestContext context,
-        StreamsInitializeRequestData request
+        StreamsGroupInitializeRequestData request
     );
 
     /**
@@ -109,9 +109,9 @@ public interface GroupCoordinator {
      * @return  A future yielding the response.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsHeartbeatResponseData> streamsHeartbeat(
+    CompletableFuture<StreamsGroupHeartbeatResponseData> streamsHeartbeat(
         RequestContext context,
-        StreamsHeartbeatRequestData request
+        StreamsGroupHeartbeatRequestData request
     );
 
     /**
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index 78c17bb0863..63d5523f137 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -17,7 +17,6 @@
 package org.apache.kafka.coordinator.group;
 
 import org.apache.kafka.common.Uuid;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.record.RecordBatch;
 import org.apache.kafka.common.requests.OffsetCommitRequest;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
@@ -52,25 +51,10 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.modern.TopicMetadata;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
 import org.apache.kafka.coordinator.group.modern.consumer.ResolvedRegularExpression;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
-import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.server.common.MetadataVersion;
 
@@ -79,7 +63,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.stream.Collectors;
 
 /**
  * This class contains helper methods to create records stored in the __consumer_offsets topic.
@@ -146,66 +129,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsGroupMemberRecord(
-        String groupId,
-        StreamsGroupMember member
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupMemberMetadataKey()
-                    .setGroupId(groupId)
-                    .setMemberId(member.memberId()),
-                (short) 14
-            ),
-            new ApiMessageAndVersion(
-                new StreamsGroupMemberMetadataValue()
-                    .setRackId(member.rackId())
-                    .setInstanceId(member.instanceId())
-                    .setClientId(member.clientId())
-                    .setClientHost(member.clientHost())
-                    .setRebalanceTimeoutMs(member.rebalanceTimeoutMs())
-                    .setTopologyHash(member.topologyHash())
-                    .setProcessId(member.processId())
-                    .setHostInfo(member.hostInfo())
-                    .setAssignor(member.assignor().orElse(null))
-                    .setClientTags(member.clientTags().entrySet().stream().map(e ->
-                        new StreamsGroupMemberMetadataValue.KeyValue()
-                            .setKey(e.getKey())
-                            .setValue(e.getValue())
-                    ).collect(Collectors.toList()))
-                    .setUserData(member.userData())
-                    .setAssignmentConfigs(member.assignmentConfigs().entrySet().stream().map(e ->
-                        new StreamsGroupMemberMetadataValue.KeyValue()
-                            .setKey(e.getKey())
-                            .setValue(e.getValue())
-                    ).collect(Collectors.toList())),
-                (short) 0
-            )
-        );
-    }
-
-    /**
-     * Creates a StreamsGroupMemberMetadata tombstone.
-     *
-     * @param groupId  The streams group id.
-     * @param memberId The streams group member id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupMemberTombstoneRecord(
-        String groupId,
-        String memberId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupMemberMetadataKey()
-                    .setGroupId(groupId)
-                    .setMemberId(memberId),
-                (short) 14
-            ),
-            null // Tombstone.
-        );
-    }
-
     /**
      * Creates a ConsumerGroupPartitionMetadata record.
      *
@@ -258,69 +181,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    /**
-     * Creates a StreamsGroupPartitionMetadata record.
-     *
-     * @param groupId                 The streams group id.
-     * @param newSubscriptionMetadata The subscription metadata.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupPartitionMetadataRecord(
-        String groupId,
-        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newSubscriptionMetadata
-    ) {
-        StreamsGroupPartitionMetadataValue value = new StreamsGroupPartitionMetadataValue();
-        newSubscriptionMetadata.forEach((topicName, topicMetadata) -> {
-            List<StreamsGroupPartitionMetadataValue.PartitionMetadata> partitionMetadata = new ArrayList<>();
-            // If the partition rack information map is empty, store an empty list in the record.
-            if (!topicMetadata.partitionRacks().isEmpty()) {
-                topicMetadata.partitionRacks().forEach((partition, racks) ->
-                    partitionMetadata.add(new StreamsGroupPartitionMetadataValue.PartitionMetadata()
-                        .setPartition(partition)
-                        .setRacks(new ArrayList<>(racks))
-                    )
-                );
-            }
-            value.topics().add(new StreamsGroupPartitionMetadataValue.TopicMetadata()
-                .setTopicId(topicMetadata.id())
-                .setTopicName(topicMetadata.name())
-                .setNumPartitions(topicMetadata.numPartitions())
-                .setPartitionMetadata(partitionMetadata)
-            );
-        });
-
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupPartitionMetadataKey()
-                    .setGroupId(groupId),
-                (short) 13
-            ),
-            new ApiMessageAndVersion(
-                value,
-                (short) 0
-            )
-        );
-    }
-
-    /**
-     * Creates a StreamsGroupPartitionMetadata tombstone.
-     *
-     * @param groupId The streams group id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupPartitionMetadataTombstoneRecord(
-        String groupId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupPartitionMetadataKey()
-                    .setGroupId(groupId),
-                (short) 13
-            ),
-            null // Tombstone.
-        );
-    }
-
     /**
      * Creates a ConsumerGroupMetadata record.
      *
@@ -346,43 +206,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsGroupEpochRecord(
-        String groupId,
-        int newGroupEpoch
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupMetadataKey()
-                    .setGroupId(groupId),
-                (short) 12
-            ),
-            new ApiMessageAndVersion(
-                new StreamsGroupMetadataValue()
-                    .setEpoch(newGroupEpoch),
-                (short) 0
-            )
-        );
-    }
-
-    /**
-     * Creates a StreamsGroupMetadata tombstone.
-     *
-     * @param groupId The streams group id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupEpochTombstoneRecord(
-        String groupId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupMetadataKey()
-                    .setGroupId(groupId),
-                (short) 12
-            ),
-            null // Tombstone.
-        );
-    }
-
     /**
      * Creates a ConsumerGroupMetadata tombstone.
      *
@@ -463,77 +286,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsTargetAssignmentRecord(
-        String groupId,
-        String memberId,
-        Map<String, Set<Integer>> activeTasks,
-        Map<String, Set<Integer>> standbyTasks,
-        Map<String, Set<Integer>> warmupTasks
-    ) {
-        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> activeTaskIds = new ArrayList<>(activeTasks.size());
-        for (Map.Entry<String, Set<Integer>> entry : activeTasks.entrySet()) {
-            activeTaskIds.add(
-                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
-                    .setPartitions(new ArrayList<>(entry.getValue()))
-            );
-        }
-        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> standbyTaskIds = new ArrayList<>(standbyTasks.size());
-        for (Map.Entry<String, Set<Integer>> entry : standbyTasks.entrySet()) {
-            standbyTaskIds.add(
-                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
-                    .setPartitions(new ArrayList<>(entry.getValue()))
-            );
-        }
-        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> warmupTaskIds = new ArrayList<>(warmupTasks.size());
-        for (Map.Entry<String, Set<Integer>> entry : warmupTasks.entrySet()) {
-            warmupTaskIds.add(
-                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
-                    .setPartitions(new ArrayList<>(entry.getValue()))
-            );
-        }
-
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMemberKey()
-                    .setGroupId(groupId)
-                    .setMemberId(memberId),
-                (short) 16
-            ),
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMemberValue()
-                    .setActiveTasks(activeTaskIds)
-                    .setStandbyTasks(standbyTaskIds)
-                    .setWarmupTasks(warmupTaskIds),
-                (short) 0
-            )
-        );
-    }
-
-    /**
-     * Creates a StreamsGroupTargetAssignmentMember tombstone.
-     *
-     * @param groupId  The streams group id.
-     * @param memberId The streams group member id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsTargetAssignmentTombstoneRecord(
-        String groupId,
-        String memberId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMemberKey()
-                    .setGroupId(groupId)
-                    .setMemberId(memberId),
-                (short) 16
-            ),
-            null // Tombstone.
-        );
-    }
-
     /**
      * Creates a ConsumerGroupTargetAssignmentMetadata record.
      *
@@ -578,44 +330,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-
-    public static CoordinatorRecord newStreamsTargetAssignmentEpochRecord(
-        String groupId,
-        int assignmentEpoch
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMetadataKey()
-                    .setGroupId(groupId),
-                (short) 15
-            ),
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMetadataValue()
-                    .setAssignmentEpoch(assignmentEpoch),
-                (short) 0
-            )
-        );
-    }
-
-    /**
-     * Creates a StreamsGroupTargetAssignmentMetadata tombstone.
-     *
-     * @param groupId The streams group id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsTargetAssignmentEpochTombstoneRecord(
-        String groupId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTargetAssignmentMetadataKey()
-                    .setGroupId(groupId),
-                (short) 15
-            ),
-            null // Tombstone.
-        );
-    }
-
     /**
      * Creates a ConsumerGroupCurrentMemberAssignment record.
      *
@@ -646,31 +360,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsCurrentAssignmentRecord(
-        String groupId,
-        StreamsGroupMember member
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupCurrentMemberAssignmentKey()
-                    .setGroupId(groupId)
-                    .setMemberId(member.memberId()),
-                (short) 17
-            ),
-            new ApiMessageAndVersion(
-                new StreamsGroupCurrentMemberAssignmentValue()
-                    .setMemberEpoch(member.memberEpoch())
-                    .setPreviousMemberEpoch(member.previousMemberEpoch())
-                    .setState(member.state().value())
-                    .setActiveTasks(toTaskIds(member.assignedActiveTasks()))
-                    .setStandbyTasks(toTaskIds(member.assignedStandbyTasks()))
-                    .setWarmupTasks(toTaskIds(member.assignedWarmupTasks()))
-                    .setActiveTasksPendingRevocation(toTaskIds(member.activeTasksPendingRevocation())),
-                (short) 0
-            )
-        );
-    }
-
     /**
      * Creates a ConsumerGroupCurrentMemberAssignment tombstone.
      *
@@ -726,28 +415,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    /**
-     * Creates a StreamsGroupCurrentMemberAssignment tombstone.
-     *
-     * @param groupId  The streams group id.
-     * @param memberId The streams group member id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsCurrentAssignmentTombstoneRecord(
-        String groupId,
-        String memberId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupCurrentMemberAssignmentKey()
-                    .setGroupId(groupId)
-                    .setMemberId(memberId),
-                (short) 17
-            ),
-            null // Tombstone
-        );
-    }
-
     /**
      * Creates a ConsumerGroupRegularExpression tombstone.
      *
@@ -1270,72 +937,4 @@ public class GroupCoordinatorRecordHelpers {
         );
         return topics;
     }
-
-    private static List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> toTaskIds(
-        Map<String, Set<Integer>> tasks
-    ) {
-        List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> taskIds = new ArrayList<>(tasks.size());
-        tasks.forEach((subtopologyId, partitions) ->
-            taskIds.add(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subtopologyId)
-                .setPartitions(new ArrayList<>(partitions)))
-        );
-        return taskIds;
-    }
-
-    /**
-     * Creates a StreamsTopology record.
-     *
-     * @param groupId       The consumer group id.
-     * @param subtopologies The subtopologies in the new topology.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
-                                                                  List<StreamsInitializeRequestData.Subtopology> subtopologies) {
-        StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
-        subtopologies.forEach(subtopology -> {
-            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
-                .map(topicInfo -> {
-                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                        .collect(Collectors.toList()) : null;
-                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
-                        .setPartitions(topicInfo.partitions());
-                }).collect(Collectors.toList());
-
-            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
-                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                    .collect(Collectors.toList()) : null;
-                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
-            }).collect(Collectors.toList());
-
-            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopology())
-                .setSourceTopics(subtopology.sourceTopics()).setSinkTopics(subtopology.sinkTopics())
-                .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
-        });
-
-        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 18),
-            new ApiMessageAndVersion(value, (short) 0));
-    }
-
-    /**
-     * Creates a StreamsGroupTopology tombstone.
-     *
-     * @param groupId The streams group id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newStreamsGroupTopologyRecordTombstone(
-        String groupId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTopologyKey()
-                    .setGroupId(groupId),
-                (short) 18
-            ),
-            null // Tombstone
-        );
-    }
-
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 20042ebfb06..b2e2460064c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -44,10 +44,10 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData.DescribedGroup;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -349,15 +349,15 @@ public class GroupCoordinatorService implements GroupCoordinator {
     }
 
     /**
-     * See {@link GroupCoordinator#streamsInitialize(RequestContext, StreamsInitializeRequestData)}.
+     * See {@link GroupCoordinator#streamsInitialize(RequestContext, org.apache.kafka.common.message.StreamsGroupInitializeRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsInitializeResponseData> streamsInitialize(
+    public CompletableFuture<StreamsGroupInitializeResponseData> streamsInitialize(
         RequestContext context,
-        StreamsInitializeRequestData request
+        StreamsGroupInitializeRequestData request
     ) {
         if (!isActive.get()) {
-            return CompletableFuture.completedFuture(new StreamsInitializeResponseData()
+            return CompletableFuture.completedFuture(new StreamsGroupInitializeResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
             );
         }
@@ -371,22 +371,22 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-group-initialize",
             request,
             exception,
-            (error, message) -> new StreamsInitializeResponseData()
+            (error, message) -> new StreamsGroupInitializeResponseData()
                 .setErrorCode(error.code())
                 .setErrorMessage(message)
         ));
     }
 
     /**
-     * See {@link GroupCoordinator#streamsHeartbeat(RequestContext, StreamsHeartbeatRequestData)}.
+     * See {@link GroupCoordinator#streamsHeartbeat(RequestContext, org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsHeartbeatResponseData> streamsHeartbeat(
+    public CompletableFuture<StreamsGroupHeartbeatResponseData> streamsHeartbeat(
         RequestContext context,
-        StreamsHeartbeatRequestData request
+        StreamsGroupHeartbeatRequestData request
     ) {
         if (!isActive.get()) {
-            return CompletableFuture.completedFuture(new StreamsHeartbeatResponseData()
+            return CompletableFuture.completedFuture(new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
             );
         }
@@ -400,7 +400,7 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-heartbeat",
             request,
             exception,
-            (error, message) -> new StreamsHeartbeatResponseData()
+            (error, message) -> new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(error.code())
                 .setErrorMessage(message)
         ));
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index aa0a18d0bff..4816649d9f6 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -39,10 +39,10 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -397,9 +397,9 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
      * @return A Result containing the StreamsInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
         RequestContext context,
-        StreamsInitializeRequestData request
+        StreamsGroupInitializeRequestData request
     ) {
         return groupMetadataManager.streamsInitialize(context, request);
     }
@@ -413,9 +413,9 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
      * @return A Result containing the StreamsHeartbeat response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
         RequestContext context,
-        StreamsHeartbeatRequestData request
+        StreamsGroupHeartbeatRequestData request
     ) {
         return groupMetadataManager.streamsHeartbeat(context, request);
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 09dd21913e6..1d95cad5a7e 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -53,14 +53,14 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.KeyValue;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskIds;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskOffset;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.Endpoint;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.KeyValue;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskIds;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.TaskOffset;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.protocol.Errors;
@@ -200,14 +200,6 @@ import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.n
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupMemberSubscriptionTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupSubscriptionMetadataRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupTargetAssignmentTombstoneRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsCurrentAssignmentRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupEpochRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupMemberRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupMemberTombstoneRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupPartitionMetadataRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupTopologyRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.Utils.assignmentToString;
 import static org.apache.kafka.coordinator.group.Utils.ofSentinel;
 import static org.apache.kafka.coordinator.group.Utils.taskAssignmentToString;
@@ -223,6 +215,14 @@ import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.CONSUMER_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.STREAMS_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember.hasAssignedPartitionsChanged;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberTombstoneRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedActiveTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedStandbyTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedWarmupTasksChanged;
@@ -1645,7 +1645,7 @@ public class GroupMetadataManager {
      * @throws UnsupportedAssignorException if the assignor is not supported.
      */
     private void throwIfStreamsInitializeRequestIsInvalid(
-        StreamsInitializeRequestData request
+        StreamsGroupInitializeRequestData request
     ) throws InvalidRequestException, UnsupportedAssignorException {
         throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
 
@@ -1667,7 +1667,7 @@ public class GroupMetadataManager {
      * @throws UnsupportedAssignorException if the assignor is not supported.
      */
     private void throwIfStreamsHeartbeatRequestIsInvalid(
-        StreamsHeartbeatRequestData request
+        StreamsGroupHeartbeatRequestData request
     ) throws InvalidRequestException, UnsupportedAssignorException {
         throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
         throwIfEmptyString(request.instanceId(), "InstanceId can't be empty.");
@@ -1744,12 +1744,12 @@ public class GroupMetadataManager {
      * @return A boolean indicating whether the owned partitions are a subset or not.
      */
     private boolean isTaskSubset(
-        List<StreamsHeartbeatRequestData.TaskIds> ownedTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedTasks,
         Map<String, Set<Integer>> target
     ) {
         if (ownedTasks == null) return false;
 
-        for (StreamsHeartbeatRequestData.TaskIds topicPartitions : ownedTasks) {
+        for (StreamsGroupHeartbeatRequestData.TaskIds topicPartitions : ownedTasks) {
             Set<Integer> partitions = target.get(topicPartitions.subtopology());
             if (partitions == null) return false;
             for (Integer partitionId : topicPartitions.partitions()) {
@@ -1949,9 +1949,9 @@ public class GroupMetadataManager {
     private void throwIfMemberEpochIsInvalid(
         StreamsGroupMember member,
         int receivedMemberEpoch,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks
     ) {
         if (receivedMemberEpoch > member.memberEpoch()) {
             throw new FencedMemberEpochException("The streams group member has a greater member "
@@ -2207,36 +2207,34 @@ public class GroupMetadataManager {
      * @param instanceId         The instance id from the request or null.
      * @param rackId             The rack id from the request or null.
      * @param rebalanceTimeoutMs The rebalance timeout from the request or -1.
-     * @param topologyHash
+     * @param topologyId         The topology id from the request or null.
      * @param clientId           The client id.
      * @param clientHost         The client host.
-     * @param assignorName       The assignor name from the request or null.
      * @param ownedActiveTasks   The list of owned active tasks from the request or null.
      * @param ownedStandbyTasks  The list of owned standby tasks from the request or null.
      * @param ownedWarmupTasks   The list of owned warmup tasks from the request or null.
+     * @param userEndpoint
+     * @param clientTags
      * @return A Result containing the StreamsHeartbeat response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
         String groupId,
         String memberId,
         int memberEpoch,
         String instanceId,
         String rackId,
         int rebalanceTimeoutMs,
-        final byte[] topologyHash,
+        final String topologyId,
         String clientId,
         String clientHost,
-        String assignorName,
         List<TaskIds> ownedActiveTasks,
         List<TaskIds> ownedStandbyTasks,
         List<TaskIds> ownedWarmupTasks,
         final String processId,
-        final HostInfo hostInfo,
+        final Endpoint userEndpoint,
         final List<KeyValue> clientTags,
-        final byte taskOffsetUpdateReason,
         final List<TaskOffset> taskOffsets,
-        final byte[] userData,
-        final List<KeyValue> assignmentConfigs,
+        final List<TaskOffset> taskEndOffsets,
         final boolean shutdownApplication
     ) throws ApiException {
         final long currentTimeMs = time.milliseconds();
@@ -2301,15 +2299,12 @@ public class GroupMetadataManager {
             .maybeUpdateInstanceId(Optional.ofNullable(instanceId))
             .maybeUpdateRackId(Optional.ofNullable(rackId))
             .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs))
-            .maybeUpdateAssignor(Optional.ofNullable(assignorName))
-            .maybeUpdateTopologyHash(Optional.ofNullable(topologyHash))
+            .maybeUpdateTopologyId(Optional.ofNullable(topologyId))
             .setClientId(clientId)
             .setClientHost(clientHost)
             .maybeUpdateProcessId(Optional.ofNullable(processId))
             .maybeUpdateClientTags(Optional.ofNullable(clientTags).map(x -> x.stream().collect(Collectors.toMap(KeyValue::key, KeyValue::value))))
-            .maybeUpdateUserData(Optional.ofNullable(userData))
-            .maybeUpdateAssignmentConfigs(Optional.ofNullable(assignmentConfigs).map(x -> x.stream().collect(Collectors.toMap(KeyValue::key, KeyValue::value))))
-            .maybeUpdateHostInfo(Optional.ofNullable(hostInfo).map(x -> new StreamsGroupMemberMetadataValue.HostInfo().setHost(x.host()).setPort(x.port())))
+            .maybeUpdateUserEndpoint(Optional.ofNullable(userEndpoint).map(x -> new StreamsGroupMemberMetadataValue.Endpoint().setHost(x.host()).setPort(x.port())))
             .build();
 
         int groupEpoch = group.groupEpoch();
@@ -2384,7 +2379,7 @@ public class GroupMetadataManager {
         }
 
         // Prepare the response.
-        StreamsHeartbeatResponseData response = new StreamsHeartbeatResponseData()
+        StreamsGroupHeartbeatResponseData response = new StreamsGroupHeartbeatResponseData()
             .setMemberId(updatedMember.memberId())
             .setMemberEpoch(updatedMember.memberEpoch())
             .setShouldInitializeTopology(group.topology() == null)
@@ -2407,9 +2402,9 @@ public class GroupMetadataManager {
         return new CoordinatorResult<>(records, response);
     }
 
-    private List<StreamsHeartbeatResponseData.TaskIds> createStreamsHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
+    private List<StreamsGroupHeartbeatResponseData.TaskIds> createStreamsHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
         return taskIds.entrySet().stream()
-            .map(entry -> new StreamsHeartbeatResponseData.TaskIds()
+            .map(entry -> new StreamsGroupHeartbeatResponseData.TaskIds()
                 .setSubtopology(entry.getKey())
                 .setPartitions(new ArrayList<>(entry.getValue())))
             .collect(Collectors.toList());
@@ -2634,8 +2629,8 @@ public class GroupMetadataManager {
      * @param subtopologies The list of subtopologies
      * @return A Result containing the StreamsInitialize response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(String groupId,
-                                                                                                  List<StreamsInitializeRequestData.Subtopology> subtopologies)
+    private CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(String groupId,
+                                                                                                       List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
         throws ApiException {
         final List<CoordinatorRecord> records = new ArrayList<>();
 
@@ -2646,21 +2641,21 @@ public class GroupMetadataManager {
 
         // TODO: For the POC, only check if internal topics exist
         Set<String> missingTopics = new HashSet<>();
-        for (StreamsInitializeRequestData.Subtopology subtopology : subtopologies) {
-            for (StreamsInitializeRequestData.TopicInfo topic : subtopology.stateChangelogTopics()) {
+        for (StreamsGroupInitializeRequestData.Subtopology subtopology : subtopologies) {
+            for (StreamsGroupInitializeRequestData.TopicInfo topic : subtopology.stateChangelogTopics()) {
                 if (metadataImage.topics().getTopic(topic.name()) == null) {
                     missingTopics.add(topic.name());
                 }
             }
-            for (StreamsInitializeRequestData.TopicInfo topic : subtopology.repartitionSourceTopics()) {
+            for (StreamsGroupInitializeRequestData.TopicInfo topic : subtopology.repartitionSourceTopics()) {
                 if (metadataImage.topics().getTopic(topic.name()) == null) {
                     missingTopics.add(topic.name());
                 }
             }
         }
         if (!missingTopics.isEmpty()) {
-            StreamsInitializeResponseData response =
-                new StreamsInitializeResponseData()
+            StreamsGroupInitializeResponseData response =
+                new StreamsGroupInitializeResponseData()
                     .setErrorCode(STREAMS_INVALID_TOPOLOGY.code())
                     .setErrorMessage("Internal topics " + String.join(", ", missingTopics) + " do not exist.");
 
@@ -2668,7 +2663,7 @@ public class GroupMetadataManager {
         } else {
             records.add(newStreamsGroupTopologyRecord(groupId, subtopologies));
 
-            StreamsInitializeResponseData response = new StreamsInitializeResponseData();
+            StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
 
             return new CoordinatorResult<>(records, response);
         }
@@ -3511,9 +3506,9 @@ public class GroupMetadataManager {
         if (!updatedMember.equals(member)) {
             records.add(newStreamsGroupMemberRecord(groupId, updatedMember));
 
-            if (updatedMember.topologyHash() != member.topologyHash()) {
-                log.info("[GroupId {}] Member {} updated its topology hash to: {}.",
-                    groupId, memberId, updatedMember.topologyHash());
+            if (updatedMember.topologyId().equals(member.topologyId())) {
+                log.info("[GroupId {}] Member {} updated its topology ID to: {}.",
+                    groupId, memberId, updatedMember.topologyId());
                 return true;
             }
         }
@@ -3651,9 +3646,9 @@ public class GroupMetadataManager {
         BiFunction<String, Integer, Integer> currentActiveTaskEpoch,
         int targetAssignmentEpoch,
         org.apache.kafka.coordinator.group.streams.Assignment targetAssignment,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks,
-        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks,
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks,
         List<CoordinatorRecord> records
     ) {
         if (member.isReconciledTo(targetAssignmentEpoch)) {
@@ -3933,14 +3928,14 @@ public class GroupMetadataManager {
      * @return A Result containing the StreamsHeartbeat response and
      *         a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsGroupLeave(
+    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupLeave(
         String groupId,
         String instanceId,
         String memberId,
         int memberEpoch
     ) throws ApiException {
         StreamsGroup group = streamsGroup(groupId);
-        StreamsHeartbeatResponseData response = new StreamsHeartbeatResponseData()
+        StreamsGroupHeartbeatResponseData response = new StreamsGroupHeartbeatResponseData()
             .setMemberId(memberId)
             .setMemberEpoch(memberEpoch);
 
@@ -4031,7 +4026,7 @@ public class GroupMetadataManager {
      *
      * @return A CoordinatorResult with a single record signifying that the static member is leaving.
      */
-    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsGroupStaticMemberGroupLeave(
+    private CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsGroupStaticMemberGroupLeave(
         StreamsGroup group,
         StreamsGroupMember member
     ) {
@@ -4043,7 +4038,7 @@ public class GroupMetadataManager {
 
         return new CoordinatorResult<>(
             Collections.singletonList(newStreamsCurrentAssignmentRecord(group.groupId(), leavingStaticMember)),
-            new StreamsHeartbeatResponseData()
+            new StreamsGroupHeartbeatResponseData()
                 .setMemberId(member.memberId())
                 .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH)
         );
@@ -4765,9 +4760,9 @@ public class GroupMetadataManager {
      * @return A Result containing the StreamsInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
         RequestContext context,
-        StreamsInitializeRequestData request
+        StreamsGroupInitializeRequestData request
     ) throws ApiException {
         throwIfStreamsInitializeRequestIsInvalid(request);
 
@@ -4786,9 +4781,9 @@ public class GroupMetadataManager {
      * @return A Result containing the StreamsHeartbeat response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
         RequestContext context,
-        StreamsHeartbeatRequestData request
+        StreamsGroupHeartbeatRequestData request
     ) throws ApiException {
         throwIfStreamsHeartbeatRequestIsInvalid(request);
 
@@ -4808,20 +4803,17 @@ public class GroupMetadataManager {
                 request.instanceId(),
                 request.rackId(),
                 request.rebalanceTimeoutMs(),
-                request.topologyHash(),
+                request.topologyId(),
                 context.clientId(),
                 context.clientAddress.toString(),
-                request.assignor(),
                 request.activeTasks(),
                 request.standbyTasks(),
                 request.warmupTasks(),
                 request.processId(),
-                request.hostInfo(),
+                request.userEndpoint(),
                 request.clientTags(),
-                request.taskOffsetUpdateReason(),
-                request.taskOffset(),
-                request.userData(),
-                request.assignmentConfigs(),
+                request.taskOffsets(),
+                request.taskEndOffsets(),
                 request.shutdownApplication()
             );
         }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
index a71caae371f..bf595347273 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
@@ -74,8 +74,8 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
     public static final String SHARE_GROUP_COUNT_METRIC_NAME = "group-count";
     public static final String CONSUMER_GROUP_COUNT_STATE_TAG = "state";
     public static final String SHARE_GROUP_COUNT_STATE_TAG = CONSUMER_GROUP_COUNT_STATE_TAG;
-    public final static String STREAMS_GROUP_COUNT_METRIC_NAME = "streams-group-count";
-    public final static String STREAMS_GROUP_COUNT_STATE_TAG = "state";
+    public static final String STREAMS_GROUP_COUNT_METRIC_NAME = "streams-group-count";
+    public static final String STREAMS_GROUP_COUNT_STATE_TAG = "state";
 
     public static final String OFFSET_COMMITS_SENSOR_NAME = "OffsetCommits";
     public static final String OFFSET_EXPIRED_SENSOR_NAME = "OffsetExpired";
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
new file mode 100644
index 00000000000..f5cac3026aa
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -0,0 +1,427 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * This class contains helper methods to create records stored in the __consumer_offsets topic.
+ */
+@SuppressWarnings("ClassDataAbstractionCoupling")
+public class CoordinatorStreamsRecordHelpers {
+
+    private CoordinatorStreamsRecordHelpers() {
+    }
+
+    public static CoordinatorRecord newStreamsGroupMemberRecord(
+        String groupId,
+        StreamsGroupMember member
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMemberMetadataKey()
+                    .setGroupId(groupId)
+                    .setMemberId(member.memberId()),
+                (short) 14
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupMemberMetadataValue()
+                    .setRackId(member.rackId())
+                    .setInstanceId(member.instanceId())
+                    .setClientId(member.clientId())
+                    .setClientHost(member.clientHost())
+                    .setRebalanceTimeoutMs(member.rebalanceTimeoutMs())
+                    .setTopologyId(member.topologyId())
+                    .setProcessId(member.processId())
+                    .setUserEndpoint(member.userEndpoint())
+                    .setClientTags(member.clientTags().entrySet().stream().map(e ->
+                        new StreamsGroupMemberMetadataValue.KeyValue()
+                            .setKey(e.getKey())
+                            .setValue(e.getValue())
+                    ).collect(Collectors.toList())),
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupMemberMetadata tombstone.
+     *
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupMemberTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMemberMetadataKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 14
+            ),
+            null // Tombstone.
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupPartitionMetadata record.
+     *
+     * @param groupId                 The streams group id.
+     * @param newSubscriptionMetadata The subscription metadata.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupPartitionMetadataRecord(
+        String groupId,
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newSubscriptionMetadata
+    ) {
+        StreamsGroupPartitionMetadataValue value = new StreamsGroupPartitionMetadataValue();
+        newSubscriptionMetadata.forEach((topicName, topicMetadata) -> {
+            List<StreamsGroupPartitionMetadataValue.PartitionMetadata> partitionMetadata = new ArrayList<>();
+            // If the partition rack information map is empty, store an empty list in the record.
+            if (!topicMetadata.partitionRacks().isEmpty()) {
+                topicMetadata.partitionRacks().forEach((partition, racks) ->
+                    partitionMetadata.add(new StreamsGroupPartitionMetadataValue.PartitionMetadata()
+                        .setPartition(partition)
+                        .setRacks(new ArrayList<>(racks))
+                    )
+                );
+            }
+            value.topics().add(new StreamsGroupPartitionMetadataValue.TopicMetadata()
+                .setTopicId(topicMetadata.id())
+                .setTopicName(topicMetadata.name())
+                .setNumPartitions(topicMetadata.numPartitions())
+                .setPartitionMetadata(partitionMetadata)
+            );
+        });
+
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupPartitionMetadataKey()
+                    .setGroupId(groupId),
+                (short) 13
+            ),
+            new ApiMessageAndVersion(
+                value,
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupPartitionMetadata tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupPartitionMetadataTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupPartitionMetadataKey()
+                    .setGroupId(groupId),
+                (short) 13
+            ),
+            null // Tombstone.
+        );
+    }
+
+    public static CoordinatorRecord newStreamsGroupEpochRecord(
+        String groupId,
+        int newGroupEpoch
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataKey()
+                    .setGroupId(groupId),
+                (short) 12
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataValue()
+                    .setEpoch(newGroupEpoch),
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupMetadata tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupEpochTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataKey()
+                    .setGroupId(groupId),
+                (short) 12
+            ),
+            null // Tombstone.
+        );
+    }
+
+    public static CoordinatorRecord newStreamsTargetAssignmentRecord(
+        String groupId,
+        String memberId,
+        Map<String, Set<Integer>> activeTasks,
+        Map<String, Set<Integer>> standbyTasks,
+        Map<String, Set<Integer>> warmupTasks
+    ) {
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> activeTaskIds = new ArrayList<>(activeTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : activeTasks.entrySet()) {
+            activeTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> standbyTaskIds = new ArrayList<>(standbyTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : standbyTasks.entrySet()) {
+            standbyTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> warmupTaskIds = new ArrayList<>(warmupTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : warmupTasks.entrySet()) {
+            warmupTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMemberKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 16
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMemberValue()
+                    .setActiveTasks(activeTaskIds)
+                    .setStandbyTasks(standbyTaskIds)
+                    .setWarmupTasks(warmupTaskIds),
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupTargetAssignmentMember tombstone.
+     *
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsTargetAssignmentTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMemberKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 16
+            ),
+            null // Tombstone.
+        );
+    }
+
+
+    public static CoordinatorRecord newStreamsTargetAssignmentEpochRecord(
+        String groupId,
+        int assignmentEpoch
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMetadataKey()
+                    .setGroupId(groupId),
+                (short) 15
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMetadataValue()
+                    .setAssignmentEpoch(assignmentEpoch),
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupTargetAssignmentMetadata tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsTargetAssignmentEpochTombstoneRecord(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMetadataKey()
+                    .setGroupId(groupId),
+                (short) 15
+            ),
+            null // Tombstone.
+        );
+    }
+
+    public static CoordinatorRecord newStreamsCurrentAssignmentRecord(
+        String groupId,
+        StreamsGroupMember member
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentKey()
+                    .setGroupId(groupId)
+                    .setMemberId(member.memberId()),
+                (short) 17
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentValue()
+                    .setMemberEpoch(member.memberEpoch())
+                    .setPreviousMemberEpoch(member.previousMemberEpoch())
+                    .setState(member.state().value())
+                    .setActiveTasks(toTaskIds(member.assignedActiveTasks()))
+                    .setStandbyTasks(toTaskIds(member.assignedStandbyTasks()))
+                    .setWarmupTasks(toTaskIds(member.assignedWarmupTasks()))
+                    .setActiveTasksPendingRevocation(toTaskIds(member.activeTasksPendingRevocation())),
+                (short) 0
+            )
+        );
+    }
+
+    /**
+     * Creates a StreamsGroupCurrentMemberAssignment tombstone.
+     *
+     * @param groupId  The streams group id.
+     * @param memberId The streams group member id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsCurrentAssignmentTombstoneRecord(
+        String groupId,
+        String memberId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 17
+            ),
+            null // Tombstone
+        );
+    }
+
+    private static List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> toTaskIds(
+        Map<String, Set<Integer>> tasks
+    ) {
+        List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> taskIds = new ArrayList<>(tasks.size());
+        tasks.forEach((subtopologyId, partitions) ->
+            taskIds.add(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId)
+                .setPartitions(new ArrayList<>(partitions)))
+        );
+        return taskIds;
+    }
+
+    /**
+     * Creates a StreamsTopology record.
+     *
+     * @param groupId       The consumer group id.
+     * @param subtopologies The subtopologies in the new topology.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
+                                                                  List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
+        StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
+        subtopologies.forEach(subtopology -> {
+            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
+                .map(topicInfo -> {
+                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                        .collect(Collectors.toList()) : null;
+                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
+                        .setPartitions(topicInfo.partitions());
+                }).collect(Collectors.toList());
+
+            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
+                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                    .collect(Collectors.toList()) : null;
+                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
+            }).collect(Collectors.toList());
+
+            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopology())
+                .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
+                .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
+        });
+
+        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 18),
+            new ApiMessageAndVersion(value, (short) 0));
+    }
+
+    /**
+     * Creates a StreamsGroupTopology tombstone.
+     *
+     * @param groupId The streams group id.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupTopologyRecordTombstone(
+        String groupId
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyKey()
+                    .setGroupId(groupId),
+                (short) 18
+            ),
+            null // Tombstone
+        );
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index 8f0819eae45..19eb79e36e6 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -17,7 +17,7 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.errors.FencedMemberEpochException;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 
 import java.util.Collections;
 import java.util.HashMap;
@@ -47,7 +47,7 @@ public class CurrentAssignmentBuilder {
     /**
      * The target assignment.
      */
-    private org.apache.kafka.coordinator.group.streams.Assignment targetAssignment;
+    private Assignment targetAssignment;
 
     /**
      * A function which returns the current epoch of a topic-partition or -1 if the topic-partition is not assigned. The current epoch is
@@ -58,17 +58,17 @@ public class CurrentAssignmentBuilder {
     /**
      * The active tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
      */
-    private List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks;
+    private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks;
 
     /**
      * The standby tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
      */
-    private List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks;
+    private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks;
 
     /**
      * The warmup tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
      */
-    private List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks;
+    private List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks;
 
     /**
      * Constructs the CurrentAssignmentBuilder based on the current state of the provided streams group member.
@@ -117,7 +117,7 @@ public class CurrentAssignmentBuilder {
      * @return This object.
      */
     public CurrentAssignmentBuilder withOwnedActiveTasks(
-        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedActiveTasks
     ) {
         this.ownedActiveTasks = ownedActiveTasks;
         return this;
@@ -131,7 +131,7 @@ public class CurrentAssignmentBuilder {
      * @return This object.
      */
     public CurrentAssignmentBuilder withOwnedStandbyTasks(
-        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedStandbyTasks
     ) {
         this.ownedStandbyTasks = ownedStandbyTasks;
         return this;
@@ -145,7 +145,7 @@ public class CurrentAssignmentBuilder {
      * @return This object.
      */
     public CurrentAssignmentBuilder withOwnedWarmupTasks(
-        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks
+        List<StreamsGroupHeartbeatRequestData.TaskIds> ownedWarmupTasks
     ) {
         this.ownedWarmupTasks = ownedWarmupTasks;
         return this;
@@ -241,7 +241,7 @@ public class CurrentAssignmentBuilder {
             return true;
         }
 
-        for (StreamsHeartbeatRequestData.TaskIds activeTasks : ownedActiveTasks) {
+        for (StreamsGroupHeartbeatRequestData.TaskIds activeTasks : ownedActiveTasks) {
             Set<Integer> tasksPendingRevocation =
                 assignment.getOrDefault(activeTasks.subtopology(), Collections.emptySet());
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
index f9ccb8f2ebc..71914da48b2 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
@@ -46,7 +46,7 @@ public enum MemberState {
      */
     UNKNOWN((byte) 127);
 
-    private final static Map<Byte, MemberState> VALUES_TO_ENUMS = new HashMap<>();
+    private static final Map<Byte, MemberState> VALUES_TO_ENUMS = new HashMap<>();
 
     static {
         for (MemberState state : MemberState.values()) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 7d3465c7ad2..09dcf7817a5 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -25,7 +25,6 @@ import org.apache.kafka.common.errors.UnknownMemberIdException;
 import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.coordinator.group.CoordinatorRecord;
-import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
@@ -883,21 +882,21 @@ public class StreamsGroup implements Group {
     @Override
     public void createGroupTombstoneRecords(List<CoordinatorRecord> records) {
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord(groupId(), memberId))
         );
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentTombstoneRecord(groupId(), memberId))
         );
-        records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochTombstoneRecord(groupId()));
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newStreamsGroupMemberTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberTombstoneRecord(groupId(), memberId))
         );
 
-        records.add(CoordinatorRecordHelpers.newStreamsGroupPartitionMetadataTombstoneRecord(groupId()));
-        records.add(CoordinatorRecordHelpers.newStreamsGroupEpochTombstoneRecord(groupId()));
-        records.add(CoordinatorRecordHelpers.newStreamsGroupTopologyRecordTombstone(groupId()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataTombstoneRecord(groupId()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecordTombstone(groupId()));
     }
 
     @Override
@@ -1124,13 +1123,13 @@ public class StreamsGroup implements Group {
         List<CoordinatorRecord> records
     ) {
         members().forEach((__, streamsGroupMember) ->
-            records.add(CoordinatorRecordHelpers.newStreamsGroupMemberRecord(groupId(), streamsGroupMember))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId(), streamsGroupMember))
         );
 
-        records.add(CoordinatorRecordHelpers.newStreamsGroupEpochRecord(groupId(), groupEpoch()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId(), groupEpoch()));
 
         members().forEach((streamsGroupMemberId, streamsGroupMember) ->
-            records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
                 groupId(),
                 streamsGroupMemberId,
                 targetAssignment(streamsGroupMemberId).activeTasks(),
@@ -1139,11 +1138,11 @@ public class StreamsGroup implements Group {
             ))
         );
 
-        records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
-        records.add(CoordinatorRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), subscriptionMetadata()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), subscriptionMetadata()));
 
         members().forEach((__, streamsGroupMember) ->
-            records.add(CoordinatorRecordHelpers.newStreamsCurrentAssignmentRecord(groupId(), streamsGroupMember))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(groupId(), streamsGroupMember))
         );
     }
 
@@ -1189,7 +1188,7 @@ public class StreamsGroup implements Group {
     }
 
     public void setTopology(final StreamsGroupTopologyValue topology) {
-        this.topology.set(Optional.of(new StreamsTopology(topology.topologyHash(), topology.topology().stream().collect(Collectors.toMap(
+        this.topology.set(Optional.of(new StreamsTopology(topology.topologyId(), topology.topology().stream().collect(Collectors.toMap(
             Subtopology::subtopology, x -> x)))));
     }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index 77e038e1a3c..5ad4370a5ab 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -24,7 +24,6 @@ import org.apache.kafka.image.TopicImage;
 import org.apache.kafka.image.TopicsImage;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
@@ -57,13 +56,11 @@ public class StreamsGroupMember {
         private int rebalanceTimeoutMs = -1;
         private String clientId = "";
         private String clientHost = "";
-        private byte[] topologyHash;
+        private String topologyId;
         private String assignor;
         private String processId;
-        private StreamsGroupMemberMetadataValue.HostInfo hostInfo;
+        private StreamsGroupMemberMetadataValue.Endpoint userEndpoint;
         private Map<String, String> clientTags;
-        private byte[] userData;
-        private Map<String, String> assignmentConfigs;
         private Map<String, Set<Integer>> assignedActiveTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedStandbyTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedWarmupTasks = Collections.emptyMap();
@@ -84,13 +81,11 @@ public class StreamsGroupMember {
             this.rebalanceTimeoutMs = member.rebalanceTimeoutMs;
             this.clientId = member.clientId;
             this.clientHost = member.clientHost;
-            this.topologyHash = member.topologyHash;
+            this.topologyId = member.topologyId;
             this.assignor = member.assignor;
             this.processId = member.processId;
-            this.hostInfo = member.hostInfo;
+            this.userEndpoint = member.userEndpoint;
             this.clientTags = member.clientTags;
-            this.userData = member.userData;
-            this.assignmentConfigs = member.assignmentConfigs;
             this.state = member.state;
             this.assignedActiveTasks = member.assignedActiveTasks;
             this.assignedStandbyTasks = member.assignedStandbyTasks;
@@ -165,13 +160,13 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setTopologyHash(byte[] topologyHash) {
-            this.topologyHash = topologyHash;
+        public Builder setTopologyId(String topologyId) {
+            this.topologyId = topologyId;
             return this;
         }
 
-        public Builder maybeUpdateTopologyHash(Optional<byte[]> topologyHash) {
-            this.topologyHash = topologyHash.orElse(this.topologyHash);
+        public Builder maybeUpdateTopologyId(Optional<String> topologyId) {
+            this.topologyId = topologyId.orElse(this.topologyId);
             return this;
         }
 
@@ -190,13 +185,13 @@ public class StreamsGroupMember {
             return this;
         }
         
-        public Builder setHostInfo(StreamsGroupMemberMetadataValue.HostInfo hostInfo) {
-            this.hostInfo = hostInfo;
+        public Builder setUserEndpoint(StreamsGroupMemberMetadataValue.Endpoint userEndpoint) {
+            this.userEndpoint = userEndpoint;
             return this;
         }
 
-        public Builder maybeUpdateHostInfo(Optional<StreamsGroupMemberMetadataValue.HostInfo> hostInfo) {
-            this.hostInfo = hostInfo.orElse(this.hostInfo);
+        public Builder maybeUpdateUserEndpoint(Optional<StreamsGroupMemberMetadataValue.Endpoint> userEndpoint) {
+            this.userEndpoint = userEndpoint.orElse(this.userEndpoint);
             return this;
         }
 
@@ -210,26 +205,6 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setUserData(byte[] userData) {
-            this.userData = userData;
-            return this;
-        }
-
-        public Builder maybeUpdateUserData(Optional<byte[]> userData) {
-            this.userData = userData.orElse(this.userData);
-            return this;
-        }
-
-        public Builder setAssignmentConfigs(Map<String, String> assignmentConfigs) {
-            this.assignmentConfigs = assignmentConfigs;
-            return this;
-        }
-
-        public Builder maybeUpdateAssignmentConfigs(Optional<Map<String, String>> assignmentConfigs) {
-            this.assignmentConfigs = assignmentConfigs.orElse(this.assignmentConfigs);
-            return this;
-        }
-
         public Builder setAssignedActiveTasks(Map<String, Set<Integer>> assignedActiveTasks) {
             this.assignedActiveTasks = assignedActiveTasks;
             return this;
@@ -256,19 +231,13 @@ public class StreamsGroupMember {
             setClientId(record.clientId());
             setClientHost(record.clientHost());
             setRebalanceTimeoutMs(record.rebalanceTimeoutMs());
-            setTopologyHash(record.topologyHash());
-            setAssignor(record.assignor());
+            setTopologyId(record.topologyId());
             setProcessId(record.processId());
-            setHostInfo(record.hostInfo());
+            setUserEndpoint(record.userEndpoint());
             setClientTags(record.clientTags().stream().collect(Collectors.toMap(
                 StreamsGroupMemberMetadataValue.KeyValue::key,
                 StreamsGroupMemberMetadataValue.KeyValue::value
             )));
-            setUserData(record.userData());
-            setAssignmentConfigs(record.assignmentConfigs().stream().collect(Collectors.toMap(
-                StreamsGroupMemberMetadataValue.KeyValue::key,
-                StreamsGroupMemberMetadataValue.KeyValue::value
-            )));
             return this;
         }
 
@@ -301,13 +270,11 @@ public class StreamsGroupMember {
                 rebalanceTimeoutMs,
                 clientId,
                 clientHost,
-                topologyHash,
+                topologyId,
                 assignor,
                 processId,
-                hostInfo,
+                userEndpoint,
                 clientTags,
-                userData,
-                assignmentConfigs,
                 state,
                 assignedActiveTasks,
                 assignedStandbyTasks,
@@ -363,9 +330,9 @@ public class StreamsGroupMember {
     private final String clientHost;
 
     /**
-     * The topology hash
+     * The topology ID
      */
-    private final byte[] topologyHash;
+    private final String topologyId;
 
     /**
      * The assignor
@@ -378,25 +345,15 @@ public class StreamsGroupMember {
     private final String processId;
 
     /**
-     * The host info
+     * The endpoint
      */
-    private final StreamsGroupMemberMetadataValue.HostInfo hostInfo;
+    private final StreamsGroupMemberMetadataValue.Endpoint userEndpoint;
 
     /**
      * The client tags
      */
     private final Map<String, String> clientTags;
 
-    /**
-     * The user data
-     */
-    private final byte[] userData;
-
-    /**
-     * The assignment configs
-     */
-    private final Map<String, String> assignmentConfigs;
-
     /**
      * Active tasks assigned to this member.
      */
@@ -427,13 +384,11 @@ public class StreamsGroupMember {
         int rebalanceTimeoutMs,
         String clientId,
         String clientHost,
-        byte[] topologyHash,
+        String topologyId,
         String assignor,
         String processId,
-        StreamsGroupMemberMetadataValue.HostInfo hostInfo,
+        StreamsGroupMemberMetadataValue.Endpoint userEndpoint,
         Map<String, String> clientTags,
-        byte[] userData,
-        Map<String, String> assignmentConfigs,
         MemberState state,
         Map<String, Set<Integer>> assignedActiveTasks,
         Map<String, Set<Integer>> assignedStandbyTasks,
@@ -449,13 +404,11 @@ public class StreamsGroupMember {
         this.rebalanceTimeoutMs = rebalanceTimeoutMs;
         this.clientId = clientId;
         this.clientHost = clientHost;
-        this.topologyHash = topologyHash;
+        this.topologyId = topologyId;
         this.assignor = assignor;
         this.processId = processId;
-        this.hostInfo = hostInfo;
+        this.userEndpoint = userEndpoint;
         this.clientTags = clientTags;
-        this.userData = userData;
-        this.assignmentConfigs = assignmentConfigs;
         this.assignedActiveTasks = assignedActiveTasks;
         this.assignedStandbyTasks = assignedStandbyTasks;
         this.assignedWarmupTasks = assignedWarmupTasks;
@@ -519,10 +472,10 @@ public class StreamsGroupMember {
     }
 
     /**
-     * @return The process ID
+     * @return The topology ID
      */
-    public byte[] topologyHash() {
-        return topologyHash;
+    public String topologyId() {
+        return topologyId;
     }
 
     /**
@@ -540,10 +493,10 @@ public class StreamsGroupMember {
     }
 
     /**
-     * @return The host info
+     * @return The user endpoint
      */
-    public StreamsGroupMemberMetadataValue.HostInfo hostInfo() {
-        return hostInfo;
+    public StreamsGroupMemberMetadataValue.Endpoint userEndpoint() {
+        return userEndpoint;
     }
 
     /**
@@ -553,17 +506,6 @@ public class StreamsGroupMember {
         return clientTags;
     }
 
-    public byte[] userData() {
-        return userData;
-    }
-
-    /**
-     * @return The assignment configs
-     */
-    public Map<String, String> assignmentConfigs() {
-        return assignmentConfigs;
-    }
-
     /**
      * @return The current state.
      */
@@ -654,13 +596,11 @@ public class StreamsGroupMember {
             && Objects.equals(rackId, that.rackId)
             && Objects.equals(clientId, that.clientId)
             && Objects.equals(clientHost, that.clientHost)
-            && Objects.deepEquals(topologyHash, that.topologyHash)
+            && Objects.deepEquals(topologyId, that.topologyId)
             && Objects.equals(assignor, that.assignor)
             && Objects.equals(processId, that.processId)
-            && Objects.equals(hostInfo, that.hostInfo)
+            && Objects.equals(userEndpoint, that.userEndpoint)
             && Objects.equals(clientTags, that.clientTags)
-            && Objects.deepEquals(userData, that.userData)
-            && Objects.equals(assignmentConfigs, that.assignmentConfigs)
             && Objects.equals(assignedActiveTasks, that.assignedActiveTasks)
             && Objects.equals(assignedStandbyTasks, that.assignedStandbyTasks)
             && Objects.equals(assignedWarmupTasks, that.assignedWarmupTasks)
@@ -678,13 +618,11 @@ public class StreamsGroupMember {
         result = 31 * result + rebalanceTimeoutMs;
         result = 31 * result + Objects.hashCode(clientId);
         result = 31 * result + Objects.hashCode(clientHost);
-        result = 31 * result + Arrays.hashCode(topologyHash);
+        result = 31 * result + Objects.hashCode(topologyId);
         result = 31 * result + Objects.hashCode(assignor);
         result = 31 * result + Objects.hashCode(processId);
-        result = 31 * result + Objects.hashCode(hostInfo);
+        result = 31 * result + Objects.hashCode(userEndpoint);
         result = 31 * result + Objects.hashCode(clientTags);
-        result = 31 * result + Arrays.hashCode(userData);
-        result = 31 * result + Objects.hashCode(assignmentConfigs);
         result = 31 * result + Objects.hashCode(assignedActiveTasks);
         result = 31 * result + Objects.hashCode(assignedStandbyTasks);
         result = 31 * result + Objects.hashCode(assignedWarmupTasks);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 9dd960b6aba..e0bec1c292a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -20,7 +20,6 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
 
-import java.util.Arrays;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
@@ -32,17 +31,17 @@ import java.util.stream.Stream;
  */
 public class StreamsTopology {
 
-    private final byte[] topologyHash;
+    private final String topologyId;
 
     private final Map<String, Subtopology> subtopologies;
 
-    public StreamsTopology(final byte[] topologyHash, final Map<String, Subtopology> subtopologies) {
-        this.topologyHash = topologyHash;
+    public StreamsTopology(final String topologyId, final Map<String, Subtopology> subtopologies) {
+        this.topologyId = topologyId;
         this.subtopologies = subtopologies;
     }
 
-    public byte[] topologyHash() {
-        return topologyHash;
+    public String topologyId() {
+        return topologyId;
     }
 
     public Map<String, Subtopology> subtopologies() {
@@ -60,7 +59,7 @@ public class StreamsTopology {
         StreamsGroupTopologyValue record
     ) {
         return new StreamsTopology(
-            record.topologyHash(),
+            record.topologyId(),
             record.topology().stream().collect(Collectors.toMap(Subtopology::subtopology, x -> x))
         );
     }
@@ -74,18 +73,18 @@ public class StreamsTopology {
             return false;
         }
         final StreamsTopology that = (StreamsTopology) o;
-        return Objects.deepEquals(topologyHash, that.topologyHash) && Objects.equals(subtopologies, that.subtopologies);
+        return Objects.deepEquals(topologyId, that.topologyId) && Objects.equals(subtopologies, that.subtopologies);
     }
 
     @Override
     public int hashCode() {
-        return Objects.hash(Arrays.hashCode(topologyHash), subtopologies);
+        return Objects.hash(topologyId, subtopologies);
     }
 
     @Override
     public String toString() {
         return "StreamsTopology{" +
-            "topologyHash=" + Arrays.toString(topologyHash) +
+            "topologyId=" + topologyId +
             ", subtopologies=" + subtopologies +
             '}';
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index b60967dc1f4..1fd34e27e89 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -17,7 +17,6 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.coordinator.group.CoordinatorRecord;
-import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
 import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
 import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
 import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
@@ -35,8 +34,6 @@ import java.util.Objects;
 import java.util.Optional;
 import java.util.stream.Collectors;
 
-import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord;
-
 /**
  * Build a new Target Assignment based on the provided parameters. As a result, it yields the records that must be persisted to the log and
  * the new member assignments as a map.
@@ -327,7 +324,7 @@ public class TargetAssignmentBuilder {
 
             if (oldMemberAssignment == null) {
                 // If the member had no assignment, we always create a record for it.
-                records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
+                records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
                     groupId,
                     memberId,
                     newMemberAssignment.activeTasks(),
@@ -338,7 +335,7 @@ public class TargetAssignmentBuilder {
                 // If the member had an assignment, we only create a record if the
                 // new assignment is different.
                 if (!newMemberAssignment.equals(oldMemberAssignment)) {
-                    records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord(
+                    records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
                         groupId,
                         memberId,
                         newMemberAssignment.activeTasks(),
@@ -350,7 +347,7 @@ public class TargetAssignmentBuilder {
         });
 
         // Bump the target assignment epoch.
-        records.add(newStreamsTargetAssignmentEpochRecord(groupId, groupEpoch));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId, groupEpoch));
 
         return new TargetAssignmentResult(records, newTargetAssignment);
     }
@@ -383,7 +380,6 @@ public class TargetAssignmentBuilder {
             targetAssignment.warmupTasks(),
             member.processId(),
             member.clientTags(),
-            member.assignmentConfigs(),
             Collections.emptyMap() // TODO: TaskOffsets is missing
         );
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java
index 64ab7ece4e9..46bdcfff049 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java
@@ -62,11 +62,6 @@ public class AssignmentMemberSpec {
      */
     private final Map<String, String> clientTags;
 
-    /**
-     * The assignment configs for customizing the assignment.
-     */
-    private final Map<String, String> assignmentConfigs;
-
     /**
      * The last received cumulative task offsets of assigned tasks or dormant tasks.
      */
@@ -115,10 +110,6 @@ public class AssignmentMemberSpec {
         return clientTags;
     }
 
-    public Map<String, String> assignmentConfigs() {
-        return assignmentConfigs;
-    }
-
     public String processId() {
         return processId;
     }
@@ -130,7 +121,6 @@ public class AssignmentMemberSpec {
                                 final Map<String, Set<Integer>> warmupTasks,
                                 final String processId,
                                 final Map<String, String> clientTags,
-                                final Map<String, String> assignmentConfigs,
                                 final Map<TaskId, Long> taskOffsets) {
         this.instanceId = Objects.requireNonNull(instanceId);
         this.rackId = Objects.requireNonNull(rackId);
@@ -139,7 +129,6 @@ public class AssignmentMemberSpec {
         this.warmupTasks = Collections.unmodifiableMap(Objects.requireNonNull(warmupTasks));
         this.processId = Objects.requireNonNull(processId);
         this.clientTags = Collections.unmodifiableMap(Objects.requireNonNull(clientTags));
-        this.assignmentConfigs = Collections.unmodifiableMap(Objects.requireNonNull(assignmentConfigs));
         this.taskOffsets = Collections.unmodifiableMap(Objects.requireNonNull(taskOffsets));
     }
 
@@ -159,7 +148,6 @@ public class AssignmentMemberSpec {
             && Objects.equals(warmupTasks, that.warmupTasks)
             && Objects.equals(processId, that.processId)
             && Objects.equals(clientTags, that.clientTags)
-            && Objects.equals(assignmentConfigs, that.assignmentConfigs)
             && Objects.equals(taskOffsets, that.taskOffsets);
     }
 
@@ -173,7 +161,6 @@ public class AssignmentMemberSpec {
             warmupTasks,
             processId,
             clientTags,
-            assignmentConfigs,
             taskOffsets
         );
     }
@@ -188,7 +175,6 @@ public class AssignmentMemberSpec {
             ", warmupTasks=" + warmupTasks +
             ", processId='" + processId + '\'' +
             ", clientTags=" + clientTags +
-            ", assignmentConfigs=" + assignmentConfigs +
             ", taskOffsets=" + taskOffsets +
             '}';
     }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
index aaaccf7d865..b1a8ea68aab 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -31,7 +31,7 @@
     { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned standby tasks for this streams client." },
     { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
-      "about": "Currently assigned warming up tasks for this streams client." },
+      "about": "Currently assigned warm-up tasks for this streams client." },
     { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskIds",
       "about": "The active tasks that must be revoked by this member." }
   ],
@@ -43,4 +43,4 @@
         "about": "The partitions of the input topics processed by this member." }
     ]}
   ]
-}
+}
\ No newline at end of file
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json
index eab6f18310e..2623748d0d4 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json
@@ -31,32 +31,23 @@
     { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
       "about": "The rebalance timeout." },
 
-    { "name": "TopologyHash", "type": "bytes", "versions": "0+",
-      "about": "The hash of the topology. " },
-    { "name": "Assignor", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
-      "about": "The desired assignor. If set to null, the vote goes towards the broker taking a pick." },
+    { "name": "TopologyId", "type": "string", "versions": "0+",
+      "about": "The ID of the topology. Must be non-empty." },
 
     { "name": "ProcessId", "type": "string", "versions": "0+",
       "about": "Identity of the streams instance that may have multiple consumers." },
-    { "name": "HostInfo", "type": "HostInfo", "versions": "0+",
-      "about": "Host information for running interactive queries on this instance.",
-      "fields": [
-        { "name": "Host", "type": "string", "versions": "0+",
-          "about": "Host for running interactive queries on this instance." },
-        { "name": "Port", "type": "int32", "versions": "0+",
-          "about": "Port for running interactive queries on this instance." }
-      ]
-    },
-    // TODO: maybe it would be nice to just stuff this info into "AssignmentConfigs", since it's quite specific
+    { "name": "UserEndpoint", "type": "Endpoint", "nullableVersions": "0+", "versions": "0+",
+      "about": "User-defined endpoint for running interactive queries on this instance." },
     { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
-      "about": "Used for rack-aware assignment algorithm." },
-
-    { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Opaque user data to be passed to the client-side assignor. Null for server-side assignors." },
-    { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+",
-      "about": "Generic array of assignment configuration strings." }
+      "about": "Used for rack-aware assignment algorithm." }
   ],
   "commonStructs": [
+    { "name": "Endpoint", "versions": "0+", "fields": [
+      { "name": "Host", "type": "string", "versions": "0+",
+        "about": "host of the endpoint" },
+      { "name": "Port", "type": "uint16", "versions": "0+",
+        "about": "port of the endpoint" }
+    ]},
     { "name": "KeyValue", "versions": "0+",
       "fields": [
         { "name": "Key", "type": "string", "versions": "0+",
@@ -66,4 +57,4 @@
       ]
     }
   ]
-}
+}
\ No newline at end of file
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
index 06cb84ab18b..f33e0ace34c 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
@@ -25,7 +25,7 @@
     { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned standby tasks for this streams client." },
     { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
-      "about": "Currently assigned warming up tasks for this streams client." }
+      "about": "Currently assigned warm-up tasks for this streams client." }
   ],
   "commonStructs": [
     { "name": "TaskIds", "versions": "0+", "fields": [
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
index 2fb5608861b..5ba633095b6 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
@@ -20,8 +20,8 @@
   "validVersions": "0",
   "flexibleVersions": "0+",
   "fields": [
-    { "name": "TopologyHash", "type": "bytes", "versions": "0+",
-      "about": "The hash of the topology. " },
+    { "name": "TopologyId", "type": "string", "versions": "0+",
+      "about": "The ID of the topology. Must be non-empty. " },
     { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
       "about": "The sub-topologies of the streams application.",
       "fields": [
@@ -29,12 +29,12 @@
           "about": "String to uniquely identify the subtopology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
-        { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
-          "about": "The regular expressions identifying topics the topology reads from." },
-        { "name": "SinkTopics", "type": "[]string", "versions": "0+",
-          "about": "The topics the topology writes to." },
+        { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+          "about": "The regular expressions identifying topics the topology reads from. null if not provided." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of state changelog topics associated with this subtopology. " },
+        { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
+          "about": "The repartition topics the sub-topology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of source topics that are internally created repartition topics. " }
       ]
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
index d6258e13db0..812ee093c2c 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
@@ -19,7 +19,6 @@ package org.apache.kafka.coordinator.group;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol;
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocolCollection;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
@@ -46,8 +45,6 @@ import org.apache.kafka.coordinator.group.generated.GroupMetadataValue;
 import org.apache.kafka.coordinator.group.generated.OffsetCommitKey;
 import org.apache.kafka.coordinator.group.generated.OffsetCommitValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.modern.MemberState;
 import org.apache.kafka.coordinator.group.modern.TopicMetadata;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
@@ -92,7 +89,6 @@ import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.n
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupEpochTombstoneRecord;
-import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupTopologyRecord;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
@@ -218,84 +214,6 @@ public class GroupCoordinatorRecordHelpersTest {
         ));
     }
 
-    @Test
-    public void testNewStreamsGroupTopologyRecord() {
-        List<StreamsInitializeRequestData.Subtopology> topology =
-            Collections.singletonList(new StreamsInitializeRequestData.Subtopology()
-                .setSubtopology("subtopology-id")
-                .setSinkTopics(Collections.singletonList("foo"))
-                .setSourceTopics(Collections.singletonList("bar"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(
-                        new StreamsInitializeRequestData.TopicInfo()
-                            .setName("repartition")
-                            .setPartitions(4)
-                            .setTopicConfigs(Collections.singletonList(
-                                new StreamsInitializeRequestData.TopicConfig()
-                                    .setKey("config-name1")
-                                    .setValue("config-value1")
-                            ))
-                    )
-                )
-                .setStateChangelogTopics(
-                    Collections.singletonList(
-                        new StreamsInitializeRequestData.TopicInfo()
-                            .setName("changelog")
-                            .setTopicConfigs(Collections.singletonList(
-                                new StreamsInitializeRequestData.TopicConfig()
-                                    .setKey("config-name2")
-                                    .setValue("config-value2")
-                            ))
-                    )
-                )
-            );
-
-        List<StreamsGroupTopologyValue.Subtopology> expectedTopology =
-            Collections.singletonList(new StreamsGroupTopologyValue.Subtopology()
-                .setSubtopology("subtopology-id")
-                .setSinkTopics(Collections.singletonList("foo"))
-                .setSourceTopics(Collections.singletonList("bar"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(
-                        new StreamsGroupTopologyValue.TopicInfo()
-                            .setName("repartition")
-                            .setPartitions(4)
-                            .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupTopologyValue.TopicConfig()
-                                    .setKey("config-name1")
-                                    .setValue("config-value1")
-                            ))
-                    )
-                )
-                .setStateChangelogTopics(
-                    Collections.singletonList(
-                        new StreamsGroupTopologyValue.TopicInfo()
-                            .setName("changelog")
-                            .setTopicConfigs(Collections.singletonList(
-                                new StreamsGroupTopologyValue.TopicConfig()
-                                    .setKey("config-name2")
-                                    .setValue("config-value2")
-                            ))
-                    )
-                )
-            );
-
-        CoordinatorRecord expectedRecord = new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new StreamsGroupTopologyKey()
-                    .setGroupId("group-id"),
-                (short) 18),
-            new ApiMessageAndVersion(
-                new StreamsGroupTopologyValue()
-                    .setTopology(expectedTopology),
-                (short) 0));
-
-        assertEquals(expectedRecord, newStreamsGroupTopologyRecord(
-            "group-id",
-            topology
-        ));
-    }
-
     @Test
     public void testEmptyPartitionMetadataWhenRacksUnavailableGroupSubscriptionMetadataRecord() {
         Uuid fooTopicId = Uuid.randomUuid();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index fa19409b208..fcdd221c907 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -54,10 +54,10 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -275,16 +275,16 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
-            requestContext(ApiKeys.STREAMS_INITIALIZE),
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
 
         assertEquals(
-            new StreamsInitializeResponseData()
+            new StreamsGroupInitializeResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
             future.get()
         );
@@ -300,7 +300,7 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
             .setGroupId("foo");
 
         service.startup(() -> 1);
@@ -311,15 +311,15 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.eq(Duration.ofMillis(5000)),
             ArgumentMatchers.any()
         )).thenReturn(CompletableFuture.completedFuture(
-            new StreamsInitializeResponseData()
+            new StreamsGroupInitializeResponseData()
         ));
 
-        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
-            requestContext(ApiKeys.STREAMS_INITIALIZE),
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
 
-        assertEquals(new StreamsInitializeResponseData(), future.get(5, TimeUnit.SECONDS));
+        assertEquals(new StreamsGroupInitializeResponseData(), future.get(5, TimeUnit.SECONDS));
     }
 
     private static Stream<Arguments> testStreamsInitializeWithExceptionSource() {
@@ -352,7 +352,7 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
             .setGroupId("foo");
 
         service.startup(() -> 1);
@@ -364,13 +364,13 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
-            requestContext(ApiKeys.STREAMS_INITIALIZE),
+        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
 
         assertEquals(
-            new StreamsInitializeResponseData()
+            new StreamsGroupInitializeResponseData()
                 .setErrorCode(expectedErrorCode)
                 .setErrorMessage(expectedErrorMessage),
             future.get(5, TimeUnit.SECONDS)
@@ -387,16 +387,16 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+        StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
-            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
         assertEquals(
-            new StreamsHeartbeatResponseData()
+            new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
             future.get()
         );
@@ -412,7 +412,7 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+        StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
             .setGroupId("foo");
 
         service.startup(() -> 1);
@@ -423,15 +423,15 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.eq(Duration.ofMillis(5000)),
             ArgumentMatchers.any()
         )).thenReturn(CompletableFuture.completedFuture(
-            new StreamsHeartbeatResponseData()
+            new StreamsGroupHeartbeatResponseData()
         ));
 
-        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
-            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
-        assertEquals(new StreamsHeartbeatResponseData(), future.get(5, TimeUnit.SECONDS));
+        assertEquals(new StreamsGroupHeartbeatResponseData(), future.get(5, TimeUnit.SECONDS));
     }
 
     private static Stream<Arguments> testStreamsHeartbeatWithExceptionSource() {
@@ -463,7 +463,7 @@ public class GroupCoordinatorServiceTest {
             new GroupCoordinatorMetrics()
         );
 
-        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+        StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
             .setGroupId("foo");
 
         service.startup(() -> 1);
@@ -475,13 +475,13 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
-            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+        CompletableFuture<StreamsGroupHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT),
             request
         );
 
         assertEquals(
-            new StreamsHeartbeatResponseData()
+            new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(expectedErrorCode)
                 .setErrorMessage(expectedErrorMessage),
             future.get(5, TimeUnit.SECONDS)
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index da7fcc52de5..2adadc1be4d 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -24,10 +24,10 @@ import org.apache.kafka.common.message.OffsetCommitRequestData;
 import org.apache.kafka.common.message.OffsetCommitResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
 import org.apache.kafka.common.message.TxnOffsetCommitResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
@@ -152,11 +152,11 @@ public class GroupCoordinatorShardTest {
             metricsShard
         );
 
-        RequestContext context = requestContext(ApiKeys.STREAMS_INITIALIZE);
-        StreamsInitializeRequestData request = new StreamsInitializeRequestData();
-        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+        RequestContext context = requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE);
+        StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData();
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
             Collections.emptyList(),
-            new StreamsInitializeResponseData()
+            new StreamsGroupInitializeResponseData()
         );
 
         when(groupMetadataManager.streamsInitialize(
@@ -184,11 +184,11 @@ public class GroupCoordinatorShardTest {
             metricsShard
         );
 
-        RequestContext context = requestContext(ApiKeys.STREAMS_HEARTBEAT);
-        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData();
-        CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+        RequestContext context = requestContext(ApiKeys.STREAMS_GROUP_HEARTBEAT);
+        StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData();
+        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
             Collections.emptyList(),
-            new StreamsHeartbeatResponseData()
+            new StreamsGroupHeartbeatResponseData()
         );
 
         when(groupMetadataManager.streamsHeartbeat(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index d450cbeecb1..4602593b6e3 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -54,7 +54,7 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -268,25 +268,25 @@ public class GroupMetadataManagerTest {
 
         // GroupId must be present in all requests.
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()));
+            new StreamsGroupHeartbeatRequestData()));
         assertEquals("GroupId can't be empty.", ex.getMessage());
 
         // GroupId can't be all whitespaces.
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("   ")));
         assertEquals("GroupId can't be empty.", ex.getMessage());
 
         // RebalanceTimeoutMs must be present in the first request (epoch == 0).
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)));
         assertEquals("RebalanceTimeoutMs must be provided in first request.", ex.getMessage());
 
         // ActiveTasks must be present and empty in the first request (epoch == 0).
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
                 .setRebalanceTimeoutMs(5000)
@@ -296,7 +296,7 @@ public class GroupMetadataManagerTest {
 
         // StandbyTasks must be present and empty in the first request (epoch == 0).
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
                 .setRebalanceTimeoutMs(5000)
@@ -306,7 +306,7 @@ public class GroupMetadataManagerTest {
 
         // WarmupTasks must be present and empty in the first request (epoch == 0).
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(0)
                 .setRebalanceTimeoutMs(5000)
@@ -317,14 +317,14 @@ public class GroupMetadataManagerTest {
         // MemberId must be non-empty in all requests except for the first one where it
         // could be empty (epoch != 0).
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberEpoch(1)));
         assertEquals("MemberId can't be empty.", ex.getMessage());
 
         // InstanceId must be non-empty if provided in all requests.
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberId(Uuid.randomUuid().toString())
                 .setMemberEpoch(1)
@@ -333,7 +333,7 @@ public class GroupMetadataManagerTest {
 
         // RackId must be non-empty if provided in all requests.
         ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
-            new StreamsHeartbeatRequestData()
+            new StreamsGroupHeartbeatRequestData()
                 .setGroupId("foo")
                 .setMemberId(Uuid.randomUuid().toString())
                 .setMemberEpoch(1)
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 6ad0df3aa4f..7e38f61ffd5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -36,10 +36,10 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.network.ClientInformation;
@@ -683,13 +683,13 @@ public class GroupMetadataManagerTestContext {
     }
 
 
-    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
-        StreamsInitializeRequestData request
+    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsInitialize(
+        StreamsGroupInitializeRequestData request
     ) {
         RequestContext context = new RequestContext(
             new RequestHeader(
-                ApiKeys.STREAMS_INITIALIZE,
-                ApiKeys.STREAMS_INITIALIZE.latestVersion(),
+                ApiKeys.STREAMS_GROUP_INITIALIZE,
+                ApiKeys.STREAMS_GROUP_INITIALIZE.latestVersion(),
                 "client",
                 0
             ),
@@ -702,7 +702,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsInitialize(
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsInitialize(
             context,
             request
         );
@@ -713,13 +713,13 @@ public class GroupMetadataManagerTestContext {
         return result;
     }
 
-    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
-        StreamsHeartbeatRequestData request
+    public CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+        StreamsGroupHeartbeatRequestData request
     ) {
         RequestContext context = new RequestContext(
             new RequestHeader(
-                ApiKeys.STREAMS_HEARTBEAT,
-                ApiKeys.STREAMS_HEARTBEAT.latestVersion(),
+                ApiKeys.STREAMS_GROUP_HEARTBEAT,
+                ApiKeys.STREAMS_GROUP_HEARTBEAT.latestVersion(),
                 "client",
                 0
             ),
@@ -732,7 +732,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsHeartbeat(
+        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsHeartbeat(
             context,
             request
         );
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
new file mode 100644
index 00000000000..44b46421205
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class CoordinatorStreamsRecordHelpersTest {
+
+    @Test
+    public void testNewStreamsGroupTopologyRecord() {
+        List<StreamsGroupInitializeRequestData.Subtopology> topology =
+            Collections.singletonList(new StreamsGroupInitializeRequestData.Subtopology()
+                .setSubtopology("subtopology-id")
+                .setRepartitionSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new StreamsGroupInitializeRequestData.TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new StreamsGroupInitializeRequestData.TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+            );
+
+        List<StreamsGroupTopologyValue.Subtopology> expectedTopology =
+            Collections.singletonList(new StreamsGroupTopologyValue.Subtopology()
+                .setSubtopology("subtopology-id")
+                .setRepartitionSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new StreamsGroupTopologyValue.TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupTopologyValue.TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new StreamsGroupTopologyValue.TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupTopologyValue.TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+            );
+
+        CoordinatorRecord expectedRecord = new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyKey()
+                    .setGroupId("group-id"),
+                (short) 18),
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyValue()
+                    .setTopology(expectedTopology),
+                (short) 0));
+
+        assertEquals(expectedRecord, CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(
+            "group-id",
+            topology
+        ));
+    }
+}
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
index c103f0995b6..3f1bf27b16d 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -18,7 +18,7 @@ package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.FencedMemberEpochException;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
@@ -230,10 +230,10 @@ public class CurrentAssignmentBuilderTest {
                 mkTaskAssignment(subtopologyId2, 5, 6))))
             .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .withOwnedActiveTasks(Arrays.asList(
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
                     .setPartitions(Arrays.asList(2, 3)),
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId2)
                     .setPartitions(Arrays.asList(5, 6))))
             .build();
@@ -286,10 +286,10 @@ public class CurrentAssignmentBuilderTest {
             member,
             currentAssignmentBuilder
                 .withOwnedActiveTasks(Arrays.asList(
-                    new StreamsHeartbeatRequestData.TaskIds()
+                    new StreamsGroupHeartbeatRequestData.TaskIds()
                         .setSubtopology(subtopologyId1)
                         .setPartitions(Arrays.asList(1, 2, 3)),
-                    new StreamsHeartbeatRequestData.TaskIds()
+                    new StreamsGroupHeartbeatRequestData.TaskIds()
                         .setSubtopology(subtopologyId2)
                         .setPartitions(Arrays.asList(5, 6))))
                 .build()
@@ -299,10 +299,10 @@ public class CurrentAssignmentBuilderTest {
             member,
             currentAssignmentBuilder
                 .withOwnedActiveTasks(Arrays.asList(
-                    new StreamsHeartbeatRequestData.TaskIds()
+                    new StreamsGroupHeartbeatRequestData.TaskIds()
                         .setSubtopology(subtopologyId1)
                         .setPartitions(Arrays.asList(2, 3)),
-                    new StreamsHeartbeatRequestData.TaskIds()
+                    new StreamsGroupHeartbeatRequestData.TaskIds()
                         .setSubtopology(subtopologyId2)
                         .setPartitions(Arrays.asList(4, 5, 6))))
                 .build()
@@ -332,10 +332,10 @@ public class CurrentAssignmentBuilderTest {
                 mkTaskAssignment(subtopologyId2, 6))))
             .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .withOwnedActiveTasks(Arrays.asList(
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
                     .setPartitions(Arrays.asList(2, 3)),
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId2)
                     .setPartitions(Arrays.asList(5, 6))))
             .build();
@@ -376,10 +376,10 @@ public class CurrentAssignmentBuilderTest {
                 mkTaskAssignment(subtopologyId2, 5, 6, 7))))
             .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .withOwnedActiveTasks(Arrays.asList(
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
                     .setPartitions(Arrays.asList(2, 3)),
-                new StreamsHeartbeatRequestData.TaskIds()
+                new StreamsGroupHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId2)
                     .setPartitions(Arrays.asList(5, 6))))
             .build();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index 5995381e7b4..f4e4eccdaa0 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -31,7 +31,6 @@ import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
-import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
 
@@ -50,13 +49,11 @@ public class StreamsGroupMemberTest {
             .setRebalanceTimeoutMs(5000)
             .setClientId("client-id")
             .setClientHost("hostname")
-            .setTopologyHash("topology-hash".getBytes())
+            .setTopologyId("topology-hash")
             .setAssignor("assignor")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
             .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
             .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
             .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
@@ -70,19 +67,14 @@ public class StreamsGroupMemberTest {
         assertEquals("rack-id", member.rackId());
         assertEquals("client-id", member.clientId());
         assertEquals("hostname", member.clientHost());
-        assertArrayEquals("topology-hash".getBytes(), member.topologyHash());
+        assertEquals("topology-hash", member.topologyId());
         assertEquals("assignor", member.assignor().get());
         assertEquals("process-id", member.processId());
-        assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
+        assertEquals(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090), member.userEndpoint());
         assertEquals(
             mkMap(mkEntry("client", "tag")),
             member.clientTags()
         );
-        assertArrayEquals("user-data".getBytes(), member.userData());
-        assertEquals(
-            mkMap(mkEntry("assignment", "config")),
-            member.assignmentConfigs()
-        );
         assertEquals(
             mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)),
             member.assignedActiveTasks()
@@ -114,13 +106,11 @@ public class StreamsGroupMemberTest {
             .setRebalanceTimeoutMs(5000)
             .setClientId("client-id")
             .setClientHost("hostname")
-            .setTopologyHash("topology-hash".getBytes())
+            .setTopologyId("topology-hash")
             .setAssignor("assignor")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
             .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
             .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
             .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
@@ -135,13 +125,11 @@ public class StreamsGroupMemberTest {
             .setRebalanceTimeoutMs(5000)
             .setClientId("client-id")
             .setClientHost("hostname")
-            .setTopologyHash("topology-hash".getBytes())
+            .setTopologyId("topology-hash")
             .setAssignor("assignor")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
             .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
             .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
             .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
@@ -156,13 +144,11 @@ public class StreamsGroupMemberTest {
             .setRebalanceTimeoutMs(5000)
             .setClientId("client-id")
             .setClientHost("hostname")
-            .setTopologyHash("topology-hash".getBytes())
+            .setTopologyId("topology-hash")
             .setAssignor("assignor")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
             .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
             .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
             .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
@@ -186,13 +172,11 @@ public class StreamsGroupMemberTest {
             .setRebalanceTimeoutMs(5000)
             .setClientId("client-id")
             .setClientHost("hostname")
-            .setTopologyHash("topology-hash".getBytes())
+            .setTopologyId("topology-hash")
             .setAssignor("assignor")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(mkMap(mkEntry("assignment", "config")))
             .setAssignedActiveTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
             .setAssignedStandbyTasks(mkAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
             .setAssignedWarmupTasks(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
@@ -230,13 +214,10 @@ public class StreamsGroupMemberTest {
             .setInstanceId("instance-id")
             .setRackId("rack-id")
             .setRebalanceTimeoutMs(1000)
-            .setTopologyHash("topology-hash".getBytes())
-            .setAssignor("assignor")
+            .setTopologyId("topology-hash")
             .setProcessId("process-id")
-            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
-            .setClientTags(Collections.singletonList(new KeyValue().setKey("client").setValue("tag")))
-            .setUserData("user-data".getBytes())
-            .setAssignmentConfigs(Collections.singletonList(new KeyValue().setKey("assignment").setValue("config")));
+            .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
+            .setClientTags(Collections.singletonList(new KeyValue().setKey("client").setValue("tag")));
 
         StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
             .updateWith(record)
@@ -247,19 +228,13 @@ public class StreamsGroupMemberTest {
         assertEquals("client-id", member.clientId());
         assertEquals("host-id", member.clientHost());
         assertEquals(1000, member.rebalanceTimeoutMs());
-        assertArrayEquals("topology-hash".getBytes(), member.topologyHash());
-        assertEquals("assignor", member.assignor().get());
+        assertEquals("topology-hash", member.topologyId());
         assertEquals("process-id", member.processId());
-        assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
+        assertEquals(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090), member.userEndpoint());
         assertEquals(
             mkMap(mkEntry("client", "tag")),
             member.clientTags()
         );
-        assertArrayEquals("user-data".getBytes(), member.userData());
-        assertEquals(
-            mkMap(mkEntry("assignment", "config")),
-            member.assignmentConfigs()
-        );
     }
 
     @Test
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 68fddc0654f..c142c9b9cd7 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -31,7 +31,6 @@ import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.timeline.SnapshotRegistry;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.ValueSource;
 
 import java.util.Collections;
 import java.util.Optional;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index 03beca59411..b16664b8f30 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -17,7 +17,6 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.Uuid;
-import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
 import org.apache.kafka.coordinator.group.MetadataImageBuilder;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
@@ -40,8 +39,9 @@ import java.util.Set;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.Assertions.assertUnorderedListEquals;
-import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord;
 import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
@@ -59,7 +59,7 @@ public class TargetAssignmentBuilderTest {
         private final String groupId;
         private final int groupEpoch;
         private final TaskAssignor assignor = mock(TaskAssignor.class);
-        private final StreamsTopology topology = new StreamsTopology(new byte[0], new HashMap<>());
+        private final StreamsTopology topology = new StreamsTopology("", new HashMap<>());
         private final Map<String, StreamsGroupMember> members = new HashMap<>();
         private final Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = new HashMap<>();
         private final Map<String, StreamsGroupMember> updatedMembers = new HashMap<>();
@@ -91,8 +91,7 @@ public class TargetAssignmentBuilderTest {
             StreamsGroupMember.Builder memberBuilder = new StreamsGroupMember.Builder(memberId);
             memberBuilder.setProcessId("processId");
             memberBuilder.setClientTags(Collections.emptyMap());
-            memberBuilder.setAssignmentConfigs(Collections.emptyMap());
-            memberBuilder.setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090));
+            memberBuilder.setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090));
 
             if (instanceId != null) {
                 memberBuilder.setInstanceId(instanceId);
@@ -146,8 +145,7 @@ public class TargetAssignmentBuilderTest {
                 builder = new StreamsGroupMember.Builder(memberId);
                 builder.setProcessId("processId");
                 builder.setClientTags(Collections.emptyMap());
-                builder.setAssignmentConfigs(Collections.emptyMap());
-                builder.setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090));
+                builder.setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090));
             }
             updatedMembers.put(memberId, builder
                 .maybeUpdateInstanceId(instanceId)
@@ -271,7 +269,6 @@ public class TargetAssignmentBuilderTest {
             .setProcessId("processId")
             .setAssignor("assignor")
             .setClientTags(clientTags)
-            .setAssignmentConfigs(assignmentConfigs)
             .build();
 
         org.apache.kafka.coordinator.group.streams.Assignment assignment = new org.apache.kafka.coordinator.group.streams.Assignment(
@@ -293,7 +290,6 @@ public class TargetAssignmentBuilderTest {
             assignment.warmupTasks(),
             "processId",
             clientTags,
-            assignmentConfigs,
             Collections.emptyMap()
         ), assignmentMemberSpec);
     }
@@ -398,11 +394,11 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
                 mkTaskAssignment(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap())
@@ -468,15 +464,15 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2),
                 mkTaskAssignment(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4),
                 mkTaskAssignment(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
@@ -554,15 +550,15 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2),
                 mkTaskAssignment(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4),
                 mkTaskAssignment(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
@@ -636,11 +632,11 @@ public class TargetAssignmentBuilderTest {
 
         // Member 1 has no record because its assignment did not change.
         assertUnorderedListEquals(Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
                 mkTaskAssignment(barSubtopologyId, 3, 4, 5)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 6),
                 mkTaskAssignment(barSubtopologyId, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
@@ -710,11 +706,11 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
                 mkTaskAssignment(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
@@ -790,7 +786,7 @@ public class TargetAssignmentBuilderTest {
         assertEquals(2, result.records().size());
 
         assertUnorderedListEquals(Collections.singletonList(
-            CoordinatorRecordHelpers.newStreamsTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
+            newStreamsTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
index b9c9a8e7aaa..6e34368a155 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
@@ -48,7 +48,6 @@ public class GroupSpecImplTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         ));
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
index bc316db8772..457bbdb524d 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
@@ -63,7 +63,6 @@ public class MockAssignorTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         );
 
@@ -95,7 +94,6 @@ public class MockAssignorTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         );
 
@@ -107,7 +105,6 @@ public class MockAssignorTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         );
 
@@ -151,7 +148,6 @@ public class MockAssignorTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         );
 
@@ -166,7 +162,6 @@ public class MockAssignorTest {
             Collections.emptyMap(),
             "test-process",
             Collections.emptyMap(),
-            Collections.emptyMap(),
             Collections.emptyMap()
         );
         final GroupAssignment result = assignor.assign(
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index a2cb052e7f2..7de099c4ede 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -214,5 +214,7 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
             throw new AssertionError(driver.exception());
         }
         assertTrue(driver.result().passed(), driver.result().result());
+
+
     }
 }
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index f0a27b913f7..b87ba61b51d 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -544,18 +544,18 @@ public class StreamThread extends Thread implements ProcessingThread {
         return streamThread.updateThreadMetadata(adminClientId(clientId));
     }
 
-    private static HostInfo parseHostInfo(final String endPoint) {
-        final HostInfo hostInfo = HostInfo.buildFromEndpoint(endPoint);
+    private static Optional<StreamsAssignmentInterface.HostInfo> parseHostInfo(final String endpoint) {
+        final HostInfo hostInfo = HostInfo.buildFromEndpoint(endpoint);
         if (hostInfo == null) {
-            return StreamsMetadataState.UNKNOWN_HOST;
+            return Optional.empty();
         } else {
-            return hostInfo;
+            return Optional.of(new StreamsAssignmentInterface.HostInfo(hostInfo.host(), hostInfo.port()));
         }
     }
 
     private static StreamsAssignmentInterface initAssignmentInterface(final UUID processId,
                                                                       final StreamsConfig config,
-                                                                      final HostInfo hostInfo,
+                                                                      final Optional<StreamsAssignmentInterface.HostInfo> endpoint,
                                                                       final TopologyMetadata topologyMetadata) {
         final InternalTopologyBuilder internalTopologyBuilder = topologyMetadata.lookupBuilderForNamedTopology(null);
 
@@ -602,7 +602,7 @@ public class StreamThread extends Thread implements ProcessingThread {
 
         return new StreamsAssignmentInterface(
             processId,
-            new StreamsAssignmentInterface.HostInfo(hostInfo.host(), hostInfo.port()),
+            endpoint,
             null,
             subtopologyMap,
             assignmentProperties,
@@ -1380,9 +1380,9 @@ public class StreamThread extends Thread implements ProcessingThread {
             }
 
             // Process metadata from Streams Rebalance Protocol
-            final Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> hostInfoListMap = streamsAssignmentInterface.partitionsByHost.get();
+            final Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> partitionsByEndpoint = streamsAssignmentInterface.partitionsByHost.get();
             final Map<HostInfo, Set<TopicPartition>> convertedHostInfoMap = new HashMap<>();
-            hostInfoListMap.forEach((hostInfo, topicPartitions) ->
+            partitionsByEndpoint.forEach((hostInfo, topicPartitions) ->
                 convertedHostInfoMap.put(new HostInfo(hostInfo.host, hostInfo.port), new HashSet<>(topicPartitions)));
             streamsMetadataState.onChange(
                 convertedHostInfoMap,
@@ -1405,6 +1405,7 @@ public class StreamThread extends Thread implements ProcessingThread {
                     activeTasksWithPartitions,
                     standbyTasksWithPartitions
                 );
+                streamsAssignmentInterface.reconciledAssignment.set(newAssignment);
             }
         }
     }


(kafka) 35/42: Resolve conflicts from 11/25 trunk rebase - Internal topic auto creation (#17433)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 4686728d8839d452377e4aed4bf96afd61cdc18b
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue Oct 29 14:37:57 2024 +0100

    Resolve conflicts from 11/25 trunk rebase - Internal topic auto creation (#17433)
    
    * impl
    
    * fixes
---
 .../group/GroupCoordinatorAdapter.scala            |   5 +-
 .../kafka/server/AutoTopicCreationManager.scala    |  39 +++-
 core/src/main/scala/kafka/server/KafkaApis.scala   |  56 +++++-
 .../server/AutoTopicCreationManagerTest.scala      | 199 ++++++++++++++++++++-
 .../scala/unit/kafka/server/KafkaApisTest.scala    |   8 +-
 .../kafka/coordinator/group/GroupCoordinator.java  |   6 +-
 .../coordinator/group/GroupCoordinatorService.java |  11 +-
 .../coordinator/group/GroupCoordinatorShard.java   |   4 +-
 .../coordinator/group/GroupMetadataManager.java    |  55 +++---
 .../streams/StreamsGroupInitializeResult.java      |  74 ++++++++
 .../group/GroupCoordinatorServiceTest.java         |  14 +-
 .../group/GroupCoordinatorShardTest.java           |   5 +-
 .../group/GroupMetadataManagerTest.java            |  51 ++++--
 .../group/GroupMetadataManagerTestContext.java     |   6 +-
 .../SmokeTestDriverIntegrationTest.java            |  13 --
 streams/src/test/resources/log4j.properties        |   2 +
 16 files changed, 447 insertions(+), 101 deletions(-)

diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index ce8bde14493..ed4322fe67a 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,7 +18,7 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
@@ -26,6 +26,7 @@ import org.apache.kafka.common.requests.{OffsetCommitRequest, RequestContext, Tr
 import org.apache.kafka.common.utils.{BufferSupplier, Time}
 import org.apache.kafka.coordinator.group
 import org.apache.kafka.coordinator.group.OffsetAndMetadata
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult
 import org.apache.kafka.image.{MetadataDelta, MetadataImage}
 import org.apache.kafka.server.common.RequestLocal
 import org.apache.kafka.server.util.FutureUtils
@@ -80,7 +81,7 @@ private[group] class GroupCoordinatorAdapter(
   override def streamsGroupInitialize(
                                    context: RequestContext,
                                    request: StreamsGroupInitializeRequestData
-                                 ): CompletableFuture[StreamsGroupInitializeResponseData] = {
+                                 ): CompletableFuture[StreamsGroupInitializeResult] = {
     FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
       s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_INITIALIZE.name} API."
     ))
diff --git a/core/src/main/scala/kafka/server/AutoTopicCreationManager.scala b/core/src/main/scala/kafka/server/AutoTopicCreationManager.scala
index 58b3035935c..3b0ec564bec 100644
--- a/core/src/main/scala/kafka/server/AutoTopicCreationManager.scala
+++ b/core/src/main/scala/kafka/server/AutoTopicCreationManager.scala
@@ -47,6 +47,13 @@ trait AutoTopicCreationManager {
     controllerMutationQuota: ControllerMutationQuota,
     metadataRequestContext: Option[RequestContext]
   ): Seq[MetadataResponseTopic]
+
+
+  def createStreamsInternalTopics(
+    topics: Map[String, CreatableTopic],
+    requestContext: RequestContext
+  ): Unit
+
 }
 
 object AutoTopicCreationManager {
@@ -108,6 +115,31 @@ class DefaultAutoTopicCreationManager(
     uncreatableTopicResponses ++ creatableTopicResponses
   }
 
+  override def createStreamsInternalTopics(
+    topics: Map[String, CreatableTopic],
+    requestContext: RequestContext
+  ): Unit = {
+
+    for ((_, creatableTopic) <- topics) {
+      if (creatableTopic.numPartitions() == -1) {
+        creatableTopic
+          .setNumPartitions(config.numPartitions)
+      }
+      if (creatableTopic.replicationFactor() == -1) {
+        creatableTopic
+          .setReplicationFactor(config.defaultReplicationFactor.shortValue)
+      }
+    }
+
+    if (topics.isEmpty) {
+      Seq.empty
+    } else if (controller.isEmpty || !controller.get.isActive && channelManager.isDefined) {
+      sendCreateTopicRequest(topics, Some(requestContext))
+    } else {
+      throw new IllegalStateException("Controller must be defined in order to create streams internal topics.")
+    }
+  }
+
   private def createTopicsInZk(
     creatableTopics: Map[String, CreatableTopic],
     controllerMutationQuota: ControllerMutationQuota
@@ -160,7 +192,7 @@ class DefaultAutoTopicCreationManager(
 
   private def sendCreateTopicRequest(
     creatableTopics: Map[String, CreatableTopic],
-    metadataRequestContext: Option[RequestContext]
+    requestContext: Option[RequestContext]
   ): Seq[MetadataResponseTopic] = {
     val topicsToCreate = new CreateTopicsRequestData.CreatableTopicCollection(creatableTopics.size)
     topicsToCreate.addAll(creatableTopics.values.asJavaCollection)
@@ -184,7 +216,8 @@ class DefaultAutoTopicCreationManager(
         } else if (response.versionMismatch() != null) {
           warn(s"Auto topic creation failed for ${creatableTopics.keys} with invalid version exception")
         } else {
-          debug(s"Auto topic creation completed for ${creatableTopics.keys} with response ${response.responseBody}.")
+          // TODO: Response may still contain errors for individual topics. This should be exposed.
+          info(s"Auto topic creation completed for ${creatableTopics.keys} with response ${response.responseBody}.")
         }
       }
     }
@@ -193,7 +226,7 @@ class DefaultAutoTopicCreationManager(
       throw new IllegalStateException("Channel manager must be defined in order to send CreateTopic requests.")
     }
 
-    val request = metadataRequestContext.map { context =>
+    val request = requestContext.map { context =>
       val requestVersion =
         channelManager.controllerApiVersions.toScala match {
           case None =>
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 5e2abe450c2..31c5aaeeccf 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -3891,10 +3891,9 @@ class KafkaApis(val requestChannel: RequestChannel,
   }
 
   def handleStreamsGroupInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    // TODO: The unit tests for this method are insufficient. Once we merge initialize with group heartbeat, we have to extend the tests to cover ACLs and internal topic creation
     val streamsGroupInitializeRequest = request.body[StreamsGroupInitializeRequest]
 
-    // TODO: Check ACLs on CREATE TOPIC & DESCRIBE_CONFIGS
-
     if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
@@ -3904,6 +3903,53 @@ class KafkaApis(val requestChannel: RequestChannel,
       requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
       CompletableFuture.completedFuture[Unit](())
     } else {
+      val requestContext = request.context
+
+      val internalTopics: Map[String, StreamsGroupInitializeRequestData.TopicInfo] = {
+        streamsGroupInitializeRequest.data().topology().asScala.flatMap(subtopology =>
+          subtopology.repartitionSourceTopics().iterator().asScala ++ subtopology.stateChangelogTopics().iterator().asScala
+        ).map(x => x.name() -> x).toMap
+      }
+
+      val prohibitedInternalTopics = internalTopics.keys.filter(Topic.isInternal)
+      if (prohibitedInternalTopics.nonEmpty) {
+        val errorResponse = new StreamsGroupInitializeResponseData()
+        errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
+        errorResponse.setErrorMessage(f"Use of Kafka internal topics ${prohibitedInternalTopics.mkString(",")} as Kafka Streams internal topics is prohibited.")
+        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
+        return CompletableFuture.completedFuture[Unit](())
+      }
+
+      val invalidTopics = internalTopics.keys.filterNot(Topic.isValid)
+      if (invalidTopics.nonEmpty) {
+        val errorResponse = new StreamsGroupInitializeResponseData()
+        errorResponse.setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code)
+        errorResponse.setErrorMessage(f"Internal topic names ${invalidTopics.mkString(",")} are not valid topic names.")
+        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
+        return CompletableFuture.completedFuture[Unit](())
+      }
+
+      // TODO: Once we move initialization to the heartbeat, we should only require these permissions if there are missing internal topics.
+      if(!authHelper.authorize(request.context, CREATE, CLUSTER, CLUSTER_NAME, logIfDenied = false)) {
+        val (_, createTopicUnauthorized) = authHelper.partitionSeqByAuthorized(request.context, CREATE, TOPIC, internalTopics.keys.toSeq)(identity[String])
+        if (createTopicUnauthorized.nonEmpty) {
+          val errorResponse = new StreamsGroupInitializeResponseData()
+          errorResponse.setErrorCode(Errors.TOPIC_AUTHORIZATION_FAILED.code)
+          errorResponse.setErrorMessage(f"Unauthorized to CREATE TOPIC ${createTopicUnauthorized.mkString(",")}.")
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
+          return CompletableFuture.completedFuture[Unit](())
+        }
+      }
+
+      val (_, describeConfigsAuthorized) = authHelper.partitionSeqByAuthorized(request.context, DESCRIBE_CONFIGS, TOPIC, internalTopics.keys.toSeq)(identity[String])
+      if (describeConfigsAuthorized.nonEmpty) {
+        val errorResponse = new StreamsGroupInitializeResponseData()
+        errorResponse.setErrorCode(Errors.TOPIC_AUTHORIZATION_FAILED.code)
+        errorResponse.setErrorMessage(f"Unauthorized to DESCRIBE_CONFIGS on topics ${describeConfigsAuthorized.mkString(",")} are unauthorized.")
+        requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(errorResponse))
+        return CompletableFuture.completedFuture[Unit](())
+      }
+
       groupCoordinator.streamsGroupInitialize(
         request.context,
         streamsGroupInitializeRequest.data,
@@ -3911,7 +3957,11 @@ class KafkaApis(val requestChannel: RequestChannel,
         if (exception != null) {
           requestHelper.sendMaybeThrottle(request, streamsGroupInitializeRequest.getErrorResponse(exception))
         } else {
-          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(response))
+          if (!response.creatableTopics().isEmpty) {
+            // TODO: Once we move this code to the heartbeat, we should indicate which topics are being created. We should also find a way to propagate failures to the client
+            autoTopicCreationManager.createStreamsInternalTopics(response.creatableTopics().asScala, requestContext);
+          }
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupInitializeResponse(response.responseData()))
         }
       }
     }
diff --git a/core/src/test/scala/unit/kafka/server/AutoTopicCreationManagerTest.scala b/core/src/test/scala/unit/kafka/server/AutoTopicCreationManagerTest.scala
index d86c450ea0a..12b63489613 100644
--- a/core/src/test/scala/unit/kafka/server/AutoTopicCreationManagerTest.scala
+++ b/core/src/test/scala/unit/kafka/server/AutoTopicCreationManagerTest.scala
@@ -29,7 +29,7 @@ import org.apache.kafka.common.Node
 import org.apache.kafka.common.internals.Topic
 import org.apache.kafka.common.internals.Topic.{GROUP_METADATA_TOPIC_NAME, SHARE_GROUP_STATE_TOPIC_NAME, TRANSACTION_STATE_TOPIC_NAME}
 import org.apache.kafka.common.message.{ApiVersionsResponseData, CreateTopicsRequestData}
-import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic
+import org.apache.kafka.common.message.CreateTopicsRequestData.{CreatableTopic, CreatableTopicConfig, CreatableTopicConfigCollection}
 import org.apache.kafka.common.message.MetadataResponseData.MetadataResponseTopic
 import org.apache.kafka.common.network.{ClientInformation, ListenerName}
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
@@ -44,6 +44,7 @@ import org.apache.kafka.server.common.{ControllerRequestCompletionHandler, NodeT
 import org.junit.jupiter.api.Assertions.{assertEquals, assertThrows, assertTrue}
 import org.junit.jupiter.api.{BeforeEach, Test}
 import org.mockito.ArgumentMatchers.any
+import org.mockito.Mockito.never
 import org.mockito.invocation.InvocationOnMock
 import org.mockito.{ArgumentCaptor, ArgumentMatchers, Mockito}
 
@@ -255,7 +256,7 @@ class AutoTopicCreationManagerTest {
       override def deserialize(bytes: Array[Byte]): KafkaPrincipal = SecurityUtils.parseKafkaPrincipal(Utils.utf8(bytes))
     }
 
-    val requestContext = initializeRequestContext(topicName, userPrincipal, Optional.of(principalSerde))
+    val requestContext = initializeRequestContext(userPrincipal, Optional.of(principalSerde))
 
     autoTopicCreationManager.createTopics(
       Set(topicName), UnboundedControllerMutationQuota, Some(requestContext))
@@ -274,7 +275,7 @@ class AutoTopicCreationManagerTest {
   def testTopicCreationWithMetadataContextWhenPrincipalSerdeNotDefined(): Unit = {
     val topicName = "topic"
 
-    val requestContext = initializeRequestContext(topicName, KafkaPrincipal.ANONYMOUS, Optional.empty())
+    val requestContext = initializeRequestContext(KafkaPrincipal.ANONYMOUS, Optional.empty())
 
     // Throw upon undefined principal serde when building the forward request
     assertThrows(classOf[IllegalArgumentException], () => autoTopicCreationManager.createTopics(
@@ -292,7 +293,7 @@ class AutoTopicCreationManagerTest {
       override def deserialize(bytes: Array[Byte]): KafkaPrincipal = SecurityUtils.parseKafkaPrincipal(Utils.utf8(bytes))
     }
 
-    val requestContext = initializeRequestContext(topicName, KafkaPrincipal.ANONYMOUS, Optional.of(principalSerde))
+    val requestContext = initializeRequestContext(KafkaPrincipal.ANONYMOUS, Optional.of(principalSerde))
     autoTopicCreationManager.createTopics(
       Set(topicName), UnboundedControllerMutationQuota, Some(requestContext))
     autoTopicCreationManager.createTopics(
@@ -322,9 +323,16 @@ class AutoTopicCreationManagerTest {
       argumentCaptor.capture())
   }
 
-  private def initializeRequestContext(topicName: String,
-                                       kafkaPrincipal: KafkaPrincipal,
-                                       principalSerde: Optional[KafkaPrincipalSerde]): RequestContext = {
+  @Test
+  def testCreateStreamsInternalTopics(): Unit = {
+    val topicConfig = new CreatableTopicConfigCollection()
+    topicConfig.add(new CreatableTopicConfig().setName("cleanup.policy").setValue("compact"));
+
+    val topics = Map(
+      "stream-topic-1" -> new CreatableTopic().setName("stream-topic-1").setNumPartitions(3).setReplicationFactor(2).setConfigs(topicConfig),
+      "stream-topic-2" -> new CreatableTopic().setName("stream-topic-2").setNumPartitions(1).setReplicationFactor(1)
+    )
+    val requestContext = initializeRequestContextWithUserPrinciple()
 
     autoTopicCreationManager = new DefaultAutoTopicCreationManager(
       config,
@@ -335,8 +343,183 @@ class AutoTopicCreationManagerTest {
       transactionCoordinator,
       Some(shareCoordinator))
 
+    autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext)
+
+    val argumentCaptor = ArgumentCaptor.forClass(classOf[AbstractRequest.Builder[_ <: AbstractRequest]])
+    Mockito.verify(brokerToController).sendRequest(
+      argumentCaptor.capture(),
+      any(classOf[ControllerRequestCompletionHandler]))
+
+    val requestHeader = new RequestHeader(ApiKeys.CREATE_TOPICS, 0, "clientId", 0)
+    val capturedRequest = argumentCaptor.getValue.asInstanceOf[EnvelopeRequest.Builder].build(ApiKeys.ENVELOPE.latestVersion())
     val topicsCollection = new CreateTopicsRequestData.CreatableTopicCollection
-    topicsCollection.add(getNewTopic(topicName))
+    topicsCollection.add(getNewTopic("stream-topic-1", 3, 2.toShort).setConfigs(topicConfig))
+    topicsCollection.add(getNewTopic("stream-topic-2", 1, 1.toShort))
+    val requestBody = new CreateTopicsRequest.Builder(
+      new CreateTopicsRequestData()
+        .setTopics(topicsCollection)
+        .setTimeoutMs(requestTimeout))
+      .build(0)
+
+    val forwardedRequestBuffer = capturedRequest.requestData().duplicate()
+    assertEquals(requestHeader, RequestHeader.parse(forwardedRequestBuffer));
+    assertEquals(requestBody.data(), CreateTopicsRequest.parse(forwardedRequestBuffer, 0).data())
+  }
+
+  @Test
+  def testCreateStreamsInternalTopicsWhenControllerNotActive(): Unit = {
+    val topics = Map(
+      "stream-topic-1" -> new CreatableTopic().setName("stream-topic-1").setNumPartitions(3).setReplicationFactor(2)
+    )
+    val requestContext = initializeRequestContextWithUserPrinciple()
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      Some(brokerToController),
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
+    Mockito.when(controller.isActive).thenReturn(false)
+
+    autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext)
+
+    Mockito.verify(brokerToController).sendRequest(
+      any(classOf[AbstractRequest.Builder[_ <: AbstractRequest]]),
+      any(classOf[ControllerRequestCompletionHandler]))
+  }
+
+  @Test
+  def testFailStreamsInternalTopicsWhenNoChannelManager(): Unit = {
+    val topics = Map(
+      "stream-topic-1" -> new CreatableTopic().setName("stream-topic-1").setNumPartitions(3).setReplicationFactor(2)
+    )
+    val requestContext = initializeRequestContextWithUserPrinciple()
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      None,
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
+    Mockito.when(controller.isActive).thenReturn(true)
+
+    assertThrows(classOf[IllegalStateException], () => autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext))
+  }
+
+  @Test
+  def testCreateStreamsInternalTopicsWithEmptyTopics(): Unit = {
+    val topics = Map.empty[String, CreatableTopic]
+    val requestContext = initializeRequestContextWithUserPrinciple()
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      Some(brokerToController),
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
+    autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext)
+
+    Mockito.verify(brokerToController, never()).sendRequest(
+      any(classOf[AbstractRequest.Builder[_ <: AbstractRequest]]),
+      any(classOf[ControllerRequestCompletionHandler]))
+  }
+
+  @Test
+  def testCreateStreamsInternalTopicsWithDefaultConfig(): Unit = {
+    val topics = Map(
+      "stream-topic-1" -> new CreatableTopic().setName("stream-topic-1").setNumPartitions(-1).setReplicationFactor(-1)
+    )
+    val requestContext = initializeRequestContextWithUserPrinciple()
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      Some(brokerToController),
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
+    autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext);
+
+    val argumentCaptor = ArgumentCaptor.forClass(classOf[AbstractRequest.Builder[_ <: AbstractRequest]])
+    Mockito.verify(brokerToController).sendRequest(
+      argumentCaptor.capture(),
+      any(classOf[ControllerRequestCompletionHandler]))
+
+    val capturedRequest = argumentCaptor.getValue.asInstanceOf[EnvelopeRequest.Builder].build(ApiKeys.ENVELOPE.latestVersion())
+
+    val requestHeader = new RequestHeader(ApiKeys.CREATE_TOPICS, 0, "clientId", 0)
+    val topicsCollection = new CreateTopicsRequestData.CreatableTopicCollection
+    topicsCollection.add(getNewTopic("stream-topic-1", config.numPartitions, config.defaultReplicationFactor.toShort))
+    val requestBody = new CreateTopicsRequest.Builder(
+      new CreateTopicsRequestData()
+        .setTopics(topicsCollection)
+        .setTimeoutMs(requestTimeout))
+      .build(0)
+    val forwardedRequestBuffer = capturedRequest.requestData().duplicate()
+    assertEquals(requestHeader, RequestHeader.parse(forwardedRequestBuffer));
+    assertEquals(requestBody.data(), CreateTopicsRequest.parse(forwardedRequestBuffer, 0).data())
+  }
+
+  @Test
+  def testCreateStreamsInternalTopicsPassesPrinciple(): Unit = {
+    val topics = Map(
+      "stream-topic-1" -> new CreatableTopic().setName("stream-topic-1").setNumPartitions(-1).setReplicationFactor(-1)
+    )
+    val requestContext = initializeRequestContextWithUserPrinciple()
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      Some(brokerToController),
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
+    autoTopicCreationManager.createStreamsInternalTopics(topics, requestContext);
+
+    val argumentCaptor = ArgumentCaptor.forClass(classOf[AbstractRequest.Builder[_ <: AbstractRequest]])
+    Mockito.verify(brokerToController).sendRequest(
+      argumentCaptor.capture(),
+      any(classOf[ControllerRequestCompletionHandler]))
+    val capturedRequest = argumentCaptor.getValue.asInstanceOf[EnvelopeRequest.Builder].build(ApiKeys.ENVELOPE.latestVersion())
+    assertEquals(new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user"), SecurityUtils.parseKafkaPrincipal(Utils.utf8(capturedRequest.requestPrincipal)))
+  }
+
+  private def initializeRequestContextWithUserPrinciple(): RequestContext = {
+    val userPrincipal = new KafkaPrincipal(KafkaPrincipal.USER_TYPE, "user")
+    val principalSerde = new KafkaPrincipalSerde {
+      override def serialize(principal: KafkaPrincipal): Array[Byte] = {
+        Utils.utf8(principal.toString)
+      }
+      override def deserialize(bytes: Array[Byte]): KafkaPrincipal = SecurityUtils.parseKafkaPrincipal(Utils.utf8(bytes))
+    }
+    initializeRequestContext(userPrincipal, Optional.of(principalSerde))
+  }
+
+  private def initializeRequestContext(kafkaPrincipal: KafkaPrincipal,
+                                       principalSerde: Optional[KafkaPrincipalSerde]): RequestContext = {
+
+    autoTopicCreationManager = new DefaultAutoTopicCreationManager(
+      config,
+      Some(brokerToController),
+      Some(adminManager),
+      Some(controller),
+      groupCoordinator,
+      transactionCoordinator,
+      Some(shareCoordinator))
+
     val createTopicApiVersion = new ApiVersionsResponseData.ApiVersion()
       .setApiKey(ApiKeys.CREATE_TOPICS.id)
       .setMinVersion(0)
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 8d62dadd642..d31e6fb27e7 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -77,6 +77,8 @@ import org.apache.kafka.common.utils.{ImplicitLinkedHashCollection, ProducerIdAn
 import org.apache.kafka.coordinator.group.GroupConfig.{CONSUMER_HEARTBEAT_INTERVAL_MS_CONFIG, CONSUMER_SESSION_TIMEOUT_MS_CONFIG, SHARE_AUTO_OFFSET_RESET_CONFIG, SHARE_HEARTBEAT_INTERVAL_MS_CONFIG, SHARE_RECORD_LOCK_DURATION_MS_CONFIG, SHARE_SESSION_TIMEOUT_MS_CONFIG}
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupConfig
 import org.apache.kafka.coordinator.group.{GroupConfig, GroupCoordinator, GroupCoordinatorConfig}
+import org.apache.kafka.coordinator.group.{GroupCoordinator, GroupCoordinatorConfig}
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult
 import org.apache.kafka.coordinator.share.{ShareCoordinator, ShareCoordinatorConfigTest}
 import org.apache.kafka.coordinator.transaction.TransactionLogConfig
 import org.apache.kafka.metadata.LeaderAndIsr
@@ -11242,7 +11244,7 @@ class KafkaApisTest extends Logging {
 
     val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
+    val future = new CompletableFuture[StreamsGroupInitializeResult]()
     when(groupCoordinator.streamsGroupInitialize(
       requestChannelRequest.context,
       streamsGroupInitializeRequest
@@ -11253,7 +11255,7 @@ class KafkaApisTest extends Logging {
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
-    val streamsGroupInitializeResponse = new StreamsGroupInitializeResponseData()
+    val streamsGroupInitializeResponse = new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData())
 
     future.complete(streamsGroupInitializeResponse)
     val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
@@ -11268,7 +11270,7 @@ class KafkaApisTest extends Logging {
 
     val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
-    val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
+    val future = new CompletableFuture[StreamsGroupInitializeResult]()
     when(groupCoordinator.streamsGroupInitialize(
       requestChannelRequest.context,
       streamsGroupInitializeRequest
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index 7c78db21761..07d5d7daaee 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -43,7 +43,6 @@ import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -51,6 +50,7 @@ import org.apache.kafka.common.message.TxnOffsetCommitResponseData;
 import org.apache.kafka.common.requests.RequestContext;
 import org.apache.kafka.common.requests.TransactionResult;
 import org.apache.kafka.common.utils.BufferSupplier;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 
@@ -93,10 +93,10 @@ public interface GroupCoordinator {
      * @param context           The request context.
      * @param request           The StreamsGroupInitializeRequest data.
      *
-     * @return  A future yielding the response.
+     * @return  A future yielding the result, which contains the response and all topics to be created.
      *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
      */
-    CompletableFuture<StreamsGroupInitializeResponseData> streamsGroupInitialize(
+    CompletableFuture<StreamsGroupInitializeResult> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 007e991ad16..3f2f4920162 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -78,6 +78,7 @@ import org.apache.kafka.coordinator.common.runtime.CoordinatorShardBuilderSuppli
 import org.apache.kafka.coordinator.common.runtime.MultiThreadedEventProcessor;
 import org.apache.kafka.coordinator.common.runtime.PartitionWriter;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.record.BrokerCompressionType;
@@ -354,14 +355,14 @@ public class GroupCoordinatorService implements GroupCoordinator {
      * See {@link GroupCoordinator#streamsGroupInitialize(RequestContext, org.apache.kafka.common.message.StreamsGroupInitializeRequestData)}.
      */
     @Override
-    public CompletableFuture<StreamsGroupInitializeResponseData> streamsGroupInitialize(
+    public CompletableFuture<StreamsGroupInitializeResult> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) {
         if (!isActive.get()) {
-            return CompletableFuture.completedFuture(new StreamsGroupInitializeResponseData()
+            return CompletableFuture.completedFuture(new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData()
                 .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
-            );
+            ));
         }
 
         return runtime.scheduleWriteOperation(
@@ -373,9 +374,9 @@ public class GroupCoordinatorService implements GroupCoordinator {
             "streams-group-initialize",
             request,
             exception,
-            (error, message) -> new StreamsGroupInitializeResponseData()
+            (error, message) -> new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData()
                 .setErrorCode(error.code())
-                .setErrorMessage(message),
+                .setErrorMessage(message)),
             log
         ));
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 6a2ad52ec3a..1e67ca0f882 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -43,7 +43,6 @@ import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -107,6 +106,7 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.coordinator.group.taskassignor.StickyTaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
@@ -398,7 +398,7 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
      * @return A Result containing the StreamsGroupInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index f613d11c8f3..78e433203a4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -38,6 +38,7 @@ import org.apache.kafka.common.message.ConsumerGroupDescribeResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerProtocolSubscription;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
 import org.apache.kafka.common.message.DescribeGroupsResponseData;
 import org.apache.kafka.common.message.HeartbeatRequestData;
 import org.apache.kafka.common.message.HeartbeatResponseData;
@@ -140,8 +141,11 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupAssignmentBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsTopology;
+import org.apache.kafka.coordinator.group.streams.topics.InternalTopicManager;
+import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
@@ -177,7 +181,6 @@ import java.util.stream.Stream;
 import static org.apache.kafka.common.protocol.Errors.COORDINATOR_NOT_AVAILABLE;
 import static org.apache.kafka.common.protocol.Errors.ILLEGAL_GENERATION;
 import static org.apache.kafka.common.protocol.Errors.NOT_COORDINATOR;
-import static org.apache.kafka.common.protocol.Errors.STREAMS_INVALID_TOPOLOGY;
 import static org.apache.kafka.common.protocol.Errors.UNKNOWN_SERVER_ERROR;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.CONSUMER_GENERATED_MEMBER_ID_REQUIRED_VERSION;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH;
@@ -2664,7 +2667,7 @@ public class GroupMetadataManager {
      * @param subtopologies The list of subtopologies.
      * @return A Result containing the StreamsGroupInitialize response and a list of records to update the state machine.
      */
-    private CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(String groupId,
+    private CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(String groupId,
                                                                                                        String topologyId,
                                                                                                             List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
         throws ApiException {
@@ -2679,49 +2682,31 @@ public class GroupMetadataManager {
         if (!isTopologyInitializationScheduled(groupId, topologyId)) {
             log.warn("No topology to initialize for group ID {} and topology ID {} found.", groupId, topologyId);
             StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
-            return new CoordinatorResult<>(records, response);
-        }
-
-        // TODO: For the POC, only check if internal topics exist
-        Set<String> missingTopics = new HashSet<>();
-        for (StreamsGroupInitializeRequestData.Subtopology subtopology : subtopologies) {
-            for (StreamsGroupInitializeRequestData.TopicInfo topic : subtopology.stateChangelogTopics()) {
-                if (metadataImage.topics().getTopic(topic.name()) == null) {
-                    missingTopics.add(topic.name());
-                }
-            }
-            for (StreamsGroupInitializeRequestData.TopicInfo topic : subtopology.repartitionSourceTopics()) {
-                if (metadataImage.topics().getTopic(topic.name()) == null) {
-                    missingTopics.add(topic.name());
-                }
-            }
+            return new CoordinatorResult<>(records, new StreamsGroupInitializeResult(response));
         }
 
         StreamsGroupTopologyValue recordValue = convertToStreamsGroupTopologyRecord(subtopologies);
 
-        cancelStreamsGroupTopologyInitializationTimeout(groupId, topologyId);
-
-        if (!missingTopics.isEmpty()) {
-            StreamsGroupInitializeResponseData response =
-                new StreamsGroupInitializeResponseData()
-                    .setErrorCode(STREAMS_INVALID_TOPOLOGY.code())
-                    .setErrorMessage("Internal topics " + String.join(", ", missingTopics) + " do not exist.");
+        final Map<String, ConfiguredSubtopology> configuredTopics =
+            InternalTopicManager.configureTopics(logContext, recordValue.topology(), metadataImage);
 
-            return new CoordinatorResult<>(records, response);
-        } else {
-            records.add(newStreamsGroupTopologyRecord(groupId, recordValue));
+        cancelStreamsGroupTopologyInitializationTimeout(groupId, topologyId);
 
-            final Map<String, StreamsGroupTopologyValue.Subtopology> subtopologyMap = recordValue.topology().stream()
-                .collect(Collectors.toMap(StreamsGroupTopologyValue.Subtopology::subtopologyId, x -> x));
+        records.add(newStreamsGroupTopologyRecord(groupId, recordValue));
 
-            final StreamsTopology topology = new StreamsTopology(topologyId, subtopologyMap);
+        final Map<String, StreamsGroupTopologyValue.Subtopology> subtopologyMap = recordValue.topology().stream()
+            .collect(Collectors.toMap(StreamsGroupTopologyValue.Subtopology::subtopologyId, x -> x));
+        final StreamsTopology topology = new StreamsTopology(topologyId, subtopologyMap);
 
+        final Map<String, CreatableTopic> missingTopics = InternalTopicManager.missingTopics(configuredTopics, metadataImage);
+        // TODO: This needs to be sorted out, once we merge heartbeat and initialization
+        if (missingTopics.isEmpty()) {
             computeFirstTargetAssignmentAfterTopologyInitialization(group, records, topology);
+        }
 
-            StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
+        StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
 
-            return new CoordinatorResult<>(records, response);
-        }
+        return new CoordinatorResult<>(records, new StreamsGroupInitializeResult(response, missingTopics));
 
     }
 
@@ -4913,7 +4898,7 @@ public class GroupMetadataManager {
      * @return A Result containing the StreamsGroupInitialize response and
      *         a list of records to update the state machine.
      */
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
         RequestContext context,
         StreamsGroupInitializeRequestData request
     ) throws ApiException {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java
new file mode 100644
index 00000000000..7a4845993eb
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupInitializeResult.java
@@ -0,0 +1,74 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+
+public class StreamsGroupInitializeResult {
+
+    private final StreamsGroupInitializeResponseData data;
+    private final Map<String, CreatableTopic> creatableTopics;
+
+    public StreamsGroupInitializeResult(StreamsGroupInitializeResponseData data, Map<String, CreatableTopic> creatableTopics) {
+        this.data = data;
+        this.creatableTopics = creatableTopics;
+    }
+
+    public StreamsGroupInitializeResult(StreamsGroupInitializeResponseData data) {
+        this.data = data;
+        this.creatableTopics = Collections.emptyMap();
+    }
+
+    public StreamsGroupInitializeResponseData responseData() {
+        return data;
+    }
+
+    public Map<String, CreatableTopic> creatableTopics() {
+        return creatableTopics;
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final StreamsGroupInitializeResult that = (StreamsGroupInitializeResult) o;
+        return Objects.equals(data, that.data) && Objects.equals(creatableTopics,
+            that.creatableTopics);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(data, creatableTopics);
+    }
+
+    @Override
+    public String toString() {
+        return "StreamsGroupInitializeResult{" +
+            "data=" + data +
+            ", creatableTopics=" + creatableTopics +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index 7505aa8c791..6ce91186adf 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -78,6 +78,7 @@ import org.apache.kafka.common.utils.Utils;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRuntime;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.server.record.BrokerCompressionType;
 import org.apache.kafka.server.util.FutureUtils;
 
@@ -280,14 +281,15 @@ public class GroupCoordinatorServiceTest {
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
             .setGroupId("foo");
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
+        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
 
         assertEquals(
-            new StreamsGroupInitializeResponseData()
-                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
+            new StreamsGroupInitializeResult(
+                new StreamsGroupInitializeResponseData()
+                    .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())),
             future.get()
         );
     }
@@ -317,7 +319,7 @@ public class GroupCoordinatorServiceTest {
             new StreamsGroupInitializeResponseData()
         ));
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
+        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
@@ -368,7 +370,7 @@ public class GroupCoordinatorServiceTest {
             ArgumentMatchers.any()
         )).thenReturn(FutureUtils.failedFuture(exception));
 
-        CompletableFuture<StreamsGroupInitializeResponseData> future = service.streamsGroupInitialize(
+        CompletableFuture<StreamsGroupInitializeResult> future = service.streamsGroupInitialize(
             requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE),
             request
         );
@@ -377,7 +379,7 @@ public class GroupCoordinatorServiceTest {
             new StreamsGroupInitializeResponseData()
                 .setErrorCode(expectedErrorCode)
                 .setErrorMessage(expectedErrorMessage),
-            future.get(5, TimeUnit.SECONDS)
+            future.get(5, TimeUnit.SECONDS).responseData()
         );
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index 03966c07ea8..b836131e667 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -65,6 +65,7 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupMemberMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMemberMetadataValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataValue;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 
@@ -154,9 +155,9 @@ public class GroupCoordinatorShardTest {
 
         RequestContext context = requestContext(ApiKeys.STREAMS_GROUP_INITIALIZE);
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData();
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = new CoordinatorResult<>(
             Collections.emptyList(),
-            new StreamsGroupInitializeResponseData()
+            new StreamsGroupInitializeResult(new StreamsGroupInitializeResponseData())
         );
 
         when(groupMetadataManager.streamsGroupInitialize(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 8ff26e74f35..afdbe390021 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -41,6 +41,9 @@ import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerProtocolAssignment;
 import org.apache.kafka.common.message.ConsumerProtocolSubscription;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopic;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfig;
+import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicConfigCollection;
 import org.apache.kafka.common.message.DescribeGroupsResponseData;
 import org.apache.kafka.common.message.HeartbeatRequestData;
 import org.apache.kafka.common.message.HeartbeatResponseData;
@@ -97,6 +100,7 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil;
 import org.apache.kafka.image.MetadataDelta;
@@ -567,10 +571,10 @@ public class GroupMetadataManagerTest {
             .setTopologyId(topologyId)
             .setTopology(subtopologies);
 
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
 
         assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response();
+        StreamsGroupInitializeResponseData response = result.response().responseData();
         assertEquals(Errors.NONE.code(), response.errorCode());
         List<CoordinatorRecord> coordinatorRecords = result.records();
         assertEquals(5, coordinatorRecords.size());
@@ -685,10 +689,10 @@ public class GroupMetadataManagerTest {
             .setTopologyId(wrongTopologyId)
             .setTopology(subtopologies);
 
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
 
         assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response();
+        StreamsGroupInitializeResponseData response = result.response().responseData();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertTrue(result.records().isEmpty());
     }
@@ -729,10 +733,10 @@ public class GroupMetadataManagerTest {
             .setTopology(subtopologies);
 
         context.streamsGroupInitialize(initialize);
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
 
         assertNotNull(result.response());
-        StreamsGroupInitializeResponseData response = result.response();
+        StreamsGroupInitializeResponseData response = result.response().responseData();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertTrue(result.records().isEmpty());
     }
@@ -745,9 +749,12 @@ public class GroupMetadataManagerTest {
         String processId = "process-id";
         Uuid fooTopicId = Uuid.randomUuid();
         String fooTopicName = "repartition";
+        Uuid barTopicId = Uuid.randomUuid();
+        String barTopicName = "bar";
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
             .withMetadataImage(new MetadataImageBuilder()
-                .addTopic(fooTopicId, fooTopicName, 6)
+                .addTopic(fooTopicId, fooTopicName, 4)
+                .addTopic(barTopicId, barTopicName, 4)
                 .addRacks()
                 .build())
             .build();
@@ -776,6 +783,7 @@ public class GroupMetadataManagerTest {
                     Collections.singletonList(
                         new StreamsGroupInitializeRequestData.TopicInfo()
                             .setName("changelog")
+                            .setReplicationFactor((short) 3)
                             .setTopicConfigs(Collections.singletonList(
                                 new StreamsGroupInitializeRequestData.TopicConfig()
                                     .setKey("config-name2")
@@ -784,7 +792,7 @@ public class GroupMetadataManagerTest {
                     )
                 )
         );
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result =
             context.streamsGroupInitialize(
                 new StreamsGroupInitializeRequestData()
                     .setGroupId(groupId)
@@ -792,14 +800,31 @@ public class GroupMetadataManagerTest {
                     .setTopology(topology)
             );
 
+        CreatableTopicConfigCollection expectedConfig = new CreatableTopicConfigCollection();
+        expectedConfig.add(
+            new CreatableTopicConfig()
+                .setName("config-name2")
+                .setValue("config-value2")
+        );
+        CreatableTopic expected =
+            new CreatableTopic()
+                .setName("changelog")
+                .setNumPartitions(4)
+                .setReplicationFactor((short) 3)
+                .setConfigs(expectedConfig);
+
         assertEquals(
-            new StreamsGroupInitializeResponseData()
-                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
-                .setErrorMessage("Internal topics changelog do not exist."),
+            new StreamsGroupInitializeResult(
+                new StreamsGroupInitializeResponseData(),
+                Collections.singletonMap(
+                    "changelog", expected
+                )
+            ),
             result.response()
         );
-        
-        assertTrue(result.records().isEmpty());
+
+        // TODO: Need to check the generated records. Adapt this unit test after merging of
+        //       initilization & heartbeat
     }
 
     private StreamsGroupHeartbeatRequestData buildFirstStreamsGroupHeartbeatRequest(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 96fd18344c0..08990d9c077 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -40,7 +40,6 @@ import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.network.ClientInformation;
@@ -111,6 +110,7 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupInitializeResult;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -736,7 +736,7 @@ public class GroupMetadataManagerTestContext {
     }
 
 
-    public CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(
+    public CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> streamsGroupInitialize(
         StreamsGroupInitializeRequestData request
     ) {
         RequestContext context = new RequestContext(
@@ -755,7 +755,7 @@ public class GroupMetadataManagerTestContext {
             false
         );
 
-        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsGroupInitialize(
+        CoordinatorResult<StreamsGroupInitializeResult, CoordinatorRecord> result = groupMetadataManager.streamsGroupInitialize(
             context,
             request
         );
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index ab8fb57d3fb..498613ce783 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -127,19 +127,6 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
         }
 
         for (final String topic: new String[]{
-            "SmokeTest-KSTREAM-REDUCE-STATE-STORE-0000000020-changelog",
-            "SmokeTest-minStoreName-changelog",
-            "SmokeTest-cntByCnt-repartition",
-            "SmokeTest-KTABLE-SUPPRESS-STATE-STORE-0000000011-changelog",
-            "SmokeTest-sum-STATE-STORE-0000000050-changelog",
-            "SmokeTest-uwin-cnt-changelog",
-            "SmokeTest-maxStoreName-changelog",
-            "SmokeTest-cntStoreName-changelog",
-            "SmokeTest-KTABLE-SUPPRESS-STATE-STORE-0000000027-changelog",
-            "SmokeTest-win-sum-changelog",
-            "SmokeTest-uwin-max-changelog",
-            "SmokeTest-uwin-min-changelog",
-            "SmokeTest-cntByCnt-changelog",
             "data",
             "echo",
             "max",
diff --git a/streams/src/test/resources/log4j.properties b/streams/src/test/resources/log4j.properties
index 197c8c74210..2f0f3833eb9 100644
--- a/streams/src/test/resources/log4j.properties
+++ b/streams/src/test/resources/log4j.properties
@@ -28,6 +28,8 @@ log4j.logger.org.apache.kafka.clients.consumer=INFO
 log4j.logger.org.apache.kafka.clients.producer=INFO
 log4j.logger.org.apache.kafka.streams=INFO
 log4j.logger.org.apache.kafka.coordinator.group=INFO
+log4j.logger.org.apache.kafka.clients.consumer.internals.StreamsGroupInitializeRequestManager=INFO
+log4j.logger.org.apache.kafka.clients.consumer.internals.StreamsGroupHeartbeatRequestManager=INFO
 
 # printing out the configs takes up a huge amount of the allotted characters,
 # and provides little value as we can always figure out the test configs without the logs


(kafka) 32/42: Complete topic metadata for automatic topic creation (#17391)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit b18625b86ff9f7d688089313441f7f7c10a1fc6d
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue Oct 8 17:30:48 2024 +0200

    Complete topic metadata for automatic topic creation (#17391)
    
    * KSTREAMS-6456: Complete topic metadata for automatic topic creation
    
    This change updates the current RPCs and schemas to add the following
    metadata:
    
     - copartition groups are added to topology record and initialize RPC
     - multiple regexs are added to topology record and initialize RPC
     - replication factors are added for reach internal topic
    
    We also add code to fill this information correctly from the
    `InternalTopologyBuilder` object.
    
    The fields `assignmentConfiguration` and `assignor` in the
    `StreamsAssignmentInterface` are removed, because they are not
    needed anymore.
    
    * fixes
---
 .../internals/StreamsAssignmentInterface.java      | 31 +++-----
 .../StreamsGroupInitializeRequestManager.java      | 71 ++++++++++++++++--
 .../message/StreamsGroupDescribeResponse.json      | 10 +--
 .../message/StreamsGroupInitializeRequest.json     | 21 ++++--
 .../StreamsGroupHeartbeatRequestManagerTest.java   | 19 ++---
 .../StreamsGroupInitializeRequestManagerTest.java  | 35 ++++++---
 .../coordinator/group/GroupMetadataManager.java    | 10 ++-
 .../streams/CoordinatorStreamsRecordHelpers.java   | 84 ++++++++++++++++------
 .../coordinator/group/streams/StreamsTopology.java | 32 +--------
 .../common/message/StreamsGroupTopologyValue.json  | 23 ++++--
 .../CoordinatorStreamsRecordHelpersTest.java       | 22 ++++++
 .../group/streams/StreamsTopologyTest.java         | 36 +++++++---
 .../streams/processor/internals/StreamThread.java  | 74 +++++++++++--------
 13 files changed, 316 insertions(+), 152 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index 1e23233f4e6..cefe9175b68 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -18,6 +18,7 @@ package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.common.TopicPartition;
 
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -41,12 +42,8 @@ public class StreamsAssignmentInterface {
 
     private Optional<HostInfo> endpoint;
 
-    private String assignor;
-
     private Map<String, Subtopology> subtopologyMap;
 
-    private Map<String, Object> assignmentConfiguration;
-
     private Map<TaskId, Long> taskLags;
 
     private AtomicBoolean shutdownRequested;
@@ -66,18 +63,10 @@ public class StreamsAssignmentInterface {
         return endpoint;
     }
 
-    public String assignor() {
-        return assignor;
-    }
-
     public Map<String, Subtopology> subtopologyMap() {
         return subtopologyMap;
     }
 
-    public Map<String, Object> assignmentConfiguration() {
-        return assignmentConfiguration;
-    }
-
     // TODO: This needs to be used somewhere
     public Map<TaskId, Long> taskLags() {
         return taskLags;
@@ -190,11 +179,14 @@ public class StreamsAssignmentInterface {
     public static class TopicInfo {
 
         public final Optional<Integer> numPartitions;
+        public final Optional<Short> replicationFactor;
         public final Map<String, String> topicConfigs;
 
         public TopicInfo(final Optional<Integer> numPartitions,
+                         final Optional<Short> replicationFactor,
                          final Map<String, String> topicConfigs) {
             this.numPartitions = numPartitions;
+            this.replicationFactor = replicationFactor;
             this.topicConfigs = topicConfigs;
         }
 
@@ -202,10 +194,10 @@ public class StreamsAssignmentInterface {
         public String toString() {
             return "TopicInfo{" +
                 "numPartitions=" + numPartitions +
+                ", replicationFactor=" + replicationFactor +
                 ", topicConfigs=" + topicConfigs +
                 '}';
         }
-
     }
 
     public static class TaskId {
@@ -241,15 +233,19 @@ public class StreamsAssignmentInterface {
         public final Set<String> sinkTopics;
         public final Map<String, TopicInfo> stateChangelogTopics;
         public final Map<String, TopicInfo> repartitionSourceTopics;
+        public final Collection<Set<String>> copartitionGroups;
 
         public Subtopology(final Set<String> sourceTopics,
                            final Set<String> sinkTopics,
                            final Map<String, TopicInfo> repartitionSourceTopics,
-                           final Map<String, TopicInfo> stateChangelogTopics) {
+                           final Map<String, TopicInfo> stateChangelogTopics,
+                           final Collection<Set<String>> copartitionGroups
+        ) {
             this.sourceTopics = sourceTopics;
             this.sinkTopics = sinkTopics;
             this.stateChangelogTopics = stateChangelogTopics;
             this.repartitionSourceTopics = repartitionSourceTopics;
+            this.copartitionGroups = copartitionGroups;
         }
 
         @Override
@@ -259,22 +255,19 @@ public class StreamsAssignmentInterface {
                 ", sinkTopics=" + sinkTopics +
                 ", stateChangelogTopics=" + stateChangelogTopics +
                 ", repartitionSourceTopics=" + repartitionSourceTopics +
+                ", copartitionGroups=" + copartitionGroups +
                 '}';
         }
     }
 
     public StreamsAssignmentInterface(UUID processId,
                                       Optional<HostInfo> endpoint,
-                                      String assignor,
                                       Map<String, Subtopology> subtopologyMap,
-                                      Map<String, Object> assignmentConfiguration,
                                       Map<String, String> clientTags
     ) {
         this.processId = processId;
         this.endpoint = endpoint;
-        this.assignor = assignor;
         this.subtopologyMap = subtopologyMap;
-        this.assignmentConfiguration = assignmentConfiguration;
         this.taskLags = new HashMap<>();
         this.shutdownRequested = new AtomicBoolean(false);
         this.clientTags = clientTags;
@@ -285,9 +278,7 @@ public class StreamsAssignmentInterface {
         return "StreamsAssignmentMetadata{" +
             "processID=" + processId +
             ", endpoint='" + endpoint + '\'' +
-            ", assignor='" + assignor + '\'' +
             ", subtopologyMap=" + subtopologyMap +
-            ", assignmentConfiguration=" + assignmentConfiguration +
             ", taskLags=" + taskLags +
             ", clientTags=" + clientTags +
             '}';
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
index b81beab78d9..8c7671efe67 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
@@ -19,6 +19,7 @@ package org.apache.kafka.clients.consumer.internals;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData.CopartitionGroup;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
 import org.apache.kafka.common.requests.StreamsGroupInitializeResponse;
@@ -27,9 +28,15 @@ import org.apache.kafka.common.utils.LogContext;
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
 
 public class StreamsGroupInitializeRequestManager implements RequestManager {
 
@@ -72,9 +79,8 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
         streamsGroupInitializeRequestData.setTopologyId(streamsAssignmentInterface.topologyId());
         final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
         streamsGroupInitializeRequestData.setTopology(topology);
-        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
-            streamsGroupInitializeRequestData
-        );
+        final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder =
+            new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequestData);
         return new NetworkClientDelegate.UnsentRequest(
             streamsGroupInitializeRequestBuilder,
             coordinatorRequestManager.coordinator()
@@ -94,21 +100,72 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
                                                                                            final StreamsAssignmentInterface.Subtopology subtopology) {
         final StreamsGroupInitializeRequestData.Subtopology subtopologyData = new StreamsGroupInitializeRequestData.Subtopology();
         subtopologyData.setSubtopologyId(subtopologyName);
-        subtopologyData.setSourceTopics(new ArrayList<>(subtopology.sourceTopics));
-        subtopologyData.setRepartitionSinkTopics(new ArrayList<>(subtopology.sinkTopics));
+        ArrayList<String> sortedSourceTopics = new ArrayList<>(subtopology.sourceTopics);
+        Collections.sort(sortedSourceTopics);
+        subtopologyData.setSourceTopics(sortedSourceTopics);
+        // TODO: We should only encode the repartition sink topics here.
+        ArrayList<String> sortedSinkTopics = new ArrayList<>(subtopology.sinkTopics);
+        Collections.sort(sortedSinkTopics);
+        subtopologyData.setRepartitionSinkTopics(sortedSinkTopics);
         subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
         subtopologyData.setStateChangelogTopics(getChangelogTopicsInfoFromStreams(subtopology));
+        subtopologyData.setCopartitionGroups(
+            getCopartitionGroupsFromStreams(subtopology.copartitionGroups, subtopologyData));
         return subtopologyData;
     }
 
+    private static List<CopartitionGroup> getCopartitionGroupsFromStreams(
+        final Collection<Set<String>> copartitionGroups,
+        final StreamsGroupInitializeRequestData.Subtopology subtopologyData) {
+
+        final Map<String, Short> sourceTopicsMap =
+            IntStream.range(0, subtopologyData.sourceTopics().size())
+                .boxed()
+                .collect(Collectors.toMap(subtopologyData.sourceTopics()::get, Integer::shortValue));
+
+        final Map<String, Short> repartitionSourceTopics =
+            IntStream.range(0, subtopologyData.repartitionSourceTopics().size())
+                .boxed()
+                .collect(
+                    Collectors.toMap(x -> subtopologyData.repartitionSourceTopics().get(x).name(),
+                        Integer::shortValue));
+
+        return copartitionGroups.stream()
+            .map(x -> getCopartitionGroupFromStreams(x, sourceTopicsMap, repartitionSourceTopics))
+            .collect(Collectors.toList());
+    }
+
+    private static CopartitionGroup getCopartitionGroupFromStreams(
+        final Set<String> topicNames,
+        final Map<String, Short> sourceTopicsMap,
+        final Map<String, Short> repartitionSourceTopics) {
+        CopartitionGroup copartitionGroup = new CopartitionGroup();
+
+        topicNames.forEach(topicName -> {
+            if (sourceTopicsMap.containsKey(topicName)) {
+                copartitionGroup.sourceTopics().add(sourceTopicsMap.get(topicName));
+            } else if (repartitionSourceTopics.containsKey(topicName)) {
+                copartitionGroup.repartitionSourceTopics()
+                    .add(repartitionSourceTopics.get(topicName));
+            } else {
+                throw new IllegalStateException(
+                    "Source topic not found in subtopology: " + topicName);
+            }
+        });
+
+        return copartitionGroup;
+    }
+
     private static List<StreamsGroupInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
         final List<StreamsGroupInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
             final StreamsGroupInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
             repartitionTopicInfo.setName(repartitionTopic.getKey());
             repartitionTopic.getValue().numPartitions.ifPresent(repartitionTopicInfo::setPartitions);
+            repartitionTopic.getValue().replicationFactor.ifPresent(repartitionTopicInfo::setReplicationFactor);
             repartitionTopicsInfo.add(repartitionTopicInfo);
         }
+        repartitionTopicsInfo.sort(Comparator.comparing(StreamsGroupInitializeRequestData.TopicInfo::name));
         return repartitionTopicsInfo;
     }
 
@@ -117,11 +174,13 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
             final StreamsGroupInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsGroupInitializeRequestData.TopicInfo();
             changelogTopicInfo.setName(changelogTopic.getKey());
+            changelogTopic.getValue().replicationFactor.ifPresent(changelogTopicInfo::setReplicationFactor);
             changelogTopicsInfo.add(changelogTopicInfo);
         }
+        changelogTopicsInfo.sort(Comparator.comparing(StreamsGroupInitializeRequestData.TopicInfo::name));
         return changelogTopicsInfo;
     }
-    
+
     private void onResponse(final ClientResponse response, final Throwable exception) {
         if (exception != null) {
             // todo: handle error
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index 227ac495c2d..71d74eee831 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -52,14 +52,14 @@
               "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
             { "name": "SourceTopics", "type": "[]string", "versions": "0+",
               "about": "The topics the topology reads from." },
-            { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
-              "about": "The regular expressions identifying topics the topology reads from." },
             { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
               "about": "The repartition topics the topology writes to." },
+            { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
+              "about": "Regular expressions identifying topics the subtopology reads from." },
             { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
               "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
             { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
-              "about": "The set of source topics that are internally created repartition topics. Created automatically." }
+              "about": "The set of source topics that are internally created repartition topics." }
           ]
         },
         { "name": "Members", "type": "[]Member", "versions": "0+",
@@ -143,7 +143,9 @@
         "about": "The name of the topic." },
       { "name": "Partitions", "type": "int32", "versions": "0+",
         "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
-      { "name": "TopicConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      { "name": "ReplicationFactor", "type": "int16", "versions": "0+",
+        "about": "The replication factor of the topic. Can be 0 if the default replication factor should be used." },
+      { "name": "TopicConfigs", "type": "[]KeyValue", "versions": "0+",
         "about": "Topic-level configurations as key-value pairs."
       }
     ]}
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
index 05c4709092c..aa68fde6bf5 100644
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
@@ -32,14 +32,25 @@
           "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
-        { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-          "about": "The regular expressions identifying topics the subtopology reads from." },
+        { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
+          "about": "Regular expressions identifying topics the subtopology reads from." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
         { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
           "about": "The repartition topics the subtopology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of source topics that are internally created repartition topics. Created automatically." }
+          "about": "The set of source topics that are internally created repartition topics. Created automatically." },
+        { "name": "CopartitionGroups", "type": "[]CopartitionGroup", "versions": "0+",
+          "about": "A subset of source topics that must be copartitioned.",
+          "fields": [
+            { "name": "SourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The topics the topology reads from. Index into the array on the subtopology level." },
+            { "name": "SourceTopicRegex", "type": "[]int16", "versions": "0+",
+              "about": "Regular expressions identifying topics the subtopology reads from. Index into the array on the subtopology level." },
+            { "name": "RepartitionSourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The set of source topics that are internally created repartition topics. Index into the array on the subtopology level." }
+          ]
+        }
       ]
     }
   ],
@@ -56,7 +67,9 @@
         "about": "The name of the topic." },
       { "name": "Partitions", "type": "int32", "versions": "0+",
         "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
-      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      { "name": "ReplicationFactor", "type": "int16", "versions": "0+",
+        "about": "The replication factor of the topic. Can be 0 if the default replication factor should be used." },
+      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+",
         "about": "Topic-level configurations as key-value pairs."
       }
     ]}
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index f4e5d814a57..91b9b5ae45a 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -107,12 +107,8 @@ class StreamsGroupHeartbeatRequestManagerTest {
 
     private final StreamsAssignmentInterface.HostInfo endPoint = new StreamsAssignmentInterface.HostInfo("localhost", 8080);
 
-    private final String assignor = "test";
-
     private final Map<String, Subtopology> subtopologyMap = new HashMap<>();
 
-    private final Map<String, Object> assignmentConfiguration = new HashMap<>();
-
     private final Map<String, String> clientTags = new HashMap<>();
 
     private final Node coordinatorNode = new Node(1, "localhost", 9092);
@@ -122,15 +118,12 @@ class StreamsGroupHeartbeatRequestManagerTest {
         config = config();
 
         subtopologyMap.clear();
-        assignmentConfiguration.clear();
         clientTags.clear();
         streamsAssignmentInterface =
             new StreamsAssignmentInterface(
                 processID,
                 Optional.of(endPoint),
-                assignor,
                 subtopologyMap,
-                assignmentConfiguration,
                 clientTags
             );
         LogContext logContext = new LogContext("test");
@@ -205,7 +198,6 @@ class StreamsGroupHeartbeatRequestManagerTest {
     @Test
     void testFullStaticInformationWhenJoining() {
         mockJoiningState();
-        assignmentConfiguration.put("config1", "value1");
         clientTags.put("clientTag1", "value2");
 
         NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
@@ -245,7 +237,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
         final Uuid uuid0 = Uuid.randomUuid();
         final Uuid uuid1 = Uuid.randomUuid();
 
-        final TopicInfo emptyTopicInfo = new TopicInfo(Optional.empty(), Collections.emptyMap());
+        final TopicInfo emptyTopicInfo = new TopicInfo(Optional.empty(), Optional.empty(), Collections.emptyMap());
 
         when(metadata.topicIds()).thenReturn(
             mkMap(
@@ -258,21 +250,24 @@ class StreamsGroupHeartbeatRequestManagerTest {
                 Collections.singleton("source0"),
                 Collections.singleton("sink0"),
                 Collections.singletonMap("repartition0", emptyTopicInfo),
-                Collections.singletonMap("changelog0", emptyTopicInfo)
+                Collections.singletonMap("changelog0", emptyTopicInfo),
+                Collections.singletonList(mkSet("source0", "repartition0"))
             ));
         streamsAssignmentInterface.subtopologyMap().put("1",
             new Subtopology(
                 Collections.singleton("source1"),
                 Collections.singleton("sink1"),
                 Collections.singletonMap("repartition1", emptyTopicInfo),
-                Collections.singletonMap("changelog1", emptyTopicInfo)
+                Collections.singletonMap("changelog1", emptyTopicInfo),
+                Collections.singletonList(mkSet("source1", "repartition1"))
             ));
         streamsAssignmentInterface.subtopologyMap().put("2",
             new Subtopology(
                 Collections.singleton("source2"),
                 Collections.singleton("sink2"),
                 Collections.singletonMap("repartition2", emptyTopicInfo),
-                Collections.singletonMap("changelog2", emptyTopicInfo)
+                Collections.singletonMap("changelog2", emptyTopicInfo),
+                Collections.singletonList(mkSet("source2", "repartition2"))
             ));
 
         StreamsGroupHeartbeatResponseData data = new StreamsGroupHeartbeatResponseData()
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index 11c92389f6a..f5bc091e7b0 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -26,7 +26,8 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.junit.jupiter.MockitoExtension;
 
-import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -73,19 +74,24 @@ class StreamsGroupInitializeRequestManagerTest {
         final Set<String> sourceTopics = mkSet("sourceTopic1", "sourceTopic2");
         final Set<String> sinkTopics = mkSet("sinkTopic1", "sinkTopic2", "sinkTopic3");
         final Map<String, StreamsAssignmentInterface.TopicInfo> repartitionTopics = mkMap(
-            mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Collections.emptyMap())),
-            mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Collections.emptyMap()))
+            mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Optional.of((short) 1), Collections.emptyMap())),
+            mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Optional.of((short) 3), Collections.emptyMap()))
         );
         final Map<String, StreamsAssignmentInterface.TopicInfo> changelogTopics = mkMap(
-            mkEntry("changelogTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap())),
-            mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap())),
-            mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap()))
+            mkEntry("changelogTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 1), Collections.emptyMap())),
+            mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 2), Collections.emptyMap())),
+            mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 3), Collections.emptyMap()))
+        );
+        final Collection<Set<String>> copartitionGroup = mkSet(
+            mkSet("sourceTopic1", "repartitionTopic2"),
+            mkSet("sourceTopic2", "repartitionTopic1")
         );
         final StreamsAssignmentInterface.Subtopology subtopology1 = new StreamsAssignmentInterface.Subtopology(
             sourceTopics,
             sinkTopics,
             repartitionTopics,
-            changelogTopics
+            changelogTopics,
+            copartitionGroup
         );
         final String subtopologyName1 = "subtopology1";
         when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
@@ -116,17 +122,28 @@ class StreamsGroupInitializeRequestManagerTest {
         assertEquals(1, subtopologies.size());
         final StreamsGroupInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
         assertEquals(subtopologyName1, subtopology.subtopologyId());
-        assertEquals(new ArrayList<>(sourceTopics), subtopology.sourceTopics());
-        assertEquals(new ArrayList<>(sinkTopics), subtopology.repartitionSinkTopics());
+        assertEquals(Arrays.asList("sourceTopic1", "sourceTopic2"), subtopology.sourceTopics());
+        assertEquals(Arrays.asList("sinkTopic1", "sinkTopic2", "sinkTopic3"), subtopology.repartitionSinkTopics());
         assertEquals(repartitionTopics.size(), subtopology.repartitionSourceTopics().size());
         subtopology.repartitionSourceTopics().forEach(topicInfo -> {
             final StreamsAssignmentInterface.TopicInfo repartitionTopic = repartitionTopics.get(topicInfo.name());
             assertEquals(repartitionTopic.numPartitions.get(), topicInfo.partitions());
+            assertEquals(repartitionTopic.replicationFactor.get(), topicInfo.replicationFactor());
         });
         assertEquals(changelogTopics.size(), subtopology.stateChangelogTopics().size());
         subtopology.stateChangelogTopics().forEach(topicInfo -> {
             assertTrue(changelogTopics.containsKey(topicInfo.name()));
             assertEquals(0, topicInfo.partitions());
+            final StreamsAssignmentInterface.TopicInfo changelogTopic = changelogTopics.get(topicInfo.name());
+            assertEquals(changelogTopic.replicationFactor.get(), topicInfo.replicationFactor());
         });
+
+        assertEquals(2, subtopology.copartitionGroups().size());
+        final StreamsGroupInitializeRequestData.CopartitionGroup copartitionGroupData1 = subtopology.copartitionGroups().get(0);
+        assertEquals(Collections.singletonList((short) 0), copartitionGroupData1.sourceTopics());
+        assertEquals(Collections.singletonList((short) 1), copartitionGroupData1.repartitionSourceTopics());
+        final StreamsGroupInitializeRequestData.CopartitionGroup copartitionGroupData2 = subtopology.copartitionGroups().get(1);
+        assertEquals(Collections.singletonList((short) 1), copartitionGroupData2.sourceTopics());
+        assertEquals(Collections.singletonList((short) 0), copartitionGroupData2.repartitionSourceTopics());
     }
 }
\ No newline at end of file
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index a8f742f0d26..f613d11c8f3 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -216,6 +216,7 @@ import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.CONSUMER_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.STREAMS_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember.hasAssignedPartitionsChanged;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.convertToStreamsGroupTopologyRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord;
@@ -2696,6 +2697,8 @@ public class GroupMetadataManager {
             }
         }
 
+        StreamsGroupTopologyValue recordValue = convertToStreamsGroupTopologyRecord(subtopologies);
+
         cancelStreamsGroupTopologyInitializationTimeout(groupId, topologyId);
 
         if (!missingTopics.isEmpty()) {
@@ -2706,9 +2709,12 @@ public class GroupMetadataManager {
 
             return new CoordinatorResult<>(records, response);
         } else {
-            records.add(newStreamsGroupTopologyRecord(groupId, subtopologies));
+            records.add(newStreamsGroupTopologyRecord(groupId, recordValue));
+
+            final Map<String, StreamsGroupTopologyValue.Subtopology> subtopologyMap = recordValue.topology().stream()
+                .collect(Collectors.toMap(StreamsGroupTopologyValue.Subtopology::subtopologyId, x -> x));
 
-            final StreamsTopology topology = new StreamsTopology(topologyId, subtopologies);
+            final StreamsTopology topology = new StreamsTopology(topologyId, subtopologyMap);
 
             computeFirstTargetAssignmentAfterTopologyInitialization(group, records, topology);
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 7a7ee7f2ae2..532955f87aa 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -381,28 +381,17 @@ public class CoordinatorStreamsRecordHelpers {
      */
     public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
                                                                   List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
-        StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
-        subtopologies.forEach(subtopology -> {
-            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
-                .map(topicInfo -> {
-                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                        .collect(Collectors.toList()) : null;
-                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
-                        .setPartitions(topicInfo.partitions());
-                }).collect(Collectors.toList());
-
-            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
-                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                    .collect(Collectors.toList()) : null;
-                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
-            }).collect(Collectors.toList());
+        return newStreamsGroupTopologyRecord(groupId, convertToStreamsGroupTopologyRecord(subtopologies));
+    }
 
-            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopologyId(subtopology.subtopologyId())
-                .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
-                .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
-        });
+    /**
+     * Creates a StreamsTopology record.
+     *
+     * @param groupId       The consumer group id.
+     * @param value         The encoded topology record value.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId, StreamsGroupTopologyValue value) {
 
         return new CoordinatorRecord(new ApiMessageAndVersion(
             new StreamsGroupTopologyKey()
@@ -411,6 +400,59 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(value, (short) 0));
     }
 
+    /**
+     * Encodes subtopologies from the initialize RPC to a StreamsTopology record value.
+     *
+     * @param subtopologies The subtopologies in the new topology.
+     * @return The record value.
+     */
+    public static StreamsGroupTopologyValue convertToStreamsGroupTopologyRecord(List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
+        StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
+        subtopologies.forEach(subtopology -> {
+            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics =
+                subtopology.repartitionSourceTopics().stream()
+                    .map(CoordinatorStreamsRecordHelpers::convertToTopicInfo)
+                    .collect(Collectors.toList());
+
+            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics =
+                subtopology.stateChangelogTopics().stream()
+                    .map(CoordinatorStreamsRecordHelpers::convertToTopicInfo)
+                    .collect(Collectors.toList());
+
+            List<StreamsGroupTopologyValue.CopartitionGroup> copartitionGroups =
+                subtopology.copartitionGroups().stream()
+                    .map(copartitionGroup -> new StreamsGroupTopologyValue.CopartitionGroup()
+                        .setSourceTopics(copartitionGroup.sourceTopics())
+                        .setSourceTopicRegex(copartitionGroup.sourceTopicRegex())
+                        .setRepartitionSourceTopics(copartitionGroup.repartitionSourceTopics())
+                    )
+                    .collect(Collectors.toList());
+
+            value.topology().add(
+                new StreamsGroupTopologyValue.Subtopology()
+                    .setSubtopologyId(subtopology.subtopologyId())
+                    .setSourceTopics(subtopology.sourceTopics())
+                    .setSourceTopicRegex(subtopology.sourceTopicRegex())
+                    .setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
+                    .setRepartitionSourceTopics(repartitionSourceTopics)
+                    .setStateChangelogTopics(stateChangelogTopics)
+                    .setCopartitionGroups(copartitionGroups)
+            );
+        });
+        return value;
+    }
+
+    private static StreamsGroupTopologyValue.TopicInfo convertToTopicInfo(StreamsGroupInitializeRequestData.TopicInfo topicInfo) {
+        List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+            .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+            .collect(Collectors.toList()) : null;
+        return new StreamsGroupTopologyValue.TopicInfo()
+            .setName(topicInfo.name())
+            .setTopicConfigs(topicConfigs)
+            .setPartitions(topicInfo.partitions())
+            .setReplicationFactor(topicInfo.replicationFactor());
+    }
+
     /**
      * Creates a StreamsGroupTopology tombstone.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 27f138be05f..408f0bfcbb4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -17,12 +17,10 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
-import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
 
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -45,35 +43,6 @@ public class StreamsTopology {
         this.subtopologies = subtopologies;
     }
 
-    public StreamsTopology(final String topologyId,
-                           final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
-        this.topologyId = topologyId;
-        this.subtopologies = new HashMap<>();
-        subtopologies.forEach(subtopology -> {
-            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
-                .map(topicInfo -> {
-                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                        .collect(Collectors.toList()) : null;
-                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
-                        .setPartitions(topicInfo.partitions());
-                }).collect(Collectors.toList());
-
-            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
-                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
-                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                    .collect(Collectors.toList()) : null;
-                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
-            }).collect(Collectors.toList());
-
-            this.subtopologies.put(
-                subtopology.subtopologyId(),
-                new StreamsGroupTopologyValue.Subtopology().setSubtopologyId(subtopology.subtopologyId())
-                    .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
-                    .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
-        });
-    }
-
     public String topologyId() {
         return topologyId;
     }
@@ -141,6 +110,7 @@ public class StreamsTopology {
             new StreamsGroupDescribeResponseData.TopicInfo()
                 .setName(x.name())
                 .setPartitions(x.partitions())
+                .setReplicationFactor(x.replicationFactor())
                 .setTopicConfigs(
                     x.topicConfigs() != null ?
                         x.topicConfigs().stream().map(
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
index af1fae06aad..d89ed3ed393 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
@@ -29,14 +29,25 @@
           "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
-        { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-          "about": "The regular expressions identifying topics the topology reads from. null if not provided." },
+        { "name": "SourceTopicRegex", "type": "[]string", "versions": "0+",
+          "about": "Regular expressions identifying topics the sub-topology reads from." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of state changelog topics associated with this subtopology. " },
+          "about": "The set of state changelog topics associated with this sub-topology." },
         { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
           "about": "The repartition topics the subtopology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of source topics that are internally created repartition topics. " }
+          "about": "The set of source topics that are internally created repartition topics." },
+        { "name": "CopartitionGroups", "type": "[]CopartitionGroup", "versions": "0+",
+          "about": "A subset of source topics that must be copartitioned.",
+          "fields": [
+            { "name": "SourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The topics the topology reads from. Index into the array on the subtopology level." },
+            { "name": "SourceTopicRegex", "type": "[]int16", "versions": "0+",
+              "about": "Regular expressions identifying topics the subtopology reads from. Index into the array on the subtopology level." },
+            { "name": "RepartitionSourceTopics", "type": "[]int16", "versions": "0+",
+              "about": "The set of source topics that are internally created repartition topics. Index into the array on the subtopology level." }
+          ]
+        }
       ]
     }
   ],
@@ -53,7 +64,9 @@
         "about": "The name of the topic." },
       { "name": "Partitions", "type": "int32", "versions": "0+",
         "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
-      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      { "name": "ReplicationFactor", "type": "int16", "versions": "0+",
+        "about": "The replication factor of the topic. Can be 0 if the default replication factor should be used." },
+      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+",
         "about": "Topic-level configurations as key-value pairs."
       }
     ]}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 7ddbc832d80..65ad8d43fa8 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -24,6 +24,7 @@ import org.apache.kafka.server.common.ApiMessageAndVersion;
 
 import org.junit.jupiter.api.Test;
 
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 
@@ -38,11 +39,13 @@ class CoordinatorStreamsRecordHelpersTest {
                 .setSubtopologyId("subtopology-id")
                 .setRepartitionSinkTopics(Collections.singletonList("foo"))
                 .setSourceTopics(Collections.singletonList("bar"))
+                .setSourceTopicRegex(Collections.singletonList("regex"))
                 .setRepartitionSourceTopics(
                     Collections.singletonList(
                         new StreamsGroupInitializeRequestData.TopicInfo()
                             .setName("repartition")
                             .setPartitions(4)
+                            .setReplicationFactor((short) 3)
                             .setTopicConfigs(Collections.singletonList(
                                 new StreamsGroupInitializeRequestData.TopicConfig()
                                     .setKey("config-name1")
@@ -54,6 +57,7 @@ class CoordinatorStreamsRecordHelpersTest {
                     Collections.singletonList(
                         new StreamsGroupInitializeRequestData.TopicInfo()
                             .setName("changelog")
+                            .setReplicationFactor((short) 2)
                             .setTopicConfigs(Collections.singletonList(
                                 new StreamsGroupInitializeRequestData.TopicConfig()
                                     .setKey("config-name2")
@@ -61,6 +65,13 @@ class CoordinatorStreamsRecordHelpersTest {
                             ))
                     )
                 )
+                .setCopartitionGroups(Arrays.asList(
+                    new StreamsGroupInitializeRequestData.CopartitionGroup()
+                        .setSourceTopics(Collections.singletonList((short) 0))
+                        .setRepartitionSourceTopics(Collections.singletonList((short) 0)),
+                    new StreamsGroupInitializeRequestData.CopartitionGroup()
+                        .setSourceTopicRegex(Collections.singletonList((short) 0))
+                ))
             );
 
         List<StreamsGroupTopologyValue.Subtopology> expectedTopology =
@@ -68,11 +79,13 @@ class CoordinatorStreamsRecordHelpersTest {
                 .setSubtopologyId("subtopology-id")
                 .setRepartitionSinkTopics(Collections.singletonList("foo"))
                 .setSourceTopics(Collections.singletonList("bar"))
+                .setSourceTopicRegex(Collections.singletonList("regex"))
                 .setRepartitionSourceTopics(
                     Collections.singletonList(
                         new StreamsGroupTopologyValue.TopicInfo()
                             .setName("repartition")
                             .setPartitions(4)
+                            .setReplicationFactor((short) 3)
                             .setTopicConfigs(Collections.singletonList(
                                 new StreamsGroupTopologyValue.TopicConfig()
                                     .setKey("config-name1")
@@ -84,6 +97,7 @@ class CoordinatorStreamsRecordHelpersTest {
                     Collections.singletonList(
                         new StreamsGroupTopologyValue.TopicInfo()
                             .setName("changelog")
+                            .setReplicationFactor((short) 2)
                             .setTopicConfigs(Collections.singletonList(
                                 new StreamsGroupTopologyValue.TopicConfig()
                                     .setKey("config-name2")
@@ -91,6 +105,13 @@ class CoordinatorStreamsRecordHelpersTest {
                             ))
                     )
                 )
+                .setCopartitionGroups(Arrays.asList(
+                    new StreamsGroupTopologyValue.CopartitionGroup()
+                        .setSourceTopics(Collections.singletonList((short) 0))
+                        .setRepartitionSourceTopics(Collections.singletonList((short) 0)),
+                    new StreamsGroupTopologyValue.CopartitionGroup()
+                        .setSourceTopicRegex(Collections.singletonList((short) 0))
+                ))
             );
 
         CoordinatorRecord expectedRecord = new CoordinatorRecord(
@@ -108,4 +129,5 @@ class CoordinatorStreamsRecordHelpersTest {
             topology
         ));
     }
+
 }
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
index e83abcbfe7c..7aa303603ab 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -145,40 +145,60 @@ public class StreamsTopologyTest {
     public void asStreamsGroupDescribeTopologyShouldReturnCorrectSubtopologies() {
         Map<String, Subtopology> subtopologies = mkMap(
             mkEntry("subtopology-1", new Subtopology()
-                .setSourceTopicRegex("regex-1")
+                .setSourceTopicRegex(Collections.singletonList("regex-1"))
                 .setSubtopologyId("subtopology-1")
                 .setSourceTopics(Collections.singletonList("source-topic-1"))
                 .setRepartitionSinkTopics(Collections.singletonList("sink-topic-1"))
                 .setRepartitionSourceTopics(
-                    Collections.singletonList(new TopicInfo().setName("repartition-topic-1")))
+                    Collections.singletonList(new TopicInfo()
+                        .setName("repartition-topic-1")
+                        .setReplicationFactor((short) 3)
+                        .setPartitions(2)))
                 .setStateChangelogTopics(
-                    Collections.singletonList(new TopicInfo().setName("changelog-topic-1")))
+                    Collections.singletonList(new TopicInfo()
+                        .setName("changelog-topic-1")
+                        .setReplicationFactor((short) 2)
+                        .setPartitions(1)))
             ),
             mkEntry("subtopology-2", new Subtopology()
-                .setSourceTopicRegex("regex-2")
+                .setSourceTopicRegex(Collections.singletonList("regex-2"))
                 .setSubtopologyId("subtopology-2")
                 .setSourceTopics(Collections.singletonList("source-topic-2"))
                 .setRepartitionSinkTopics(Collections.singletonList("sink-topic-2"))
                 .setRepartitionSourceTopics(
-                    Collections.singletonList(new TopicInfo().setName("repartition-topic-2")))
+                    Collections.singletonList(new TopicInfo()
+                        .setName("repartition-topic-2")
+                        .setReplicationFactor((short) 3)
+                        .setPartitions(2)))
                 .setStateChangelogTopics(
-                    Collections.singletonList(new TopicInfo().setName("changelog-topic-2")))
+                    Collections.singletonList(new TopicInfo()
+                        .setName("changelog-topic-2")
+                        .setReplicationFactor((short) 2)
+                        .setPartitions(1)))
             )
         );
         StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
         List<StreamsGroupDescribeResponseData.Subtopology> result = topology.asStreamsGroupDescribeTopology();
         assertEquals(2, result.size());
-        assertEquals("regex-1", result.get(0).sourceTopicRegex());
+        assertEquals(Collections.singletonList("regex-1"), result.get(0).sourceTopicRegex());
         assertEquals("subtopology-1", result.get(0).subtopologyId());
         assertEquals(Collections.singletonList("source-topic-1"), result.get(0).sourceTopics());
         assertEquals(Collections.singletonList("sink-topic-1"), result.get(0).repartitionSinkTopics());
         assertEquals("repartition-topic-1", result.get(0).repartitionSourceTopics().get(0).name());
+        assertEquals((short) 3, result.get(0).repartitionSourceTopics().get(0).replicationFactor());
+        assertEquals(2, result.get(0).repartitionSourceTopics().get(0).partitions());
         assertEquals("changelog-topic-1", result.get(0).stateChangelogTopics().get(0).name());
-        assertEquals("regex-2", result.get(1).sourceTopicRegex());
+        assertEquals((short) 2, result.get(0).stateChangelogTopics().get(0).replicationFactor());
+        assertEquals(1, result.get(0).stateChangelogTopics().get(0).partitions());
+        assertEquals(Collections.singletonList("regex-2"), result.get(1).sourceTopicRegex());
         assertEquals("subtopology-2", result.get(1).subtopologyId());
         assertEquals(Collections.singletonList("source-topic-2"), result.get(1).sourceTopics());
         assertEquals(Collections.singletonList("sink-topic-2"), result.get(1).repartitionSinkTopics());
         assertEquals("repartition-topic-2", result.get(1).repartitionSourceTopics().get(0).name());
+        assertEquals((short) 3, result.get(1).repartitionSourceTopics().get(0).replicationFactor());
+        assertEquals(2, result.get(1).repartitionSourceTopics().get(0).partitions());
         assertEquals("changelog-topic-2", result.get(1).stateChangelogTopics().get(0).name());
+        assertEquals((short) 2, result.get(1).stateChangelogTopics().get(0).replicationFactor());
+        assertEquals(1, result.get(1).stateChangelogTopics().get(0).partitions());
     }
 }
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index 0b69a099663..27e709490be 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -73,6 +73,7 @@ import org.slf4j.Logger;
 
 import java.time.Duration;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
@@ -558,9 +559,38 @@ public class StreamThread extends Thread implements ProcessingThread {
                                                                       final TopologyMetadata topologyMetadata) {
         final InternalTopologyBuilder internalTopologyBuilder = topologyMetadata.lookupBuilderForNamedTopology(null);
 
+        final Map<String, Subtopology> subtopologyMap = initBrokerTopology(config, internalTopologyBuilder);
+
+        return new StreamsAssignmentInterface(
+            processId,
+            endpoint,
+            subtopologyMap,
+            config.getClientTags()
+        );
+    }
+
+    private static Map<String, Subtopology> initBrokerTopology(final StreamsConfig config, final InternalTopologyBuilder internalTopologyBuilder) {
+        final Map<String, String> defaultTopicConfigs = new HashMap<>();
+        for (final Map.Entry<String, Object> entry : config.originalsWithPrefix(StreamsConfig.TOPIC_PREFIX).entrySet()) {
+            if (entry.getValue() != null) {
+                defaultTopicConfigs.put(entry.getKey(), entry.getValue().toString());
+            }
+        }
+        final long windowChangeLogAdditionalRetention = config.getLong(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG);
+
         final Map<String, Subtopology> subtopologyMap = new HashMap<>();
+        final Collection<Set<String>> copartitionGroups = internalTopologyBuilder.copartitionGroups();
+
         for (final Map.Entry<TopologyMetadata.Subtopology, TopicsInfo> topicsInfoEntry : internalTopologyBuilder.subtopologyToTopicsInfo()
             .entrySet()) {
+
+            final HashSet<String> allSourceTopics = new HashSet<>(
+                topicsInfoEntry.getValue().sourceTopics);
+            topicsInfoEntry.getValue().repartitionSourceTopics.forEach(
+                (repartitionSourceTopic, repartitionTopicInfo) -> {
+                    allSourceTopics.add(repartitionSourceTopic);
+                });
+
             subtopologyMap.put(
                 String.valueOf(topicsInfoEntry.getKey().nodeGroupId),
                 new Subtopology(
@@ -569,44 +599,28 @@ public class StreamThread extends Thread implements ProcessingThread {
                     topicsInfoEntry.getValue().repartitionSourceTopics.entrySet()
                         .stream()
                         .collect(Collectors.toMap(Map.Entry::getKey, e ->
-                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs))),
+                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(),
+                                Optional.of(config.getInt(StreamsConfig.REPLICATION_FACTOR_CONFIG).shortValue()),
+                                e.getValue().properties(defaultTopicConfigs, windowChangeLogAdditionalRetention)))),
                     topicsInfoEntry.getValue().stateChangelogTopics.entrySet()
                         .stream()
                         .collect(Collectors.toMap(Map.Entry::getKey, e ->
-                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs)))
-
+                            new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(),
+                                Optional.of(config.getInt(StreamsConfig.REPLICATION_FACTOR_CONFIG).shortValue()),
+                                e.getValue().properties(defaultTopicConfigs, windowChangeLogAdditionalRetention)))),
+                    copartitionGroups.stream().filter(allSourceTopics::containsAll).collect(
+                        Collectors.toList())
                 )
             );
         }
 
-        // TODO: Which of these are actually needed?
-        // TODO: Maybe we want to split this into assignment properties and internal topic configuration properties
-        final HashMap<String, Object> assignmentProperties = new HashMap<>();
-        assignmentProperties.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, config.getInt(StreamsConfig.REPLICATION_FACTOR_CONFIG));
-        assignmentProperties.put(StreamsConfig.APPLICATION_SERVER_CONFIG, config.getString(StreamsConfig.APPLICATION_SERVER_CONFIG));
-        assignmentProperties.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, config.getInt(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG));
-        assignmentProperties.put(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG,
-            config.getLong(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG));
-        assignmentProperties.put(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG, config.getInt(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG));
-        assignmentProperties.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG,
-            config.getLong(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG,
-            config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG,
-            config.getString(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG,
-            config.getList(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG,
-            config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG));
+        if (subtopologyMap.values().stream().mapToInt(x -> x.copartitionGroups.size()).sum()
+            != copartitionGroups.size()) {
+            throw new IllegalStateException(
+                "Not all copartition groups were converted to broker topology");
+        }
 
-        return new StreamsAssignmentInterface(
-            processId,
-            endpoint,
-            null,
-            subtopologyMap,
-            assignmentProperties,
-            config.getClientTags()
-        );
+        return subtopologyMap;
     }
 
     private static DefaultTaskManager maybeCreateSchedulingTaskManager(final boolean processingThreadsEnabled,


(kafka) 07/42: Minor: Test fixes

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 8f22f7a618193c11fcb5024ba8c382539831061e
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Tue May 28 18:17:03 2024 +0200

    Minor: Test fixes
    
    Fixed some tests and some actual bugs. Added missing request parsing.
    
    See https://github.com/lucasbru/kafka/pull/13
---
 .../internals/StreamsInitializeRequestManager.java | 10 ++---
 .../kafka/common/requests/AbstractRequest.java     |  4 ++
 .../kafka/common/requests/AbstractResponse.java    |  4 ++
 .../common/requests/StreamsInitializeRequest.java  |  2 +-
 .../common/requests/StreamsInitializeResponse.java |  2 +-
 .../StreamsInitializeRequestManagerTest.java       |  4 +-
 .../kafka/common/requests/RequestResponseTest.java | 43 ++++++++++++++++++++++
 7 files changed, 60 insertions(+), 9 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
index 34f9fee96f7..5d19d8a8e50 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -76,16 +76,16 @@ public class StreamsInitializeRequestManager implements RequestManager {
     }
 
     private List<StreamsInitializeRequestData.Subtopology> getTopologyFromStreams() {
-        final Map<String, StreamsAssignmentInterface.SubTopology> subTopologyMap = streamsAssignmentInterface.subtopologyMap();
+        final Map<String, StreamsAssignmentInterface.Subtopology> subTopologyMap = streamsAssignmentInterface.subtopologyMap();
         final List<StreamsInitializeRequestData.Subtopology> topology = new ArrayList<>(subTopologyMap.size());
-        for (final Map.Entry<String, StreamsAssignmentInterface.SubTopology> subtopology : subTopologyMap.entrySet()) {
+        for (final Map.Entry<String, StreamsAssignmentInterface.Subtopology> subtopology : subTopologyMap.entrySet()) {
             topology.add(getSubtopologyFromStreams(subtopology.getKey(), subtopology.getValue()));
         }
         return topology;
     }
 
     private static StreamsInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
-                                                                                      final StreamsAssignmentInterface.SubTopology subtopology) {
+                                                                                      final StreamsAssignmentInterface.Subtopology subtopology) {
         final StreamsInitializeRequestData.Subtopology subtopologyData = new StreamsInitializeRequestData.Subtopology();
         subtopologyData.setSubtopology(subtopologyName);
         subtopologyData.setSourceTopics(new ArrayList<>(subtopology.sourceTopics));
@@ -95,7 +95,7 @@ public class StreamsInitializeRequestManager implements RequestManager {
         return subtopologyData;
     }
 
-    private static List<StreamsInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.SubTopology subtopologyDataFromStreams) {
+    private static List<StreamsInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
         final List<StreamsInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
             final StreamsInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsInitializeRequestData.TopicInfo();
@@ -106,7 +106,7 @@ public class StreamsInitializeRequestManager implements RequestManager {
         return repartitionTopicsInfo;
     }
 
-    private static List<StreamsInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.SubTopology subtopologyDataFromStreams) {
+    private static List<StreamsInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.Subtopology subtopologyDataFromStreams) {
         final List<StreamsInitializeRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
         for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
             final StreamsInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsInitializeRequestData.TopicInfo();
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
index 87a7a826869..e0cb5e97b5d 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
@@ -350,6 +350,10 @@ public abstract class AbstractRequest implements AbstractRequestResponse {
                 return DeleteShareGroupStateRequest.parse(buffer, apiVersion);
             case READ_SHARE_GROUP_STATE_SUMMARY:
                 return ReadShareGroupStateSummaryRequest.parse(buffer, apiVersion);
+            case STREAMS_HEARTBEAT:
+                return StreamsHeartbeatRequest.parse(buffer, apiVersion);
+            case STREAMS_INITIALIZE:
+                return StreamsInitializeRequest.parse(buffer, apiVersion);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseRequest`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
index 83f29471ba3..cc3d3384a27 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
@@ -287,6 +287,10 @@ public abstract class AbstractResponse implements AbstractRequestResponse {
                 return DeleteShareGroupStateResponse.parse(responseBuffer, version);
             case READ_SHARE_GROUP_STATE_SUMMARY:
                 return ReadShareGroupStateSummaryResponse.parse(responseBuffer, version);
+            case STREAMS_HEARTBEAT:
+                return StreamsHeartbeatResponse.parse(responseBuffer, version);
+            case STREAMS_INITIALIZE:
+                return StreamsInitializeResponse.parse(responseBuffer, version);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseResponse`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
index 83761d805de..5f150053798 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
@@ -52,7 +52,7 @@ public class StreamsInitializeRequest extends AbstractRequest {
     private final StreamsInitializeRequestData data;
 
     public StreamsInitializeRequest(StreamsInitializeRequestData data, short version) {
-        super(ApiKeys.STREAMS_HEARTBEAT, version);
+        super(ApiKeys.STREAMS_INITIALIZE, version);
         this.data = data;
     }
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
index 81c281aba98..050b28b02af 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
@@ -40,7 +40,7 @@ public class StreamsInitializeResponse extends AbstractResponse {
     private final StreamsInitializeResponseData data;
 
     public StreamsInitializeResponse(StreamsInitializeResponseData data) {
-        super(ApiKeys.STREAMS_HEARTBEAT);
+        super(ApiKeys.STREAMS_INITIALIZE);
         this.data = data;
     }
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
index bb734a7b1f5..6aebd48efec 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
@@ -80,9 +80,9 @@ class StreamsInitializeRequestManagerTest {
             mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap())),
             mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap()))
         );
-        final StreamsAssignmentInterface.SubTopology subtopology1 = new StreamsAssignmentInterface.SubTopology(
-            sinkTopics,
+        final StreamsAssignmentInterface.Subtopology subtopology1 = new StreamsAssignmentInterface.Subtopology(
             sourceTopics,
+            sinkTopics,
             repartitionTopics,
             changelogTopics
         );
diff --git a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
index cb6a2458261..da4ae96af47 100644
--- a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
@@ -234,6 +234,14 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaPartitionState;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaTopicState;
 import org.apache.kafka.common.message.StopReplicaResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
+import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -1123,6 +1131,8 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateRequest(version);
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateRequest(version);
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryRequest(version);
+            case STREAMS_HEARTBEAT: return createStreamsHeartbeatRequest(version);
+            case STREAMS_INITIALIZE: return createStreamsInitializeRequest(version);
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -1217,6 +1227,8 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateResponse();
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateResponse();
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryResponse();
+            case STREAMS_HEARTBEAT: return createStreamsHeartbeatResponse();
+            case STREAMS_INITIALIZE: return createStreamsInitializeResponse();
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -4015,6 +4027,37 @@ public class RequestResponseTest {
         return new ReadShareGroupStateSummaryResponse(data);
     }
 
+    private AbstractRequest createStreamsPrepareAssignmentRequest(final short version) {
+        return new StreamsPrepareAssignmentRequest.Builder(new StreamsPrepareAssignmentRequestData()).build(version);
+    }
+
+    private AbstractRequest createStreamsInstallAssignmentRequest(final short version) {
+        return new StreamsInstallAssignmentRequest.Builder(new StreamsInstallAssignmentRequestData()).build(version);
+    }
+
+    private AbstractRequest createStreamsInitializeRequest(final short version) {
+        return new StreamsInitializeRequest.Builder(new StreamsInitializeRequestData()).build(version);
+    }
+
+    private AbstractRequest createStreamsHeartbeatRequest(final short version) {
+        return new StreamsHeartbeatRequest.Builder(new StreamsHeartbeatRequestData()).build(version);
+    }
+
+    private AbstractResponse createStreamsPrepareAssignmentResponse() {
+        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData());
+    }
+
+    private AbstractResponse createStreamsInstallAssignmentResponse() {
+        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData());
+    }
+
+    private AbstractResponse createStreamsInitializeResponse() {
+        return new StreamsInitializeResponse(new StreamsInitializeResponseData());
+    }
+
+    private AbstractResponse createStreamsHeartbeatResponse() {
+        return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData());
+
     @Test
     public void testInvalidSaslHandShakeRequest() {
         AbstractRequest request = new SaslHandshakeRequest.Builder(


(kafka) 29/42: KAFKA-17125: finalize TaskId (#17300)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit deb38899cc9bdb9582974d48054c348699fa0401
Author: Alieh Saeedi <10...@users.noreply.github.com>
AuthorDate: Wed Oct 2 14:37:49 2024 +0200

    KAFKA-17125: finalize TaskId (#17300)
---
 .../org/apache/kafka/coordinator/group/taskassignor/TaskId.java  | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
index 885858f700d..8991aeb11ca 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
@@ -18,12 +18,13 @@ package org.apache.kafka.coordinator.group.taskassignor;
 
 import java.util.Objects;
 
-public final class TaskId {
+public final class TaskId implements Comparable<TaskId> {
 
     private final String subtopologyId;
     private final int partition;
 
     public TaskId(final String subtopologyId, final int partition) {
+        Objects.requireNonNull(subtopologyId);
         this.subtopologyId = subtopologyId;
         this.partition = partition;
     }
@@ -65,6 +66,10 @@ public final class TaskId {
     }
 
     public int compareTo(final TaskId other) {
-        return this.hashCode() - other.hashCode();
+        int diff = subtopologyId.compareTo(other.subtopologyId);
+        if (diff == 0) {
+            diff = partition - other.partition;
+        }
+        return diff;
     }
 }


(kafka) 09/42: Resolve merge conflict from 11/25 trunk rebase Implement InitStreamsApp RPC in the group coordinator

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit c1a597b211e1583ec9a12020b3c45e4d7030cc36
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Mon Jun 3 17:23:43 2024 +0200

    Resolve merge conflict from 11/25 trunk rebase Implement InitStreamsApp RPC in the group coordinator
    
    Implement init streams app call in group coordinator without creating internal topics.
    
    Create topology metadata record
    Verify existence of all required internal topics
    
    See https://github.com/lucasbru/kafka/pull/15
---
 .../group/GroupCoordinatorAdapter.scala            |  11 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   |  28 +++++
 .../group/GroupCoordinatorAdapterTest.scala        |  18 ++-
 .../scala/unit/kafka/server/KafkaApisTest.scala    |  62 +++++++++
 .../kafka/coordinator/group/GroupCoordinator.java  |  16 +++
 .../group/GroupCoordinatorRecordHelpers.java       |  42 +++++++
 .../coordinator/group/GroupCoordinatorService.java |  31 +++++
 .../coordinator/group/GroupCoordinatorShard.java   |  18 +++
 .../coordinator/group/GroupMetadataManager.java    | 116 +++++++++++++++++
 .../group/GroupCoordinatorRecordHelpersTest.java   |  82 ++++++++++++
 .../group/GroupCoordinatorServiceTest.java         | 115 +++++++++++++++++
 .../group/GroupCoordinatorShardTest.java           |  34 +++++
 .../group/GroupMetadataManagerTest.java            | 140 +++++++++++++++++++++
 .../group/GroupMetadataManagerTestContext.java     |  42 +++++++
 14 files changed, 753 insertions(+), 2 deletions(-)

diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index 970d283953e..d45221d1e71 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,7 +18,7 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
@@ -77,6 +77,15 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
+  override def streamsInitialize(
+                                   context: RequestContext,
+                                   request: StreamsInitializeRequestData
+                                 ): CompletableFuture[StreamsInitializeResponseData] = {
+    FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
+      s"The old group coordinator does not support ${ApiKeys.STREAMS_INITIALIZE.name} API."
+    ))
+  }
+
   override def shareGroupHeartbeat(
     context: RequestContext,
     request: ShareGroupHeartbeatRequestData
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 21942229d87..046f1570707 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -276,6 +276,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.WRITE_SHARE_GROUP_STATE => handleWriteShareGroupStateRequest(request)
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
+        case ApiKeys.STREAMS_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
       }
     } catch {
@@ -3883,6 +3884,33 @@ class KafkaApis(val requestChannel: RequestChannel,
 
   }
 
+  def handleStreamsInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsInitializeRequest = request.body[StreamsInitializeRequest]
+
+    // TODO: Check ACLs on CREATE TOPIC & DESCRIBE_CONFIGS
+
+    if (!config.isNewGroupCoordinatorEnabled) {
+      // The API is not supported by the "old" group coordinator (the default). If the
+      // new one is not enabled, we fail directly here.
+      requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      CompletableFuture.completedFuture[Unit](())
+    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsInitializeRequest.data.groupId)) {
+      requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
+      CompletableFuture.completedFuture[Unit](())
+    } else {
+      groupCoordinator.streamsInitialize(
+        request.context,
+        streamsInitializeRequest.data,
+      ).handle[Unit] { (response, exception) =>
+        if (exception != null) {
+          requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(exception))
+        } else {
+          requestHelper.sendMaybeThrottle(request, new StreamsInitializeResponse(response))
+        }
+      }
+    }
+  }
+
   def handleGetTelemetrySubscriptionsRequest(request: RequestChannel.Request): Unit = {
     val subscriptionRequest = request.body[GetTelemetrySubscriptionsRequest]
 
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index 7a9de453740..0d57eea15f9 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -19,7 +19,7 @@ package kafka.coordinator.group
 import kafka.coordinator.group.GroupCoordinatorConcurrencyTest.{JoinGroupCallback, SyncGroupCallback}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
 import org.apache.kafka.common.errors.{InvalidGroupIdException, UnsupportedVersionException}
-import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
+import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol
 import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
 import org.apache.kafka.common.message.OffsetDeleteRequestData.{OffsetDeleteRequestPartition, OffsetDeleteRequestTopic, OffsetDeleteRequestTopicCollection}
@@ -78,6 +78,22 @@ class GroupCoordinatorAdapterTest {
     assertFutureThrows(future, classOf[UnsupportedVersionException])
   }
 
+  @Test
+  def testStreamsInitialize(): Unit = {
+    val groupCoordinator = mock(classOf[GroupCoordinator])
+    val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
+
+    val ctx = makeContext(ApiKeys.STREAMS_INITIALIZE, ApiKeys.STREAMS_INITIALIZE.latestVersion)
+    val request = new StreamsInitializeRequestData()
+      .setGroupId("group")
+
+    val future = adapter.streamsInitialize(ctx, request)
+
+    assertTrue(future.isDone)
+    assertTrue(future.isCompletedExceptionally)
+    assertFutureThrows(future, classOf[UnsupportedVersionException])
+  }
+
   @Test
   def testJoinShareGroup(): Unit = {
     val groupCoordinator = mock(classOf[GroupCoordinator])
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 5771a17d5ea..4c0f3421e3f 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11233,6 +11233,68 @@ class KafkaApisTest extends Logging {
     val response = verifyNoThrottling[ConsumerGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
+  
+  def testStreamsInitializeRequest(): Unit = {
+    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+
+    val future = new CompletableFuture[StreamsInitializeResponseData]()
+    when(groupCoordinator.streamsInitialize(
+      requestChannelRequest.context,
+      streamsInitializeRequest
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(overrideProperties = Map(
+      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
+    ))
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    val streamsInitializeResponse = new StreamsInitializeResponseData()
+
+    future.complete(streamsInitializeResponse)
+    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    assertEquals(streamsInitializeResponse, response.data)
+  }
+
+  @Test
+  def testStreamsInitializeRequestFutureFailed(): Unit = {
+    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+
+    val future = new CompletableFuture[StreamsInitializeResponseData]()
+    when(groupCoordinator.streamsInitialize(
+      requestChannelRequest.context,
+      streamsInitializeRequest
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(overrideProperties = Map(
+      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
+    ))
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
+    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
+  }
+
+  @Test
+  def testStreamsInitializeRequestAuthorizationFailed(): Unit = {
+    val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsInitializeRequest.Builder(streamsInitializeRequest, true).build())
+
+    val authorizer: Authorizer = mock(classOf[Authorizer])
+    when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
+      .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
+    kafkaApis = createKafkaApis(
+      authorizer = Some(authorizer),
+      overrideProperties = Map(GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true")
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    val response = verifyNoThrottling[StreamsInitializeResponse](requestChannelRequest)
+    assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
+  }
 
   @ParameterizedTest
   @ValueSource(booleans = Array(true, false))
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index 223cff9720e..8a5032451b1 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -39,6 +39,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -82,6 +84,20 @@ public interface GroupCoordinator {
         ConsumerGroupHeartbeatRequestData request
     );
 
+    /**
+     * Initialize a Streams Group.
+     *
+     * @param context           The request context.
+     * @param request           The StreamsHeartbeatRequest data.
+     *
+     * @return  A future yielding the response.
+     *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
+     */
+    CompletableFuture<StreamsInitializeResponseData> streamsInitialize(
+        RequestContext context,
+        StreamsInitializeRequestData request
+    );
+
     /**
      * Heartbeat to a Share Group.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index 05cf4d5bd3a..98cf7f937e8 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -17,6 +17,7 @@
 package org.apache.kafka.coordinator.group;
 
 import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.record.RecordBatch;
 import org.apache.kafka.common.requests.OffsetCommitRequest;
 import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
@@ -51,6 +52,8 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.modern.TopicMetadata;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
 import org.apache.kafka.coordinator.group.modern.consumer.ResolvedRegularExpression;
@@ -63,11 +66,13 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 /**
  * This class contains helper methods to create records stored in
  * the __consumer_offsets topic.
  */
+@SuppressWarnings("ClassDataAbstractionCoupling")
 public class GroupCoordinatorRecordHelpers {
     private GroupCoordinatorRecordHelpers() {}
 
@@ -937,4 +942,41 @@ public class GroupCoordinatorRecordHelpers {
         );
         return topics;
     }
+
+    /**
+     * Creates a StreamsTopology record.
+     *
+     * @param groupId                   The consumer group id.
+     * @param subtopologies             The subtopologies in the new topology.
+     * @return The record.
+     */
+    public static CoordinatorRecord newStreamsGroupTopologyRecord(String groupId,
+                                                                  List<StreamsInitializeRequestData.Subtopology> subtopologies) {
+        StreamsGroupTopologyValue value = new StreamsGroupTopologyValue();
+        subtopologies.forEach(subtopology -> {
+            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
+                .map(topicInfo -> {
+                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs().stream()
+                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                        .collect(Collectors.toList());
+                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
+                        .setPartitions(topicInfo.partitions());
+                }).collect(Collectors.toList());
+
+            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
+                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs().stream()
+                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                    .collect(Collectors.toList());
+                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
+            }).collect(Collectors.toList());
+
+            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopology())
+                .setSourceTopics(subtopology.sourceTopics()).setSinkTopics(subtopology.sinkTopics())
+                .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
+        });
+
+        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 15),
+            new ApiMessageAndVersion(value, (short) 0));
+    }
+
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 96d0253a09e..2a3eef88a04 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -44,6 +44,8 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData.DescribedGroup;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -344,6 +346,35 @@ public class GroupCoordinatorService implements GroupCoordinator {
         ));
     }
 
+    /**
+     * See {@link GroupCoordinator#streamsInitialize(RequestContext, StreamsInitializeRequestData)}.
+     */
+    @Override
+    public CompletableFuture<StreamsInitializeResponseData> streamsInitialize(
+        RequestContext context,
+        StreamsInitializeRequestData request
+    ) {
+        if (!isActive.get()) {
+            return CompletableFuture.completedFuture(new StreamsInitializeResponseData()
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
+            );
+        }
+
+        return runtime.scheduleWriteOperation(
+            "streams-group-initialize",
+            topicPartitionFor(request.groupId()),
+            Duration.ofMillis(config.offsetCommitTimeoutMs),
+            coordinator -> coordinator.streamsInitialize(context, request)
+        ).exceptionally(exception -> handleOperationException(
+            "streams-group-initialize",
+            request,
+            exception,
+            (error, message) -> new StreamsInitializeResponseData()
+                .setErrorCode(error.code())
+                .setErrorMessage(message)
+        ));
+    }
+
     /**
      * See {@link GroupCoordinator#shareGroupHeartbeat(RequestContext, ShareGroupHeartbeatRequestData)}.
      */
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 099755710b9..b002f96b60b 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -39,6 +39,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -361,6 +363,22 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
         return groupMetadataManager.consumerGroupHeartbeat(context, request);
     }
 
+    /**
+     * Handles a StreamsInitialize request.
+     *
+     * @param context The request context.
+     * @param request The actual StreamsInitialize request.
+     *
+     * @return A Result containing the StreamsInitialize response and
+     *         a list of records to update the state machine.
+     */
+    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
+        RequestContext context,
+        StreamsInitializeRequestData request
+    ) {
+        return groupMetadataManager.streamsInitialize(context, request);
+    }
+
     /**
      * Handles a ShareGroupHeartbeat request.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 5a7e98ea3cc..c7cf02f7974 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -53,6 +53,8 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.protocol.Errors;
@@ -103,6 +105,8 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.modern.Assignment;
 import org.apache.kafka.coordinator.group.modern.MemberState;
@@ -150,6 +154,7 @@ import java.util.stream.Stream;
 import static org.apache.kafka.common.protocol.Errors.COORDINATOR_NOT_AVAILABLE;
 import static org.apache.kafka.common.protocol.Errors.ILLEGAL_GENERATION;
 import static org.apache.kafka.common.protocol.Errors.NOT_COORDINATOR;
+import static org.apache.kafka.common.protocol.Errors.STREAMS_INVALID_TOPOLOGY;
 import static org.apache.kafka.common.protocol.Errors.UNKNOWN_SERVER_ERROR;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.CONSUMER_GENERATED_MEMBER_ID_REQUIRED_VERSION;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH;
@@ -172,6 +177,7 @@ import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.n
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupMemberSubscriptionTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupSubscriptionMetadataRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupTargetAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupTopologyRecord;
 import static org.apache.kafka.coordinator.group.Utils.assignmentToString;
 import static org.apache.kafka.coordinator.group.Utils.ofSentinel;
 import static org.apache.kafka.coordinator.group.Utils.toConsumerProtocolAssignment;
@@ -1398,7 +1404,29 @@ public class GroupMetadataManager {
             throw new InvalidRequestException("MemberEpoch is invalid.");
         }
     }
+    
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfStreamsInitializeRequestIsInvalid(
+        StreamsInitializeRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
+
+        if (request.topology().isEmpty()) {
+            throw new InvalidRequestException("There must be at least one subtopology.");
+        }
+
+        // TODO: Check invariants
+    }
+    
 
+    /**
     /**
      * Verifies that the partitions currently owned by the member (the ones set in the
      * request) matches the ones that the member should own. It matches if the consumer
@@ -1963,6 +1991,54 @@ public class GroupMetadataManager {
         return new CoordinatorResult<>(records, response);
     }
 
+
+    /**
+     * Handles the initialization of the topology information on the broker side, that will be reused by all members of the group.
+     *
+     * @param groupId       The group id from the request.
+     * @param subtopologies The list of subtopologies
+     * @return A Result containing the StreamsInitialize response and a list of records to update the state machine.
+     */
+    private CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(String groupId,
+                                                                                                  List<StreamsInitializeRequestData.Subtopology> subtopologies)
+        throws ApiException {
+        final List<CoordinatorRecord> records = new ArrayList<>();
+
+        // TODO: Throw if group does not exist or is not a streams group. Needs model of
+        //       similar to  final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, createIfNotExists, records);
+        //                   throwIfNull(group);
+
+        // TODO: For the POC, only check if internal topics exist
+        Set<String> missingTopics = new HashSet<>();
+        for (StreamsInitializeRequestData.Subtopology subtopology : subtopologies) {
+            for (StreamsInitializeRequestData.TopicInfo topic : subtopology.stateChangelogTopics()) {
+                if (metadataImage.topics().getTopic(topic.name()) == null) {
+                    missingTopics.add(topic.name());
+                }
+            }
+            for (StreamsInitializeRequestData.TopicInfo topic : subtopology.repartitionSourceTopics()) {
+                if (metadataImage.topics().getTopic(topic.name()) == null) {
+                    missingTopics.add(topic.name());
+                }
+            }
+        }
+        if (!missingTopics.isEmpty()) {
+            StreamsInitializeResponseData response =
+                new StreamsInitializeResponseData()
+                    .setErrorCode(STREAMS_INVALID_TOPOLOGY.code())
+                    .setErrorMessage("Internal topics " + String.join(", ", missingTopics) + " do not exist.");
+
+            return new CoordinatorResult<>(records, response);
+        } else {
+            records.add(newStreamsGroupTopologyRecord(groupId, subtopologies));
+
+            StreamsInitializeResponseData response = new StreamsInitializeResponseData();
+
+            return new CoordinatorResult<>(records, response);
+        }
+
+    }
+
     /**
      * Handle a JoinGroupRequest to a ConsumerGroup.
      *
@@ -3563,6 +3639,46 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Handles a ConsumerGroupHeartbeat request.
+     *
+     * @param context The request context.
+     * @param request The actual ConsumerGroupHeartbeat request.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
+        RequestContext context,
+        StreamsInitializeRequestData request
+    ) throws ApiException {
+        throwIfStreamsInitializeRequestIsInvalid(request);
+
+        return streamsInitialize(
+            request.groupId(),
+            request.topology()
+        );
+    }
+
+    /**
+     * Replays StreamsGroupTopologyKey/Value to update the hard state of
+     * the streams group.
+     *
+     * @param key   A StreamsGroupTopologyKey key.
+     * @param value A StreamsGroupTopologyValue record.
+     */
+    public void replay(
+        StreamsGroupTopologyKey key,
+        StreamsGroupTopologyValue value
+    ) {
+
+        // TODO: Insert the topology information to the in-memory representation. Needs the notion
+        //       of a Streams group
+//        String groupId = key.groupId();
+//        StreamsGroup streamsGroup = getOrMaybeCreatePersistedConsumerGroup(groupId, value != null);
+//        streamsGroup.setTopology(value);
+    }
+
     /**
      * Handles a ShareGroupHeartbeat request.
      *
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
index 812ee093c2c..480c1576440 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
@@ -19,6 +19,7 @@ package org.apache.kafka.coordinator.group;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol;
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocolCollection;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
@@ -45,6 +46,8 @@ import org.apache.kafka.coordinator.group.generated.GroupMetadataValue;
 import org.apache.kafka.coordinator.group.generated.OffsetCommitKey;
 import org.apache.kafka.coordinator.group.generated.OffsetCommitValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.modern.MemberState;
 import org.apache.kafka.coordinator.group.modern.TopicMetadata;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
@@ -89,6 +92,7 @@ import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.n
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupEpochTombstoneRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupTopologyRecord;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
@@ -214,6 +218,84 @@ public class GroupCoordinatorRecordHelpersTest {
         ));
     }
 
+    @Test
+    public void testNewStreamsGroupTopologyRecord() {
+        List<StreamsInitializeRequestData.Subtopology> topology =
+            Collections.singletonList(new StreamsInitializeRequestData.Subtopology()
+                .setSubtopology("subtopology-id")
+                .setSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new StreamsInitializeRequestData.TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsInitializeRequestData.TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new StreamsInitializeRequestData.TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsInitializeRequestData.TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+            );
+
+        List<StreamsGroupTopologyValue.Subtopology> expectedTopology =
+            Collections.singletonList(new StreamsGroupTopologyValue.Subtopology()
+                .setSubtopology("subtopology-id")
+                .setSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new StreamsGroupTopologyValue.TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupTopologyValue.TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new StreamsGroupTopologyValue.TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupTopologyValue.TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+            );
+
+        CoordinatorRecord expectedRecord = new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyKey()
+                    .setGroupId("group-id"),
+                (short) 15),
+            new ApiMessageAndVersion(
+                new StreamsGroupTopologyValue()
+                    .setTopology(expectedTopology),
+                (short) 0));
+
+        assertEquals(expectedRecord, newStreamsGroupTopologyRecord(
+            "group-id",
+            topology
+        ));
+    }
+
     @Test
     public void testEmptyPartitionMetadataWhenRacksUnavailableGroupSubscriptionMetadataRecord() {
         Uuid fooTopicId = Uuid.randomUuid();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index bccfa57397c..96273e368e1 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -30,6 +30,7 @@ import org.apache.kafka.common.errors.NotLeaderOrFollowerException;
 import org.apache.kafka.common.errors.RebalanceInProgressException;
 import org.apache.kafka.common.errors.RecordBatchTooLargeException;
 import org.apache.kafka.common.errors.RecordTooLargeException;
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
 import org.apache.kafka.common.errors.UnknownMemberIdException;
 import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
 import org.apache.kafka.common.internals.Topic;
@@ -53,6 +54,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -260,6 +263,118 @@ public class GroupCoordinatorServiceTest {
         );
     }
 
+    @Test
+    public void testStreamsInitializeWhenNotStarted() throws ExecutionException, InterruptedException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+            .setGroupId("foo");
+
+        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_INITIALIZE),
+            request
+        );
+
+        assertEquals(
+            new StreamsInitializeResponseData()
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
+            future.get()
+        );
+    }
+
+    @Test
+    public void testStreamsInitialize() throws ExecutionException, InterruptedException, TimeoutException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+            .setGroupId("foo");
+
+        service.startup(() -> 1);
+
+        when(runtime.scheduleWriteOperation(
+            ArgumentMatchers.eq("streams-group-initialize"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.eq(Duration.ofMillis(5000)),
+            ArgumentMatchers.any()
+        )).thenReturn(CompletableFuture.completedFuture(
+            new StreamsInitializeResponseData()
+        ));
+
+        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_INITIALIZE),
+            request
+        );
+
+        assertEquals(new StreamsInitializeResponseData(), future.get(5, TimeUnit.SECONDS));
+    }
+
+    private static Stream<Arguments> testStreamsInitializeWithExceptionSource() {
+        return Stream.of(
+            Arguments.arguments(new UnknownTopicOrPartitionException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new NotEnoughReplicasException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new org.apache.kafka.common.errors.TimeoutException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new NotLeaderOrFollowerException(), Errors.NOT_COORDINATOR.code(), null),
+            Arguments.arguments(new KafkaStorageException(), Errors.NOT_COORDINATOR.code(), null),
+            Arguments.arguments(new RecordTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new RecordBatchTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new InvalidFetchSizeException(""), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new InvalidRequestException("Invalid"), Errors.INVALID_REQUEST.code(), "Invalid"),
+            Arguments.arguments(new StreamsInvalidTopologyException("Invalid"), Errors.STREAMS_INVALID_TOPOLOGY.code(), "Invalid")
+        );
+    }
+
+    @ParameterizedTest
+    @MethodSource("testStreamsInitializeWithExceptionSource")
+    public void testStreamsInitializeWithException(
+        Throwable exception,
+        short expectedErrorCode,
+        String expectedErrorMessage
+    ) throws ExecutionException, InterruptedException, TimeoutException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsInitializeRequestData request = new StreamsInitializeRequestData()
+            .setGroupId("foo");
+
+        service.startup(() -> 1);
+
+        when(runtime.scheduleWriteOperation(
+            ArgumentMatchers.eq("streams-group-initialize"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.eq(Duration.ofMillis(5000)),
+            ArgumentMatchers.any()
+        )).thenReturn(FutureUtils.failedFuture(exception));
+
+        CompletableFuture<StreamsInitializeResponseData> future = service.streamsInitialize(
+            requestContext(ApiKeys.STREAMS_INITIALIZE),
+            request
+        );
+
+        assertEquals(
+            new StreamsInitializeResponseData()
+                .setErrorCode(expectedErrorCode)
+                .setErrorMessage(expectedErrorMessage),
+            future.get(5, TimeUnit.SECONDS)
+        );
+    }
+
     @Test
     public void testPartitionFor() {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index cb68771c8a5..33756fe53ac 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -24,6 +24,8 @@ import org.apache.kafka.common.message.OffsetCommitRequestData;
 import org.apache.kafka.common.message.OffsetCommitResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
 import org.apache.kafka.common.message.TxnOffsetCommitResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
@@ -131,6 +133,38 @@ public class GroupCoordinatorShardTest {
         assertEquals(result, coordinator.consumerGroupHeartbeat(context, request));
     }
 
+    @Test
+    public void testStreamsInitialize() {
+        GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
+        OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
+        CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
+        CoordinatorMetricsShard metricsShard = mock(CoordinatorMetricsShard.class);
+        GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
+            new LogContext(),
+            groupMetadataManager,
+            offsetMetadataManager,
+            Time.SYSTEM,
+            new MockCoordinatorTimer<>(Time.SYSTEM),
+            mock(GroupCoordinatorConfig.class),
+            coordinatorMetrics,
+            metricsShard
+        );
+
+        RequestContext context = requestContext(ApiKeys.STREAMS_INITIALIZE);
+        StreamsInitializeRequestData request = new StreamsInitializeRequestData();
+        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+            Collections.emptyList(),
+            new StreamsInitializeResponseData()
+        );
+
+        when(groupMetadataManager.streamsInitialize(
+            context,
+            request
+        )).thenReturn(result);
+
+        assertEquals(result, coordinator.streamsInitialize(context, request));
+    }
+
     @Test
     public void testCommitOffset() {
         GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index c5bb26d4ba7..c9f2d80ca2b 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -54,6 +54,11 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData.Subtopology;
+import org.apache.kafka.common.message.StreamsInitializeRequestData.TopicConfig;
+import org.apache.kafka.common.message.StreamsInitializeRequestData.TopicInfo;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -15757,4 +15762,139 @@ public class GroupMetadataManagerTest {
         assertEquals(expectedSuccessCount, successCount);
         return memberIds;
     }
+
+    @Test
+    public void testTopologyInitialization() {
+        String groupId = "fooup";
+
+        Uuid fooTopicId = Uuid.randomUuid();
+        String fooTopicName = "repartition";
+        Uuid barTopicId = Uuid.randomUuid();
+        String barTopicName = "changelog";
+
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(new MetadataImageBuilder()
+                .addTopic(fooTopicId, fooTopicName, 6)
+                .addTopic(barTopicId, barTopicName, 3)
+                .addRacks()
+                .build())
+            .build();
+
+        assertThrows(GroupIdNotFoundException.class, () ->
+            context.groupMetadataManager.consumerGroup(groupId));
+
+        final List<Subtopology> topology = Collections.singletonList(
+            new Subtopology()
+                .setSubtopology("subtopology-id")
+                .setSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+        );
+        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
+            context.streamsInitialize(
+                new StreamsInitializeRequestData()
+                    .setGroupId(groupId)
+                    .setTopology(topology)
+            );
+
+        assertEquals(
+            new StreamsInitializeResponseData(),
+            result.response()
+        );
+
+        List<CoordinatorRecord> expectedRecords = Arrays.asList(
+            CoordinatorRecordHelpers.newStreamsGroupTopologyRecord(
+                groupId,
+                topology
+            )
+        );
+
+        assertRecordsEquals(expectedRecords, result.records());
+    }
+
+    @Test
+    public void testTopologyInitializationMissingInternalTopics() {
+        String groupId = "fooup";
+
+        Uuid fooTopicId = Uuid.randomUuid();
+        String fooTopicName = "repartition";
+
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(new MetadataImageBuilder()
+                .addTopic(fooTopicId, fooTopicName, 6)
+                .addRacks()
+                .build())
+            .build();
+
+        assertThrows(GroupIdNotFoundException.class, () ->
+            context.groupMetadataManager.consumerGroup(groupId));
+
+        final List<Subtopology> topology = Collections.singletonList(
+            new Subtopology()
+                .setSubtopology("subtopology-id")
+                .setSinkTopics(Collections.singletonList("foo"))
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+        );
+        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
+            context.streamsInitialize(
+                new StreamsInitializeRequestData()
+                    .setGroupId(groupId)
+                    .setTopology(topology)
+            );
+
+        assertEquals(
+            new StreamsInitializeResponseData()
+                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
+                .setErrorMessage("Internal topics changelog do not exist."),
+            result.response()
+        );
+
+        assertTrue(result.records().isEmpty());
+
+    }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 4230934a499..bdcc0c9e012 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -36,6 +36,8 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupResponseData;
 import org.apache.kafka.common.network.ClientInformation;
@@ -84,6 +86,8 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.modern.MemberState;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup;
@@ -673,6 +677,37 @@ public class GroupMetadataManagerTestContext {
         return result;
     }
 
+
+    public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
+        StreamsInitializeRequestData request
+    ) {
+        RequestContext context = new RequestContext(
+            new RequestHeader(
+                ApiKeys.STREAMS_INITIALIZE,
+                ApiKeys.STREAMS_INITIALIZE.latestVersion(),
+                "client",
+                0
+            ),
+            "1",
+            InetAddress.getLoopbackAddress(),
+            KafkaPrincipal.ANONYMOUS,
+            ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT),
+            SecurityProtocol.PLAINTEXT,
+            ClientInformation.EMPTY,
+            false
+        );
+
+        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result = groupMetadataManager.streamsInitialize(
+            context,
+            request
+        );
+
+        if (result.replayRecords()) {
+            result.records().forEach(this::replay);
+        }
+        return result;
+    }
+
     public List<MockCoordinatorTimer.ExpiredTimeout<Void, CoordinatorRecord>> sleep(long ms) {
         time.sleep(ms);
         List<MockCoordinatorTimer.ExpiredTimeout<Void, CoordinatorRecord>> timeouts = timer.poll();
@@ -1583,6 +1618,13 @@ public class GroupMetadataManagerTestContext {
                 );
                 break;
 
+            case StreamsGroupTopologyKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupTopologyKey) key.message(),
+                    (StreamsGroupTopologyValue) messageOrNull(value)
+                );
+                break;
+
             default:
                 throw new IllegalStateException("Received an unknown record type " + key.version()
                     + " in " + record);


(kafka) 02/42: Reslove merge conflict from 11/25 trunk rebase - StreamsInitialize RPC and some errors

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit f8ecdc9a716165d2c541a27ed3953d6118928380
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Fri Apr 26 13:12:15 2024 +0200

    Reslove merge conflict from 11/25 trunk rebase - StreamsInitialize RPC and some errors
    
    Initial RPCs for StreamsInitialize.
    
    See https://github.com/lucasbru/kafka/pull/7
---
 .../StreamsInconsistentTopologyException.java      | 23 ++++++
 .../errors/StreamsInvalidTopologyException.java    | 23 ++++++
 .../StreamsMissingInternalTopicsException.java     | 23 ++++++
 .../StreamsMissingSourceTopicsException.java       | 23 ++++++
 .../StreamsShutdownApplicationException.java       | 23 ++++++
 .../org/apache/kafka/common/protocol/ApiKeys.java  |  5 +-
 .../org/apache/kafka/common/protocol/Errors.java   | 17 ++++-
 .../common/requests/StreamsHeartbeatRequest.java   | 88 ++++++++++++++++++++++
 .../common/requests/StreamsHeartbeatResponse.java  | 78 +++++++++++++++++++
 .../common/requests/StreamsInitializeRequest.java  | 62 +++++++++++++++
 .../common/requests/StreamsInitializeResponse.java | 55 ++++++++++++++
 .../common/message/StreamsHeartbeatRequest.json    | 37 +++++----
 .../common/message/StreamsHeartbeatResponse.json   |  9 +--
 .../common/message/StreamsInitializeRequest.json   | 64 ++++++++++++++++
 .../common/message/StreamsInitializeResponse.json  | 37 +++++++++
 15 files changed, 547 insertions(+), 20 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentTopologyException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentTopologyException.java
new file mode 100644
index 00000000000..d5d590ceb10
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInconsistentTopologyException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsInconsistentTopologyException extends ApiException {
+    public StreamsInconsistentTopologyException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidTopologyException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidTopologyException.java
new file mode 100644
index 00000000000..28a5c8ab77d
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidTopologyException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsInvalidTopologyException extends ApiException {
+    public StreamsInvalidTopologyException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java
new file mode 100644
index 00000000000..ffd0b63d8e3
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsMissingInternalTopicsException extends ApiException {
+    public StreamsMissingInternalTopicsException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingSourceTopicsException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingSourceTopicsException.java
new file mode 100644
index 00000000000..6a347837701
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingSourceTopicsException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsMissingSourceTopicsException extends ApiException {
+    public StreamsMissingSourceTopicsException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsShutdownApplicationException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsShutdownApplicationException.java
new file mode 100644
index 00000000000..e578c985a68
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsShutdownApplicationException.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsShutdownApplicationException extends ApiException {
+    public StreamsShutdownApplicationException(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index e95882be699..fa9600d8536 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -130,7 +130,10 @@ public enum ApiKeys {
     READ_SHARE_GROUP_STATE(ApiMessageType.READ_SHARE_GROUP_STATE, true),
     WRITE_SHARE_GROUP_STATE(ApiMessageType.WRITE_SHARE_GROUP_STATE, true),
     DELETE_SHARE_GROUP_STATE(ApiMessageType.DELETE_SHARE_GROUP_STATE, true),
-    READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true);
+    READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
+    STREAMS_HEARTBEAT(ApiMessageType.STREAMS_HEARTBEAT),
+    STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE);
+    
 
     private static final Map<ApiMessageType.ListenerType, EnumSet<ApiKeys>> APIS_BY_LISTENER =
         new EnumMap<>(ApiMessageType.ListenerType.class);
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index 309ae7bc86a..6246c4b4d14 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -20,6 +20,11 @@ import org.apache.kafka.common.InvalidRecordException;
 import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.BrokerIdNotRegisteredException;
 import org.apache.kafka.common.errors.BrokerNotAvailableException;
+import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.errors.StreamsMissingInternalTopicsException;
+import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
+import org.apache.kafka.common.errors.StreamsShutdownApplicationException;
 import org.apache.kafka.common.errors.ClusterAuthorizationException;
 import org.apache.kafka.common.errors.ConcurrentTransactionsException;
 import org.apache.kafka.common.errors.ControllerMovedException;
@@ -413,7 +418,17 @@ public enum Errors {
     DUPLICATE_VOTER(126, "The voter is already part of the set of voters.", DuplicateVoterException::new),
     VOTER_NOT_FOUND(127, "The voter is not part of the set of voters.", VoterNotFoundException::new),
     INVALID_REGULAR_EXPRESSION(128, "The regular expression is not valid.", InvalidRegularExpression::new),
-    REBOOTSTRAP_REQUIRED(129, "Client metadata is stale, client should rebootstrap to obtain new metadata.", RebootstrapRequiredException::new);
+    REBOOTSTRAP_REQUIRED(129, "Client metadata is stale, client should rebootstrap to obtain new metadata.", RebootstrapRequiredException::new),
+    STREAMS_INVALID_TOPOLOGY(130, "The supplied topology is invalid.",
+        StreamsInvalidTopologyException::new),
+    STREAMS_INCONSISTENT_TOPOLOGY(131, "The topology hash supplied is inconsistent with the topology for this consumer group.",
+        StreamsInconsistentTopologyException::new),
+    STREAMS_MISSING_SOURCE_TOPICS(132, "One or more source topics are missing.",
+        StreamsMissingSourceTopicsException::new),
+    STREAMS_MISSING_INTERNAL_TOPICS(133, "One or more internal topics are missing.",
+        StreamsMissingInternalTopicsException::new),
+    STREAMS_SHUTDOWN_APPLICATION(134, "A client requested the shutdown of the whole application.",
+        StreamsShutdownApplicationException::new);
 
     private static final Logger log = LoggerFactory.getLogger(Errors.class);
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java
new file mode 100644
index 00000000000..0e552934c4f
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatRequest.java
@@ -0,0 +1,88 @@
+/*
+ * 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 org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+
+public class StreamsHeartbeatRequest extends AbstractRequest {
+
+    /**
+     * A member epoch of <code>-1</code> means that the member wants to leave the group.
+     */
+    public static final int LEAVE_GROUP_MEMBER_EPOCH = -1;
+    public static final int LEAVE_GROUP_STATIC_MEMBER_EPOCH = -2;
+
+    /**
+     * A member epoch of <code>0</code> means that the member wants to join the group.
+     */
+    public static final int JOIN_GROUP_MEMBER_EPOCH = 0;
+
+    public static class Builder extends AbstractRequest.Builder<StreamsHeartbeatRequest> {
+        private final StreamsHeartbeatRequestData data;
+
+        public Builder(StreamsHeartbeatRequestData data) {
+            this(data, false);
+        }
+
+        public Builder(StreamsHeartbeatRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_HEARTBEAT, enableUnstableLastVersion);
+            this.data = data;
+        }
+
+        @Override
+        public StreamsHeartbeatRequest build(short version) {
+            return new StreamsHeartbeatRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final StreamsHeartbeatRequestData data;
+
+    public StreamsHeartbeatRequest(StreamsHeartbeatRequestData data, short version) {
+        super(ApiKeys.STREAMS_HEARTBEAT, version);
+        this.data = data;
+    }
+
+    @Override
+    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        return new StreamsHeartbeatResponse(
+            new StreamsHeartbeatResponseData()
+                .setThrottleTimeMs(throttleTimeMs)
+                .setErrorCode(Errors.forException(e).code())
+        );
+    }
+
+    @Override
+    public StreamsHeartbeatRequestData data() {
+        return data;
+    }
+
+    public static StreamsHeartbeatRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsHeartbeatRequest(new StreamsHeartbeatRequestData(
+            new ByteBufferAccessor(buffer), version), version);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
new file mode 100644
index 00000000000..1e8c7a5b7e9
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
@@ -0,0 +1,78 @@
+/*
+ * 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 org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Possible error codes.
+ *
+ * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
+ * - {@link Errors#NOT_COORDINATOR}
+ * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
+ * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
+ * - {@link Errors#INVALID_REQUEST}
+ * - {@link Errors#UNKNOWN_MEMBER_ID}
+ * - {@link Errors#FENCED_MEMBER_EPOCH}
+ * - {@link Errors#UNSUPPORTED_ASSIGNOR}
+ * - {@link Errors#UNRELEASED_INSTANCE_ID}
+ * - {@link Errors#GROUP_MAX_SIZE_REACHED}
+ * - {@link Errors#STREAMS_SHUTDOWN_APPLICATION}
+ * - {@link Errors#STREAMS_INCONSISTENT_TOPOLOGY}
+ * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
+ * - {@link Errors#STREAMS_MISSING_INTERNAL_TOPICS}
+ */
+public class StreamsHeartbeatResponse extends AbstractResponse {
+    private final StreamsHeartbeatResponseData data;
+
+    public StreamsHeartbeatResponse(StreamsHeartbeatResponseData data) {
+        super(ApiKeys.STREAMS_HEARTBEAT);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsHeartbeatResponseData data() {
+        return data;
+    }
+
+    @Override
+    public Map<Errors, Integer> errorCounts() {
+        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
+    }
+
+    @Override
+    public int throttleTimeMs() {
+        return data.throttleTimeMs();
+    }
+
+    @Override
+    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
+        data.setThrottleTimeMs(throttleTimeMs);
+    }
+
+    public static StreamsHeartbeatResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData(
+            new ByteBufferAccessor(buffer), version));
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
new file mode 100644
index 00000000000..04072dd8565
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
@@ -0,0 +1,62 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ApiMessage;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+
+public class StreamsInitializeRequest extends AbstractRequest {
+
+    public static class Builder extends AbstractRequest.Builder<StreamsInitializeRequest> {
+        private final StreamsInitializeRequestData data;
+
+        public Builder(StreamsInitializeRequestData data) {
+            this(data, false);
+        }
+
+        public Builder(StreamsInitializeRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_INITIALIZE, enableUnstableLastVersion);
+            this.data = data;
+        }
+
+        @Override
+        public StreamsInitializeRequest build(short version) {
+            return new StreamsInitializeRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final StreamsInitializeRequestData data;
+
+    public StreamsInitializeRequest(StreamsInitializeRequestData data, short version) {
+        super(ApiKeys.STREAMS_HEARTBEAT, version);
+        this.data = data;
+    }
+
+    @Override
+    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        return new StreamsInitializeResponse(
+            new StreamsInitializeResponseData()
+                .setThrottleTimeMs(throttleTimeMs)
+                .setErrorCode(Errors.forException(e).code())
+        );
+    }
+
+    @Override
+    public StreamsInitializeRequestData data() {
+        return data;
+    }
+
+    public static StreamsInitializeRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsInitializeRequest(new StreamsInitializeRequestData(
+            new ByteBufferAccessor(buffer), version), version);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
new file mode 100644
index 00000000000..7b7d19961de
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
@@ -0,0 +1,55 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Possible error codes.
+ *
+ * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
+ * - {@link Errors#NOT_COORDINATOR}
+ * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
+ * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
+ * - {@link Errors#INVALID_REQUEST}
+ * - {@link Errors#STREAMS_INVALID_TOPOLOGY}
+ */
+public class StreamsInitializeResponse extends AbstractResponse {
+
+    private final StreamsInitializeResponseData data;
+
+    public StreamsInitializeResponse(StreamsInitializeResponseData data) {
+        super(ApiKeys.STREAMS_HEARTBEAT);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsInitializeResponseData data() {
+        return data;
+    }
+
+    @Override
+    public Map<Errors, Integer> errorCounts() {
+        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
+    }
+
+    @Override
+    public int throttleTimeMs() {
+        return data.throttleTimeMs();
+    }
+
+    @Override
+    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
+        data.setThrottleTimeMs(throttleTimeMs);
+    }
+
+    public static StreamsInitializeResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsInitializeResponse(new StreamsInitializeResponseData(
+            new ByteBufferAccessor(buffer), version));
+    }
+}
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
index a5f52e262f2..e21762e7e10 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -48,9 +48,16 @@
 
     { "name": "ProcessId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Identity of the streams instance that may have multiple consumers. Null if unchanged since last heartbeat." },
-    { "name": "UserEndPoint", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "End-point a user can use for IQ. Null if unchanged since last heartbeat." },
-    { "name": "ClientTags", "type": "[]string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "HostInfo", "type": "HostInfo", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Host information for running interactive queries on this instance. Null if unchanged since last heartbeat.",
+      "fields": [
+        { "name": "Host", "type": "string", "versions": "0+",
+          "about": "Host for running interactive queries on this instance." },
+        { "name": "Port", "type": "int32", "versions": "0+",
+          "about": "Port for running interactive queries on this instance." }
+      ]
+    },
+    { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
 
     { "name": "TaskLagUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
@@ -64,15 +71,11 @@
           "about": "The cumulative lag for the task" }
       ]
     },
-    { "name": "AssignmentConfigs", "type": "[]AssignmentConfig", "versions": "0+","nullableVersions": "0+", "default": "null",
-      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat.",
-      "fields": [
-        { "name": "Key", "type": "string", "versions": "0+",
-          "about": "key of the config" },
-        { "name": "Value", "type": "string", "versions": "0+",
-          "about": "value of the config" }
-      ]
-    }
+    { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat."
+    },
+    { "name": "ShutdownApplication", "type": "bool", "versions": "0+", "default": false,
+      "about": "Whether all Streams clients in the group should shut down." }
   ],
   "commonStructs": [
     { "name": "TaskId", "versions": "0+", "fields": [
@@ -82,6 +85,14 @@
         "about": "subtopology ID" },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "partitions" }
-    ]}
+    ]},
+    { "name": "KeyValue", "versions": "0+",
+      "fields": [
+        { "name": "Key", "type": "string", "versions": "0+",
+          "about": "key of the config" },
+        { "name": "Value", "type": "string", "versions": "0+",
+          "about": "value of the config" }
+      ]
+    }
   ]
 }
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
index 0ab1b0f0ea0..272a5a4cd51 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
@@ -30,11 +30,10 @@
   // - UNSUPPORTED_ASSIGNOR (version 0+)
   // - UNRELEASED_INSTANCE_ID (version 0+)
   // - GROUP_MAX_SIZE_REACHED (version 0+)
-
-  // Streams-specific errors:
-  // - INCONSISTENT_TOPOLOGY (version 0+)
-  // - MISSING_SOURCE_TOPICS (version 0+)
-  // - MISSING_INTERNAL_TOPICS (version 0+)
+  // - STREAMS_INCONSISTENT_TOPOLOGY (version 0+)
+  // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
+  // - STREAMS_MISSING_INTERNAL_TOPICS (version 0+)
+  // - STREAMS_SHUTDOWN_APPLICATION (version 0+)
   "fields": [
     // Same as consumer group heart beat
     { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
new file mode 100644
index 00000000000..c031ba5a11f
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
@@ -0,0 +1,64 @@
+// 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.
+
+{
+  "apiKey": 77,
+  "type": "request",
+  "listeners": ["zkBroker", "broker"],
+  "name": "StreamsInitializeRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+      "about": "The group identifier." },
+    { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
+      "about": "The sub-topologies of the streams application.",
+      "fields": [
+        // We are using strings here, to avoid fixing a structure on task IDs which will
+        // allow introducing stable naming for subtopologies in the future.
+        { "name": "Subtopology", "type": "string", "versions": "0+",
+          "about": "String to uniquely the sub-topology. Deterministically generated from the topology" },
+        { "name": "Partitions", "type": "int32", "versions": "0+",
+          "about": "The number of partitions expected for all source topics and changelog topics." },
+        { "name": "SourceTopics", "type": "[]string", "versions": "0+",
+          "about": "The topics the topology reads from." },
+        { "name": "SinkTopics", "type": "[]string", "versions": "0+",
+          "about": "The topics the topology writes to." },
+        { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
+          "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
+        { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
+          "about": "The set of source topics that are internally created repartition topics. Created automatically." }
+      ]
+    }
+  ],
+  "commonStructs": [
+    { "name": "TopicConfig", "versions": "0+", "fields": [
+        { "name": "key", "type": "string", "versions": "0+",
+          "about": "The key of the topic-level configuration." },
+        { "name": "value", "type": "string", "versions": "0+",
+          "about": "The value of the topic-level configuration," }
+      ]
+    },
+    { "name": "TopicInfo", "versions": "0+", "fields": [
+      { "name": "Name", "type": "string", "versions": "0+",
+        "about": "The name of the topic." },
+      { "name": "Partitions", "type": "int32", "versions": "0+",
+        "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
+      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "Topic-level configurations as key-value pairs."
+      }
+    ]}
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsInitializeResponse.json b/clients/src/main/resources/common/message/StreamsInitializeResponse.json
new file mode 100644
index 00000000000..ff73577303e
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsInitializeResponse.json
@@ -0,0 +1,37 @@
+// 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.
+
+{
+  "apiKey": 77,
+  "type": "response",
+  "name": "StreamsInitializeResponse",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  // Supported errors:
+  // - GROUP_AUTHORIZATION_FAILED (version 0+)
+  // - NOT_COORDINATOR (version 0+)
+  // - COORDINATOR_NOT_AVAILABLE (version 0+)
+  // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
+  // - INVALID_REQUEST (version 0+)
+  // - STREAMS_INVALID_TOPOLOGY (version 0+)
+  "fields": [
+    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
+      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
+    { "name": "ErrorCode", "type": "int16", "versions": "0+",
+      "about": "The top-level error code, or 0 if there was no error" },
+    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The top-level error message, or null if there was no error." }
+  ]
+}


(kafka) 30/42: MINOR: Use subtopologyId and spelling consistently (#17370)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 8b6094c4e328f04cfd92afa2c094c2dd94ef3904
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Mon Oct 7 13:01:15 2024 +0200

    MINOR: Use subtopologyId and spelling consistently (#17370)
    
    Throughout RPCs, we were using subtopology instead of subtopologyId for
    the string ID of a subtopology. We were also using sub-topology
    spelling. Cleaning this up before merging the auto-topic creating code.
---
 .../StreamsGroupHeartbeatRequestManager.java       |  8 +++---
 .../message/StreamsGroupDescribeResponse.json      | 14 +++++-----
 .../message/StreamsGroupHeartbeatRequest.json      |  8 +++---
 .../message/StreamsGroupHeartbeatResponse.json     |  2 +-
 .../message/StreamsGroupInitializeRequest.json     |  8 +++---
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  6 ++--
 .../coordinator/group/GroupMetadataManager.java    |  4 +--
 .../coordinator/group/streams/Assignment.java      |  6 ++--
 .../streams/CoordinatorStreamsRecordHelpers.java   | 10 +++----
 .../group/streams/CurrentAssignmentBuilder.java    |  8 +++---
 .../group/streams/StreamsGroupMember.java          |  4 +--
 .../coordinator/group/streams/StreamsTopology.java |  6 ++--
 .../StreamsGroupCurrentMemberAssignmentValue.json  |  2 +-
 .../StreamsGroupTargetAssignmentMemberValue.json   |  2 +-
 .../common/message/StreamsGroupTopologyValue.json  |  6 ++--
 .../coordinator/group/streams/AssignmentTest.java  | 12 ++++----
 .../CoordinatorStreamsRecordHelpersTest.java       |  2 +-
 .../streams/CurrentAssignmentBuilderTest.java      |  4 +--
 .../group/streams/StreamsGroupMemberTest.java      | 30 ++++++++++----------
 .../group/streams/StreamsTopologyTest.java         | 32 +++++++++++-----------
 .../group/streams/TargetAssignmentBuilderTest.java |  2 +-
 21 files changed, 88 insertions(+), 88 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index f41ed9d0998..3a80765206d 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -271,8 +271,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
     private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
         Map<String, TopicPartitions> tps = new HashMap<>();
         data.activeTasks().forEach(taskId -> Stream.concat(
-                streamsInterface.subtopologyMap().get(taskId.subtopology()).sourceTopics.stream(),
-                streamsInterface.subtopologyMap().get(taskId.subtopology()).repartitionSourceTopics.keySet().stream()
+                streamsInterface.subtopologyMap().get(taskId.subtopologyId()).sourceTopics.stream(),
+                streamsInterface.subtopologyMap().get(taskId.subtopologyId()).repartitionSourceTopics.keySet().stream()
             )
             .forEach(topic -> {
                 final TopicPartitions toInsert = tps.computeIfAbsent(topic, k -> {
@@ -323,7 +323,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         target.clear();
         source.forEach(taskId -> {
             taskId.partitions().forEach(partition -> {
-                target.add(new StreamsAssignmentInterface.TaskId(taskId.subtopology(), partition));
+                target.add(new StreamsAssignmentInterface.TaskId(taskId.subtopologyId(), partition));
             });
         });
     }
@@ -602,7 +602,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                 .stream()
                 .map(entry -> {
                     TaskIds ids = new TaskIds();
-                    ids.setSubtopology(entry.getKey());
+                    ids.setSubtopologyId(entry.getKey());
                     ids.setPartitions(entry.getValue());
                     return ids;
                 })
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index 9cf580f0441..227ac495c2d 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -48,8 +48,8 @@
         { "name":  "Topology", "type": "[]Subtopology", "versions": "0+", "nullableVersions": "0+", "default": "null",
           "about": "The sub-topologies of the streams application. Null if uninitialized.",
           "fields": [
-            { "name": "Subtopology", "type": "string", "versions": "0+",
-              "about": "String to uniquely identify the sub-topology." },
+            { "name": "SubtopologyId", "type": "string", "versions": "0+",
+              "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
             { "name": "SourceTopics", "type": "[]string", "versions": "0+",
               "about": "The topics the topology reads from." },
             { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
@@ -57,7 +57,7 @@
             { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
               "about": "The repartition topics the topology writes to." },
             { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-              "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
+              "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
             { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
               "about": "The set of source topics that are internally created repartition topics. Created automatically." }
           ]
@@ -103,8 +103,8 @@
   ],
   "commonStructs": [
     { "name": "TaskOffset", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "The sub-topology identifier." },
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
       { "name": "Partition", "type": "int32", "versions": "0+",
         "about": "The partition." },
       { "name": "Offset", "type": "int64", "versions": "0+",
@@ -127,8 +127,8 @@
         "about": "Warm-up tasks for this client. " }
     ]},
     { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "The sub-topology identifier." },
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "The partitions of the input topics processed by this member." }
     ]},
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
index 7f829f1e410..ec28c2766fb 100644
--- a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
@@ -72,16 +72,16 @@
         "about": "value of the config" }
     ]},
     { "name": "TaskOffset", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "The sub-topology identifier." },
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
       { "name": "Partition", "type": "int32", "versions": "0+",
         "about": "The partition." },
       { "name": "Offset", "type": "int64", "versions": "0+",
         "about": "The offset." }
     ]},
     { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "The sub-topology identifier." },
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "The partitions of the input topics processed by this member." }
     ]}
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
index ac11b3d8264..40e134dc407 100644
--- a/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatResponse.json
@@ -96,7 +96,7 @@
         "about": "partitions" }
     ]},
     { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "The partitions of the input topics processed by this member." }
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
index 3223d1e8d9e..05c4709092c 100644
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
@@ -29,15 +29,15 @@
       "about": "The sub-topologies of the streams application.",
       "fields": [
         { "name": "SubtopologyId", "type": "string", "versions": "0+",
-          "about": "String to uniquely identify the sub-topology. Deterministically generated from the topology" },
+          "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
         { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-          "about": "The regular expressions identifying topics the sub-topology reads from." },
+          "about": "The regular expressions identifying topics the subtopology reads from." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
+          "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
         { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
-          "about": "The repartition topics the sub-topology writes to." },
+          "about": "The repartition topics the subtopology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of source topics that are internally created repartition topics. Created automatically." }
       ]
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index 503576d8fd5..a635d7d418e 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -282,11 +282,11 @@ class StreamsGroupHeartbeatRequestManagerTest {
             .setThrottleTimeMs(TEST_THROTTLE_TIME_MS)
             .setHeartbeatIntervalMs(1000)
             .setActiveTasks(Collections.singletonList(
-                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("0").setPartitions(Collections.singletonList(0))))
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopologyId("0").setPartitions(Collections.singletonList(0))))
             .setStandbyTasks(Collections.singletonList(
-                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("1").setPartitions(Collections.singletonList(1))))
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopologyId("1").setPartitions(Collections.singletonList(1))))
             .setWarmupTasks(Collections.singletonList(
-                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopology("2").setPartitions(Collections.singletonList(2))));
+                new StreamsGroupHeartbeatResponseData.TaskIds().setSubtopologyId("2").setPartitions(Collections.singletonList(2))));
 
         mockResponse(data);
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index dfb768f9fb5..80785af9c76 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -1778,7 +1778,7 @@ public class GroupMetadataManager {
         if (ownedTasks == null) return false;
 
         for (StreamsGroupHeartbeatRequestData.TaskIds topicPartitions : ownedTasks) {
-            Set<Integer> partitions = target.get(topicPartitions.subtopology());
+            Set<Integer> partitions = target.get(topicPartitions.subtopologyId());
             if (partitions == null) return false;
             for (Integer partitionId : topicPartitions.partitions()) {
                 if (!partitions.contains(partitionId)) return false;
@@ -2438,7 +2438,7 @@ public class GroupMetadataManager {
     private List<StreamsGroupHeartbeatResponseData.TaskIds> createStreamsGroupHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
         return taskIds.entrySet().stream()
             .map(entry -> new StreamsGroupHeartbeatResponseData.TaskIds()
-                .setSubtopology(entry.getKey())
+                .setSubtopologyId(entry.getKey())
                 .setPartitions(new ArrayList<>(entry.getValue())))
             .collect(Collectors.toList());
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
index b80e34cbfe5..09a83323072 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -108,19 +108,19 @@ public class Assignment {
         return new Assignment(
             record.activeTasks().stream()
                 .collect(Collectors.toMap(
-                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopologyId,
                         taskId -> new HashSet<>(taskId.partitions())
                     )
                 ),
             record.standbyTasks().stream()
                 .collect(Collectors.toMap(
-                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopologyId,
                         taskId -> new HashSet<>(taskId.partitions())
                     )
                 ),
             record.warmupTasks().stream()
                 .collect(Collectors.toMap(
-                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopologyId,
                         taskId -> new HashSet<>(taskId.partitions())
                     )
                 )
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 48a31fdd4c7..7a7ee7f2ae2 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -213,7 +213,7 @@ public class CoordinatorStreamsRecordHelpers {
         for (Map.Entry<String, Set<Integer>> entry : activeTasks.entrySet()) {
             activeTaskIds.add(
                 new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
+                    .setSubtopologyId(entry.getKey())
                     .setPartitions(new ArrayList<>(entry.getValue()))
             );
         }
@@ -221,7 +221,7 @@ public class CoordinatorStreamsRecordHelpers {
         for (Map.Entry<String, Set<Integer>> entry : standbyTasks.entrySet()) {
             standbyTaskIds.add(
                 new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
+                    .setSubtopologyId(entry.getKey())
                     .setPartitions(new ArrayList<>(entry.getValue()))
             );
         }
@@ -229,7 +229,7 @@ public class CoordinatorStreamsRecordHelpers {
         for (Map.Entry<String, Set<Integer>> entry : warmupTasks.entrySet()) {
             warmupTaskIds.add(
                 new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-                    .setSubtopology(entry.getKey())
+                    .setSubtopologyId(entry.getKey())
                     .setPartitions(new ArrayList<>(entry.getValue()))
             );
         }
@@ -366,7 +366,7 @@ public class CoordinatorStreamsRecordHelpers {
         List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> taskIds = new ArrayList<>(tasks.size());
         tasks.forEach((subtopologyId, partitions) ->
             taskIds.add(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subtopologyId)
+                .setSubtopologyId(subtopologyId)
                 .setPartitions(new ArrayList<>(partitions)))
         );
         return taskIds;
@@ -399,7 +399,7 @@ public class CoordinatorStreamsRecordHelpers {
                 return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
             }).collect(Collectors.toList());
 
-            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopologyId())
+            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopologyId(subtopology.subtopologyId())
                 .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
                 .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
         });
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index 24e8a2f2a6c..974f465a740 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -168,17 +168,17 @@ public class CurrentAssignmentBuilder {
         } else {
             this.ownedActiveTasks = ownedAssignment.activeTasks().entrySet().stream()
                 .map(activeTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(activeTaskIds.getKey())
+                    .setSubtopologyId(activeTaskIds.getKey())
                     .setPartitions(new ArrayList<>(activeTaskIds.getValue())))
                 .collect(Collectors.toList());
             this.ownedStandbyTasks = ownedAssignment.standbyTasks().entrySet().stream()
                 .map(standbyTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(standbyTaskIds.getKey())
+                    .setSubtopologyId(standbyTaskIds.getKey())
                     .setPartitions(new ArrayList<>(standbyTaskIds.getValue())))
                 .collect(Collectors.toList());
             this.ownedWarmupTasks = ownedAssignment.warmupTasks().entrySet().stream()
                 .map(warmupTaskIds -> new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(warmupTaskIds.getKey())
+                    .setSubtopologyId(warmupTaskIds.getKey())
                     .setPartitions(new ArrayList<>(warmupTaskIds.getValue())))
                 .collect(Collectors.toList());
         }
@@ -329,7 +329,7 @@ public class CurrentAssignmentBuilder {
 
         for (StreamsGroupHeartbeatRequestData.TaskIds owned : ownedTasks) {
             Set<Integer> tasksPendingRevocation =
-                assignment.getOrDefault(owned.subtopology(), Collections.emptySet());
+                assignment.getOrDefault(owned.subtopologyId(), Collections.emptySet());
 
             for (Integer partitionId : owned.partitions()) {
                 if (tasksPendingRevocation.contains(partitionId)) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index 7caa1f77ff0..12d97d32e62 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -277,7 +277,7 @@ public class StreamsGroupMember {
             List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> topicPartitionsList
         ) {
             return topicPartitionsList.stream().collect(Collectors.toMap(
-                StreamsGroupCurrentMemberAssignmentValue.TaskIds::subtopology,
+                StreamsGroupCurrentMemberAssignmentValue.TaskIds::subtopologyId,
                 taskIds -> Collections.unmodifiableSet(new HashSet<>(taskIds.partitions()))));
         }
 
@@ -632,7 +632,7 @@ public class StreamsGroupMember {
         List<StreamsGroupDescribeResponseData.TaskIds> taskIds = new ArrayList<>();
         tasks.forEach((subtopologyId, partitionSet) -> {
             taskIds.add(new StreamsGroupDescribeResponseData.TaskIds()
-                .setSubtopology(subtopologyId)
+                .setSubtopologyId(subtopologyId)
                 .setPartitions(new ArrayList<>(partitionSet)));
         });
         return taskIds;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index ca2fd9a6da0..16b8f6d5178 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -68,7 +68,7 @@ public class StreamsTopology {
 
             this.subtopologies.put(
                 subtopology.subtopologyId(),
-                new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopologyId())
+                new StreamsGroupTopologyValue.Subtopology().setSubtopologyId(subtopology.subtopologyId())
                     .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
                     .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
         });
@@ -92,7 +92,7 @@ public class StreamsTopology {
     public static StreamsTopology fromRecord(StreamsGroupTopologyValue record) {
         return new StreamsTopology(
             record.topologyId(),
-            record.topology().stream().collect(Collectors.toMap(Subtopology::subtopology, x -> x))
+            record.topology().stream().collect(Collectors.toMap(Subtopology::subtopologyId, x -> x))
         );
     }
 
@@ -125,7 +125,7 @@ public class StreamsTopology {
         return subtopologies.values().stream().map(
             subtopology -> new StreamsGroupDescribeResponseData.Subtopology()
                 .setSourceTopicRegex(subtopology.sourceTopicRegex())
-                .setSubtopology(subtopology.subtopology())
+                .setSubtopologyId(subtopology.subtopologyId())
                 .setSourceTopics(subtopology.sourceTopics())
                 .setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
                 .setRepartitionSourceTopics(
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
index bcb0e6b6eed..8d393de7b6c 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -41,7 +41,7 @@
   ],
   "commonStructs": [
     { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "The partitions of the input topics processed by this member." }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
index f33e0ace34c..88424950082 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
@@ -29,7 +29,7 @@
   ],
   "commonStructs": [
     { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
+      { "name": "SubtopologyId", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "The partitions of the input topics processed by this member." }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
index 5ba633095b6..af1fae06aad 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
@@ -25,8 +25,8 @@
     { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
       "about": "The sub-topologies of the streams application.",
       "fields": [
-        { "name": "Subtopology", "type": "string", "versions": "0+",
-          "about": "String to uniquely identify the subtopology." },
+        { "name": "SubtopologyId", "type": "string", "versions": "0+",
+          "about": "String to uniquely identify the subtopology. Deterministically generated from the topology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
         { "name": "SourceTopicRegex", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
@@ -34,7 +34,7 @@
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of state changelog topics associated with this subtopology. " },
         { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
-          "about": "The repartition topics the sub-topology writes to." },
+          "about": "The repartition topics the subtopology writes to." },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
           "about": "The set of source topics that are internally created repartition topics. " }
       ]
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
index 57a48e2d365..65675136eb7 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -64,24 +64,24 @@ public class AssignmentTest {
         String subtopology2 = "subtopology2";
         List<StreamsGroupTargetAssignmentMemberValue.TaskIds> activeTasks = new ArrayList<>();
         activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology1)
+            .setSubtopologyId(subtopology1)
             .setPartitions(Arrays.asList(1, 2, 3)));
         activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology2)
+            .setSubtopologyId(subtopology2)
             .setPartitions(Arrays.asList(4, 5, 6)));
         List<StreamsGroupTargetAssignmentMemberValue.TaskIds> standbyTasks = new ArrayList<>();
         standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology1)
+            .setSubtopologyId(subtopology1)
             .setPartitions(Arrays.asList(7, 8, 9)));
         standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology2)
+            .setSubtopologyId(subtopology2)
             .setPartitions(Arrays.asList(1, 2, 3)));
         List<StreamsGroupTargetAssignmentMemberValue.TaskIds> warmupTasks = new ArrayList<>();
         warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology1)
+            .setSubtopologyId(subtopology1)
             .setPartitions(Arrays.asList(4, 5, 6)));
         warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
-            .setSubtopology(subtopology2)
+            .setSubtopologyId(subtopology2)
             .setPartitions(Arrays.asList(7, 8, 9)));
 
         StreamsGroupTargetAssignmentMemberValue record = new StreamsGroupTargetAssignmentMemberValue()
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 0b291bd098e..839897d4dae 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -64,7 +64,7 @@ class CoordinatorStreamsRecordHelpersTest {
 
         List<StreamsGroupTopologyValue.Subtopology> expectedTopology =
             Collections.singletonList(new StreamsGroupTopologyValue.Subtopology()
-                .setSubtopology("subtopology-id")
+                .setSubtopologyId("subtopology-id")
                 .setRepartitionSinkTopics(Collections.singletonList("foo"))
                 .setSourceTopics(Collections.singletonList("bar"))
                 .setRepartitionSourceTopics(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
index 93e40214dd8..d6f83025c7f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -418,10 +418,10 @@ public class CurrentAssignmentBuilderTest {
             .withCurrentWarmupTaskProcessIds((subtopologyId, partitionId) -> Collections.emptySet())
             .withOwnedActiveTasks(Arrays.asList(
                 new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId1)
+                    .setSubtopologyId(subtopologyId1)
                     .setPartitions(Arrays.asList(2, 3)),
                 new StreamsGroupHeartbeatRequestData.TaskIds()
-                    .setSubtopology(subtopologyId2)
+                    .setSubtopologyId(subtopologyId2)
                     .setPartitions(Arrays.asList(5, 6))))
             .withOwnedStandbyTasks(Collections.emptyList())
             .withOwnedWarmupTasks(Collections.emptyList())
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index 0e5a0ffef07..00f6ef6c676 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -248,27 +248,27 @@ public class StreamsGroupMemberTest {
             .setPreviousMemberEpoch(9)
             .setState((byte) 1)
             .setActiveTasks(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId1)
+                .setSubtopologyId(subtopologyId1)
                 .setPartitions(Arrays.asList(1, 2)))
             )
             .setStandbyTasks(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId2)
+                .setSubtopologyId(subtopologyId2)
                 .setPartitions(Arrays.asList(3, 4)))
             )
             .setWarmupTasks(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId1)
+                .setSubtopologyId(subtopologyId1)
                 .setPartitions(Arrays.asList(5, 6)))
             )
             .setActiveTasksPendingRevocation(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId2)
+                .setSubtopologyId(subtopologyId2)
                 .setPartitions(Arrays.asList(7, 8)))
             )
             .setStandbyTasksPendingRevocation(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId1)
+                .setSubtopologyId(subtopologyId1)
                 .setPartitions(Arrays.asList(9, 10)))
             )
             .setWarmupTasksPendingRevocation(Collections.singletonList(new TaskIds()
-                .setSubtopology(subtopologyId2)
+                .setSubtopologyId(subtopologyId2)
                 .setPartitions(Arrays.asList(11, 12)))
             );
 
@@ -300,13 +300,13 @@ public class StreamsGroupMemberTest {
             .setMemberEpoch(epoch)
             .setPreviousMemberEpoch(epoch - 1)
             .setActiveTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subTopology1)
+                .setSubtopologyId(subTopology1)
                 .setPartitions(assignedTasks1)))
             .setStandbyTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subTopology2)
+                .setSubtopologyId(subTopology2)
                 .setPartitions(assignedTasks2)))
             .setWarmupTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
-                .setSubtopology(subTopology3)
+                .setSubtopologyId(subTopology3)
                 .setPartitions(assignedTasks3)));
         String memberId = Uuid.randomUuid().toString();
         String clientId = "clientId";
@@ -355,25 +355,25 @@ public class StreamsGroupMemberTest {
             .setAssignment(
                 new StreamsGroupDescribeResponseData.Assignment()
                     .setActiveTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology1)
+                        .setSubtopologyId(subTopology1)
                         .setPartitions(assignedTasks1)))
                     .setStandbyTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology2)
+                        .setSubtopologyId(subTopology2)
                         .setPartitions(assignedTasks2)))
                     .setWarmupTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology3)
+                        .setSubtopologyId(subTopology3)
                         .setPartitions(assignedTasks3)))
             )
             .setTargetAssignment(
                 new StreamsGroupDescribeResponseData.Assignment()
                     .setActiveTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology1)
+                        .setSubtopologyId(subTopology1)
                         .setPartitions(assignedTasks3)))
                     .setStandbyTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology2)
+                        .setSubtopologyId(subTopology2)
                         .setPartitions(assignedTasks2)))
                     .setWarmupTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
-                        .setSubtopology(subTopology3)
+                        .setSubtopologyId(subTopology3)
                         .setPartitions(assignedTasks1)))
             );
         // TODO: Add TaskOffsets
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
index 7ef086c9be5..8cb9c9aa645 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -45,8 +45,8 @@ public class StreamsTopologyTest {
     @Test
     public void subtopologiesShouldBeCorrect() {
         Map<String, Subtopology> subtopologies = mkMap(
-            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
-            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+            mkEntry("subtopology-1", new Subtopology().setSubtopologyId("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopologyId("subtopology-2"))
         );
         StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
         assertEquals(subtopologies, topology.subtopologies());
@@ -83,8 +83,8 @@ public class StreamsTopologyTest {
         StreamsGroupTopologyValue record = new StreamsGroupTopologyValue()
             .setTopologyId("topology-id")
             .setTopology(Arrays.asList(
-                new Subtopology().setSubtopology("subtopology-1"),
-                new Subtopology().setSubtopology("subtopology-2")
+                new Subtopology().setSubtopologyId("subtopology-1"),
+                new Subtopology().setSubtopologyId("subtopology-2")
             ));
         StreamsTopology topology = StreamsTopology.fromRecord(record);
         assertEquals("topology-id", topology.topologyId());
@@ -96,8 +96,8 @@ public class StreamsTopologyTest {
     @Test
     public void equalsShouldReturnTrueForEqualTopologies() {
         Map<String, Subtopology> subtopologies = mkMap(
-            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
-            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+            mkEntry("subtopology-1", new Subtopology().setSubtopologyId("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopologyId("subtopology-2"))
         );
         StreamsTopology topology1 = new StreamsTopology("topology-id", subtopologies);
         StreamsTopology topology2 = new StreamsTopology("topology-id", subtopologies);
@@ -107,10 +107,10 @@ public class StreamsTopologyTest {
     @Test
     public void equalsShouldReturnFalseForDifferentTopologies() {
         Map<String, Subtopology> subtopologies1 = mkMap(
-            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1"))
+            mkEntry("subtopology-1", new Subtopology().setSubtopologyId("subtopology-1"))
         );
         Map<String, Subtopology> subtopologies2 = mkMap(
-            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+            mkEntry("subtopology-2", new Subtopology().setSubtopologyId("subtopology-2"))
         );
         StreamsTopology topology1 = new StreamsTopology("topology-id-1", subtopologies1);
         StreamsTopology topology2 = new StreamsTopology("topology-id-2", subtopologies2);
@@ -120,8 +120,8 @@ public class StreamsTopologyTest {
     @Test
     public void hashCodeShouldBeConsistentWithEquals() {
         Map<String, Subtopology> subtopologies = mkMap(
-            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
-            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+            mkEntry("subtopology-1", new Subtopology().setSubtopologyId("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopologyId("subtopology-2"))
         );
         StreamsTopology topology1 = new StreamsTopology("topology-id", subtopologies);
         StreamsTopology topology2 = new StreamsTopology("topology-id", subtopologies);
@@ -131,8 +131,8 @@ public class StreamsTopologyTest {
     @Test
     public void toStringShouldReturnCorrectRepresentation() {
         Map<String, Subtopology> subtopologies = mkMap(
-            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
-            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+            mkEntry("subtopology-1", new Subtopology().setSubtopologyId("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopologyId("subtopology-2"))
         );
         StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
         String expectedString = "StreamsTopology{topologyId=topology-id, subtopologies=" + subtopologies + "}";
@@ -144,7 +144,7 @@ public class StreamsTopologyTest {
         Map<String, Subtopology> subtopologies = mkMap(
             mkEntry("subtopology-1", new Subtopology()
                 .setSourceTopicRegex("regex-1")
-                .setSubtopology("subtopology-1")
+                .setSubtopologyId("subtopology-1")
                 .setSourceTopics(Collections.singletonList("source-topic-1"))
                 .setRepartitionSinkTopics(Collections.singletonList("sink-topic-1"))
                 .setRepartitionSourceTopics(
@@ -154,7 +154,7 @@ public class StreamsTopologyTest {
             ),
             mkEntry("subtopology-2", new Subtopology()
                 .setSourceTopicRegex("regex-2")
-                .setSubtopology("subtopology-2")
+                .setSubtopologyId("subtopology-2")
                 .setSourceTopics(Collections.singletonList("source-topic-2"))
                 .setRepartitionSinkTopics(Collections.singletonList("sink-topic-2"))
                 .setRepartitionSourceTopics(
@@ -167,13 +167,13 @@ public class StreamsTopologyTest {
         List<StreamsGroupDescribeResponseData.Subtopology> result = topology.asStreamsGroupDescribeTopology();
         assertEquals(2, result.size());
         assertEquals("regex-1", result.get(0).sourceTopicRegex());
-        assertEquals("subtopology-1", result.get(0).subtopology());
+        assertEquals("subtopology-1", result.get(0).subtopologyId());
         assertEquals(Collections.singletonList("source-topic-1"), result.get(0).sourceTopics());
         assertEquals(Collections.singletonList("sink-topic-1"), result.get(0).repartitionSinkTopics());
         assertEquals("repartition-topic-1", result.get(0).repartitionSourceTopics().get(0).name());
         assertEquals("changelog-topic-1", result.get(0).stateChangelogTopics().get(0).name());
         assertEquals("regex-2", result.get(1).sourceTopicRegex());
-        assertEquals("subtopology-2", result.get(1).subtopology());
+        assertEquals("subtopology-2", result.get(1).subtopologyId());
         assertEquals(Collections.singletonList("source-topic-2"), result.get(1).sourceTopics());
         assertEquals(Collections.singletonList("sink-topic-2"), result.get(1).repartitionSinkTopics());
         assertEquals("repartition-topic-2", result.get(1).repartitionSourceTopics().get(0).name());
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index 1679336815f..e7b52deae42 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -117,7 +117,7 @@ public class TargetAssignmentBuilderTest {
             ));
             topicsImageBuilder = topicsImageBuilder.addTopic(topicId, topicName, numTasks);
             topology.subtopologies().put(subtopologyId, new StreamsGroupTopologyValue.Subtopology()
-                .setSubtopology(subtopologyId)
+                .setSubtopologyId(subtopologyId)
                 .setSourceTopics(Collections.singletonList(topicId.toString())));
 
             return subtopologyId;


(kafka) 08/42: Define initial record types for the consumer offset topic

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 286314d72aefe139192e2b28b7351a75872079b0
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Wed May 29 16:33:54 2024 +0200

    Define initial record types for the consumer offset topic
    
    The goal is to define initial record types for storing group metadata. The aim is roughly match the data represented in the RPCs and the KIP-848 records. There is an extra record for the topology that is called when StreamsInitialize is called.
    
    See https://github.com/lucasbru/kafka/pull/14
    
    target assignment and topology
    
    current assignment
    
    member metadata
    
    names and version
    
    initial copy
---
 .../internals/StreamsInitializeRequestManager.java |  2 +-
 .../common/message/StreamsInitializeRequest.json   |  6 +-
 .../StreamsGroupCurrentMemberAssignmentKey.json    | 28 +++++++++
 .../StreamsGroupCurrentMemberAssignmentValue.json  | 46 +++++++++++++++
 .../message/StreamsGroupMemberMetadataKey.json     | 28 +++++++++
 .../message/StreamsGroupMemberMetadataValue.json   | 69 ++++++++++++++++++++++
 .../common/message/StreamsGroupMetadataKey.json    | 26 ++++++++
 .../common/message/StreamsGroupMetadataValue.json  | 26 ++++++++
 .../message/StreamsGroupPartitionMetadataKey.json  | 26 ++++++++
 .../StreamsGroupPartitionMetadataValue.json        | 40 +++++++++++++
 .../StreamsGroupTargetAssignmentMemberKey.json     | 28 +++++++++
 .../StreamsGroupTargetAssignmentMemberValue.json   | 38 ++++++++++++
 .../StreamsGroupTargetAssignmentMetadataKey.json   | 26 ++++++++
 .../StreamsGroupTargetAssignmentMetadataValue.json | 26 ++++++++
 .../common/message/StreamsGroupTopologyKey.json    | 26 ++++++++
 .../common/message/StreamsGroupTopologyValue.json  | 31 ++++------
 16 files changed, 448 insertions(+), 24 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
index 5d19d8a8e50..2bc4f79f548 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -122,7 +122,7 @@ public class StreamsInitializeRequestManager implements RequestManager {
             logger.error("Error during Streams initialization: ", exception);
         } else {
             // todo: handle success
-            logger.info("Streams initialization successful", exception);
+            logger.info("Streams initialization successful");
         }
     }
 }
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
index c031ba5a11f..7f18cd455d0 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
@@ -26,12 +26,8 @@
     { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
       "about": "The sub-topologies of the streams application.",
       "fields": [
-        // We are using strings here, to avoid fixing a structure on task IDs which will
-        // allow introducing stable naming for subtopologies in the future.
         { "name": "Subtopology", "type": "string", "versions": "0+",
-          "about": "String to uniquely the sub-topology. Deterministically generated from the topology" },
-        { "name": "Partitions", "type": "int32", "versions": "0+",
-          "about": "The number of partitions expected for all source topics and changelog topics." },
+          "about": "String to uniquely identify the subtopology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
         { "name": "SinkTopics", "type": "[]string", "versions": "0+",
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
new file mode 100644
index 00000000000..6d8cb6b906c
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
@@ -0,0 +1,28 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupCurrentMemberAssignmentKey",
+  "validVersions": "14",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "8",
+      "about": "The group id." },
+    { "name": "MemberId", "type": "string", "versions": "8",
+      "about": "The member id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
new file mode 100644
index 00000000000..d79e58cba75
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -0,0 +1,46 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupCurrentMemberAssignmentValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "MemberEpoch", "versions": "0+", "type": "int32",
+      "about": "The current member epoch that is expected from the member in the heartbeat request." },
+    { "name": "PreviousMemberEpoch", "versions": "0+", "type": "int32",
+      "about": "If the last epoch bump is lost before reaching the member, the member will retry with the previous epoch." },
+    { "name": "State", "versions": "0+", "type": "int8",
+      "about": "The member state. See StreamsGroupMember.MemberState for the possible values." },
+    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned active tasks for this streams client." },
+    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned standby tasks for this streams client." },
+    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned warming up tasks for this streams client." },
+    { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskId",
+      "about": "The active tasks that must be revoked by this member." }
+  ],
+  "commonStructs": [
+    { "name": "TaskId", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "The partitions of the input topics processed by this member." }
+    ]}
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
new file mode 100644
index 00000000000..bc54bc8010b
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
@@ -0,0 +1,28 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupMemberMetadataKey",
+  "validVersions": "11",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "5",
+      "about": "The group id." },
+    { "name": "MemberId", "type": "string", "versions": "5",
+      "about": "The member id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json
new file mode 100644
index 00000000000..eab6f18310e
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataValue.json
@@ -0,0 +1,69 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupMemberMetadataValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "InstanceId", "versions": "0+", "nullableVersions": "0+", "type": "string",
+      "about": "The (optional) instance id." },
+    { "name": "RackId", "versions": "0+", "nullableVersions": "0+", "type": "string",
+      "about": "The (optional) rack id." },
+    { "name": "ClientId", "versions": "0+", "type": "string",
+      "about": "The client id." },
+    { "name": "ClientHost", "versions": "0+", "type": "string",
+      "about": "The client host." },
+    { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
+      "about": "The rebalance timeout." },
+
+    { "name": "TopologyHash", "type": "bytes", "versions": "0+",
+      "about": "The hash of the topology. " },
+    { "name": "Assignor", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
+      "about": "The desired assignor. If set to null, the vote goes towards the broker taking a pick." },
+
+    { "name": "ProcessId", "type": "string", "versions": "0+",
+      "about": "Identity of the streams instance that may have multiple consumers." },
+    { "name": "HostInfo", "type": "HostInfo", "versions": "0+",
+      "about": "Host information for running interactive queries on this instance.",
+      "fields": [
+        { "name": "Host", "type": "string", "versions": "0+",
+          "about": "Host for running interactive queries on this instance." },
+        { "name": "Port", "type": "int32", "versions": "0+",
+          "about": "Port for running interactive queries on this instance." }
+      ]
+    },
+    // TODO: maybe it would be nice to just stuff this info into "AssignmentConfigs", since it's quite specific
+    { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
+      "about": "Used for rack-aware assignment algorithm." },
+
+    { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Opaque user data to be passed to the client-side assignor. Null for server-side assignors." },
+    { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+",
+      "about": "Generic array of assignment configuration strings." }
+  ],
+  "commonStructs": [
+    { "name": "KeyValue", "versions": "0+",
+      "fields": [
+        { "name": "Key", "type": "string", "versions": "0+",
+          "about": "key of the config" },
+        { "name": "Value", "type": "string", "versions": "0+",
+          "about": "value of the config" }
+      ]
+    }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
new file mode 100644
index 00000000000..0ad8fbce88b
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupMetadataKey",
+  "validVersions": "9",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "3",
+      "about": "The group id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataValue.json
new file mode 100644
index 00000000000..7d63be55eff
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataValue.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupMetadataValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "Epoch", "versions": "0+", "type": "int32",
+      "about": "The group epoch." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
new file mode 100644
index 00000000000..52b879dbcd1
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupPartitionMetadataKey",
+  "validVersions": "10",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "4",
+      "about": "The group id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataValue.json
new file mode 100644
index 00000000000..a208aa8769c
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataValue.json
@@ -0,0 +1,40 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupPartitionMetadataValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "Topics", "versions": "0+", "type": "[]TopicMetadata",
+      "about": "The list of topic metadata.", "fields": [
+      { "name": "TopicId", "versions": "0+", "type": "uuid",
+        "about": "The topic id." },
+      { "name": "TopicName", "versions": "0+", "type": "string",
+        "about": "The topic name." },
+      { "name": "NumPartitions", "versions": "0+", "type": "int32",
+        "about": "The number of partitions of the topic." },
+      { "name": "PartitionMetadata", "versions": "0+", "type": "[]PartitionMetadata",
+        "about": "Partitions mapped to a set of racks. If the rack information is unavailable for all the partitions, an empty list is stored", "fields": [
+          { "name": "Partition", "versions": "0+", "type": "int32",
+            "about": "The partition number." },
+          { "name": "Racks", "versions": "0+", "type": "[]string",
+            "about": "The set of racks that the partition is mapped to." }
+      ]}
+    ]}
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
new file mode 100644
index 00000000000..6faac03a9e2
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
@@ -0,0 +1,28 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupTargetAssignmentMemberKey",
+  "validVersions": "13",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "7",
+      "about": "The group id." },
+    { "name": "MemberId", "type": "string", "versions": "7",
+      "about": "The member id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
new file mode 100644
index 00000000000..38526e4381c
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
@@ -0,0 +1,38 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupTargetAssignmentMemberValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned active tasks for this streams client." },
+    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned standby tasks for this streams client." },
+    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskId",
+      "about": "Currently assigned warming up tasks for this streams client." }
+  ],
+  "commonStructs": [
+    { "name": "TaskId", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "The subtopology identifier." },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "The partitions of the input topics processed by this member." }
+    ]}
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
new file mode 100644
index 00000000000..91f58c07f64
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupTargetAssignmentMetadataKey",
+  "validVersions": "12",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "6",
+      "about": "The group id." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataValue.json
new file mode 100644
index 00000000000..b35fc7e1dda
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataValue.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupTargetAssignmentMetadataValue",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "AssignmentEpoch", "versions": "0+", "type": "int32",
+      "about": "The assignment epoch." }
+  ]
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
new file mode 100644
index 00000000000..0e72d8c3372
--- /dev/null
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
@@ -0,0 +1,26 @@
+// 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.
+
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
+{
+  "type": "data",
+  "name": "StreamsGroupTopologyKey",
+  "validVersions": "15",
+  "flexibleVersions": "none",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "3",
+      "about": "The group id." }
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
similarity index 68%
copy from clients/src/main/resources/common/message/StreamsInitializeRequest.json
copy to group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
index c031ba5a11f..74ced92af39 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeRequest.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
@@ -13,43 +13,38 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+// The streams rebalance protocol is in development. This schema is subject to non-backwards-compatible changes.
 {
-  "apiKey": 77,
-  "type": "request",
-  "listeners": ["zkBroker", "broker"],
-  "name": "StreamsInitializeRequest",
+  "type": "data",
+  "name": "StreamsGroupTopologyValue",
   "validVersions": "0",
   "flexibleVersions": "0+",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
-      "about": "The group identifier." },
+    { "name": "TopologyHash", "type": "bytes", "versions": "0+",
+      "about": "The hash of the topology. " },
     { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
       "about": "The sub-topologies of the streams application.",
       "fields": [
-        // We are using strings here, to avoid fixing a structure on task IDs which will
-        // allow introducing stable naming for subtopologies in the future.
         { "name": "Subtopology", "type": "string", "versions": "0+",
-          "about": "String to uniquely the sub-topology. Deterministically generated from the topology" },
-        { "name": "Partitions", "type": "int32", "versions": "0+",
-          "about": "The number of partitions expected for all source topics and changelog topics." },
+          "about": "String to uniquely identify the subtopology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
         { "name": "SinkTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology writes to." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
+          "about": "The set of state changelog topics associated with this subtopology. " },
         { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
-          "about": "The set of source topics that are internally created repartition topics. Created automatically." }
+          "about": "The set of source topics that are internally created repartition topics. " }
       ]
     }
   ],
   "commonStructs": [
     { "name": "TopicConfig", "versions": "0+", "fields": [
-        { "name": "key", "type": "string", "versions": "0+",
-          "about": "The key of the topic-level configuration." },
-        { "name": "value", "type": "string", "versions": "0+",
-          "about": "The value of the topic-level configuration," }
-      ]
+      { "name": "key", "type": "string", "versions": "0+",
+        "about": "The key of the topic-level configuration." },
+      { "name": "value", "type": "string", "versions": "0+",
+        "about": "The value of the topic-level configuration," }
+    ]
     },
     { "name": "TopicInfo", "versions": "0+", "fields": [
       { "name": "Name", "type": "string", "versions": "0+",


(kafka) 21/42: Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-08-15

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit dc5b2ef7ecd259fca8dc729de25339fce3bd7e04
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Fri Aug 16 19:58:35 2024 +0200

    Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-08-15
---
 .../internals/AbstractMembershipManager.java       |  1 +
 .../consumer/internals/RequestManagers.java        |  4 ++-
 .../StreamsGroupHeartbeatRequestManager.java       | 18 ++++++-------
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  4 +--
 .../events/ApplicationEventProcessorTest.java      |  2 --
 .../group/GroupCoordinatorRecordHelpers.java       |  4 +--
 .../coordinator/group/GroupMetadataManager.java    |  2 +-
 .../streams/CoordinatorStreamsRecordHelpers.java   | 31 ++++++++++++----------
 .../StreamsGroupCurrentMemberAssignmentKey.json    |  6 ++---
 .../message/StreamsGroupMemberMetadataKey.json     |  6 ++---
 .../common/message/StreamsGroupMetadataKey.json    |  4 +--
 .../message/StreamsGroupPartitionMetadataKey.json  |  4 +--
 .../StreamsGroupTargetAssignmentMemberKey.json     |  6 ++---
 .../StreamsGroupTargetAssignmentMetadataKey.json   |  4 +--
 .../common/message/StreamsGroupTopologyKey.json    |  4 +--
 .../group/GroupCoordinatorServiceTest.java         | 30 ++++++++++++++-------
 .../CoordinatorStreamsRecordHelpersTest.java       |  2 +-
 .../group/streams/StreamsGroupTest.java            |  6 ++---
 .../assignment/TaskAssignorConvergenceTest.java    |  4 +--
 19 files changed, 78 insertions(+), 64 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
index c6aa70d805e..049944ed09f 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractMembershipManager.java
@@ -1270,6 +1270,7 @@ public abstract class AbstractMembershipManager<R extends AbstractResponse> impl
 
     protected void updateMemberEpoch(int newEpoch) {
         boolean newEpochReceived = this.memberEpoch != newEpoch;
+        log.info("Updating member epoch to {}", newEpoch);
         this.memberEpoch = newEpoch;
         // Simply notify based on epoch changes only, since the member will generate a member ID
         // at startup, and it will remain unchanged for its entire lifetime.
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 0f7e7cf1178..7cf4a3e67f6 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -70,7 +70,7 @@ public class RequestManagers implements Closeable {
                            Optional<CoordinatorRequestManager> coordinatorRequestManager,
                            Optional<CommitRequestManager> commitRequestManager,
                            Optional<ConsumerHeartbeatRequestManager> heartbeatRequestManager,
-                           Optional<ConsumerMembershipManager> membershipManager) {
+                           Optional<ConsumerMembershipManager> membershipManager,
                            Optional<StreamsGroupHeartbeatRequestManager> streamsHeartbeatRequestManager,
                            Optional<StreamsInitializeRequestManager> streamsInitializeRequestManager) {
         this.log = logContext.logger(RequestManagers.class);
@@ -113,6 +113,8 @@ public class RequestManagers implements Closeable {
         this.shareHeartbeatRequestManager = shareHeartbeatRequestManager;
         this.consumerMembershipManager = Optional.empty();
         this.shareMembershipManager = shareMembershipManager;
+        this.streamsHeartbeatRequestManager = Optional.empty();
+        this.streamsInitializeRequestManager = Optional.empty();
         this.offsetsRequestManager = null;
         this.topicMetadataRequestManager = null;
         this.fetchRequestManager = null;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 7b3713b4131..2b3b7c8f248 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -61,7 +61,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final StreamsGroupHeartbeatRequestManager.HeartbeatState heartbeatState;
 
-    private final MembershipManager membershipManager;
+    private final ConsumerMembershipManager membershipManager;
 
     private final StreamsInitializeRequestManager streamsInitializeRequestManager;
 
@@ -83,7 +83,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         final ConsumerConfig config,
         final CoordinatorRequestManager coordinatorRequestManager,
         final StreamsInitializeRequestManager streamsInitializeRequestManager,
-        final MembershipManager membershipManager,
+        final ConsumerMembershipManager membershipManager,
         final BackgroundEventHandler backgroundEventHandler,
         final Metrics metrics,
         final StreamsAssignmentInterface streamsAssignmentInterface,
@@ -158,7 +158,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
                                                                      final boolean ignoreResponse) {
         NetworkClientDelegate.UnsentRequest request = makeHeartbeatRequest(ignoreResponse);
         heartbeatRequestState.onSendAttempt(currentTimeMs);
-        membershipManager.onHeartbeatRequestSent();
+        membershipManager.onHeartbeatRequestGenerated();
         metricsManager.recordHeartbeatSentMs(currentTimeMs);
         return request;
     }
@@ -335,7 +335,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
         this.heartbeatState.reset();
         this.heartbeatRequestState.onFailedAttempt(currentTimeMs);
-        membershipManager.onHeartbeatFailure();
+        membershipManager.onHeartbeatFailure(false);
 
         switch (error) {
             case NOT_COORDINATOR:
@@ -503,7 +503,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     static class HeartbeatState {
 
-        private final MembershipManager membershipManager;
+        private final ConsumerMembershipManager membershipManager;
         private final int rebalanceTimeoutMs;
         private final StreamsGroupHeartbeatRequestManager.HeartbeatState.SentFields sentFields;
 
@@ -514,7 +514,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
         public HeartbeatState(
             final StreamsAssignmentInterface streamsInterface,
-            final MembershipManager membershipManager,
+            final ConsumerMembershipManager membershipManager,
             final int rebalanceTimeoutMs) {
             this.membershipManager = membershipManager;
             this.rebalanceTimeoutMs = rebalanceTimeoutMs;
@@ -552,9 +552,9 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             // Immutable -- only sent when joining
             if (joining) {
                 data.setProcessId(streamsInterface.processID().toString());
-//                data.setActiveTasks(Collections.emptyList());
-//                data.setStandbyTasks(Collections.emptyList());
-//                data.setWarmupTasks(Collections.emptyList());
+                data.setActiveTasks(Collections.emptyList());
+                data.setStandbyTasks(Collections.emptyList());
+                data.setWarmupTasks(Collections.emptyList());
                 streamsInterface.endpoint().ifPresent(streamsEndpoint -> {
                     data.setUserEndpoint(new StreamsGroupHeartbeatRequestData.Endpoint()
                         .setHost(streamsEndpoint.host)
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index f4c67e1d9b9..aed1b4dafd7 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -55,7 +55,6 @@ import java.util.Properties;
 import java.util.UUID;
 import java.util.stream.Collectors;
 
-import static org.apache.kafka.clients.consumer.internals.ConsumerTestBuilder.DEFAULT_MAX_POLL_INTERVAL_MS;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.common.utils.Utils.mkSet;
@@ -74,6 +73,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
     public static final int TEST_MEMBER_EPOCH = 5;
     public static final String TEST_INSTANCE_ID = "instanceId";
     public static final int TEST_THROTTLE_TIME_MS = 5;
+    private static final int DEFAULT_MAX_POLL_INTERVAL_MS = 10000;
     private StreamsGroupHeartbeatRequestManager heartbeatRequestManager;
 
     private Time time;
@@ -89,7 +89,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
     private StreamsInitializeRequestManager streamsInitializeRequestManager;
 
     @Mock
-    private MembershipManager membershipManager;
+    private ConsumerMembershipManager membershipManager;
 
     @Mock
     private BackgroundEventHandler backgroundEventHandler;
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
index 28f938c2657..c56bef00c9f 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessorTest.java
@@ -97,8 +97,6 @@ public class ApplicationEventProcessorTest {
                 withGroupId ? Optional.of(heartbeatRequestManager) : Optional.empty(),
                 withGroupId ? Optional.of(membershipManager) : Optional.empty(),
                 Optional.empty(),
-                Optional.empty(),
-                Optional.empty(),
                 Optional.empty()
         );
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index 63d5523f137..7b7a2d701f8 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -271,7 +271,7 @@ public class GroupCoordinatorRecordHelpers {
      * @param memberId The consumer group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newTargetAssignmentTombstoneRecord(
+    public static CoordinatorRecord newConsumerGroupTargetAssignmentTombstoneRecord(
         String groupId,
         String memberId
     ) {
@@ -317,7 +317,7 @@ public class GroupCoordinatorRecordHelpers {
      * @param groupId The consumer group id.
      * @return The record.
      */
-    public static CoordinatorRecord newConsumerTargetAssignmentEpochTombstoneRecord(
+    public static CoordinatorRecord newConsumerGroupTargetAssignmentEpochTombstoneRecord(
         String groupId
     ) {
         return new CoordinatorRecord(
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index e934304b168..3e51e4b798a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -3534,7 +3534,7 @@ public class GroupMetadataManager {
         if (!updatedMember.equals(member)) {
             records.add(newStreamsGroupMemberRecord(groupId, updatedMember));
 
-            if (updatedMember.topologyId().equals(member.topologyId())) {
+            if (!updatedMember.topologyId().equals(member.topologyId())) {
                 log.info("[GroupId {}] Member {} updated its topology ID to: {}.",
                     groupId, memberId, updatedMember.topologyId());
                 return true;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index f5cac3026aa..2f48151e137 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -58,7 +58,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 14
+                (short) 17
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMemberMetadataValue()
@@ -96,7 +96,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 14
+                (short) 17
             ),
             null // Tombstone.
         );
@@ -137,7 +137,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 13
+                (short) 16
             ),
             new ApiMessageAndVersion(
                 value,
@@ -159,7 +159,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 13
+                (short) 16
             ),
             null // Tombstone.
         );
@@ -173,7 +173,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 12
+                (short) 15
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataValue()
@@ -196,7 +196,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 12
+                (short) 15
             ),
             null // Tombstone.
         );
@@ -239,7 +239,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 16
+                (short) 19
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMemberValue()
@@ -267,7 +267,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 16
+                (short) 19
             ),
             null // Tombstone.
         );
@@ -282,7 +282,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 15
+                (short) 18
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataValue()
@@ -305,7 +305,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 15
+                (short) 18
             ),
             null // Tombstone.
         );
@@ -320,7 +320,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 17
+                (short) 20
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupCurrentMemberAssignmentValue()
@@ -352,7 +352,7 @@ public class CoordinatorStreamsRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 17
+                (short) 20
             ),
             null // Tombstone
         );
@@ -402,7 +402,10 @@ public class CoordinatorStreamsRecordHelpers {
                 .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
         });
 
-        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 18),
+        return new CoordinatorRecord(new ApiMessageAndVersion(
+            new StreamsGroupTopologyKey()
+                .setGroupId(groupId),
+            (short) 21),
             new ApiMessageAndVersion(value, (short) 0));
     }
 
@@ -419,7 +422,7 @@ public class CoordinatorStreamsRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId(groupId),
-                (short) 18
+                (short) 21
             ),
             null // Tombstone
         );
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
index 771f7324a9e..a99e32754c6 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupCurrentMemberAssignmentKey",
-  "validVersions": "17",
+  "validVersions": "20",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "17",
+    { "name": "GroupId", "type": "string", "versions": "20",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "17",
+    { "name": "MemberId", "type": "string", "versions": "20",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
index bac9ac247cf..8e0f66deba7 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupMemberMetadataKey",
-  "validVersions": "14",
+  "validVersions": "17",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "14",
+    { "name": "GroupId", "type": "string", "versions": "17",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "14",
+    { "name": "MemberId", "type": "string", "versions": "17",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
index 26121bf2ba2..6c54fb8bd14 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupMetadataKey",
-  "validVersions": "12",
+  "validVersions": "15",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "12",
+    { "name": "GroupId", "type": "string", "versions": "15",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
index 546a8f80535..0d91a992d0c 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupPartitionMetadataKey",
-  "validVersions": "13",
+  "validVersions": "16",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "13",
+    { "name": "GroupId", "type": "string", "versions": "16",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
index 4fc8231ec3d..f96f6f89e01 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMemberKey",
-  "validVersions": "16",
+  "validVersions": "19",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "16",
+    { "name": "GroupId", "type": "string", "versions": "19",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "16",
+    { "name": "MemberId", "type": "string", "versions": "19",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
index 02b40f727c4..514885f8ad7 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMetadataKey",
-  "validVersions": "15",
+  "validVersions": "18",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "15",
+    { "name": "GroupId", "type": "string", "versions": "18",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
index 261b755cd51..2e51c117bd7 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTopologyKey",
-  "validVersions": "18",
+  "validVersions": "21",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "18",
+    { "name": "GroupId", "type": "string", "versions": "21",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index 5b1aad09027..dfd898c225c 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -273,7 +273,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
@@ -298,7 +299,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
@@ -350,7 +352,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupInitializeRequestData request = new StreamsGroupInitializeRequestData()
@@ -385,7 +388,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
@@ -410,7 +414,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
@@ -461,7 +466,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
 
         StreamsGroupHeartbeatRequestData request = new StreamsGroupHeartbeatRequestData()
@@ -1779,7 +1785,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
         int partitionCount = 2;
         service.startup(() -> partitionCount);
@@ -1821,7 +1828,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
         int partitionCount = 1;
         service.startup(() -> partitionCount);
@@ -1855,7 +1863,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
         int partitionCount = 1;
         service.startup(() -> partitionCount);
@@ -1887,7 +1896,8 @@ public class GroupCoordinatorServiceTest {
             new LogContext(),
             createConfig(),
             runtime,
-            new GroupCoordinatorMetrics()
+            new GroupCoordinatorMetrics(),
+            createConfigManager()
         );
         when(runtime.scheduleReadOperation(
             ArgumentMatchers.eq("streams-group-describe"),
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 44b46421205..cf1a003cd84 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -96,7 +96,7 @@ class CoordinatorStreamsRecordHelpersTest {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId("group-id"),
-                (short) 18),
+                (short) 21),
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyValue()
                     .setTopology(expectedTopology),
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 3da224f3a95..2fd5d461c99 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -649,7 +649,7 @@ public class StreamsGroupTest {
             group.validateOffsetFetch("member-id", 0, Long.MAX_VALUE));
 
         // Create a member.
-        snapshotRegistry.getOrCreateSnapshot(0);
+        snapshotRegistry.idempotentCreateSnapshot(0);
         group.updateMember(new StreamsGroupMember.Builder("member-id").build());
 
         // The member does not exist at last committed offset 0.
@@ -716,13 +716,13 @@ public class StreamsGroupTest {
             new TopicPartition("__consumer_offsets", 0)
         );
         StreamsGroup group = new StreamsGroup(snapshotRegistry, "group-foo", metricsShard);
-        snapshotRegistry.getOrCreateSnapshot(0);
+        snapshotRegistry.idempotentCreateSnapshot(0);
         assertTrue(group.isInStates(Collections.singleton("empty"), 0));
         assertFalse(group.isInStates(Collections.singleton("Empty"), 0));
 
         group.updateMember(new StreamsGroupMember.Builder("member1")
             .build());
-        snapshotRegistry.getOrCreateSnapshot(1);
+        snapshotRegistry.idempotentCreateSnapshot((1));
         assertTrue(group.isInStates(Collections.singleton("empty"), 0));
         assertTrue(group.isInStates(Collections.singleton("stable"), 1));
         assertFalse(group.isInStates(Collections.singleton("empty"), 1));
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
index 936c9eb6a85..19eb361a1d3 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/assignment/TaskAssignorConvergenceTest.java
@@ -471,8 +471,8 @@ public class TaskAssignorConvergenceTest {
 
     @ParameterizedTest
     @ValueSource(strings = {
-        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_NONE,
-        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_MIN_TRAFFIC,
+//        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_NONE,
+//        StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_MIN_TRAFFIC,
         StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_BALANCE_SUBTOPOLOGY
     })
     public void randomClusterPerturbationsShouldConverge(final String rackAwareStrategy) {


(kafka) 16/42: Reslove confict from 11/25 trunk rebase - Replay all streams-related records

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit cc4985e5972aea2af26c20aae6eb79622e16b66f
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Mon Jun 24 16:43:11 2024 +0200

    Reslove confict from 11/25 trunk rebase - Replay all streams-related records
    
    See https://github.com/lucasbru/kafka/pull/23
---
 .../coordinator/group/GroupCoordinatorShard.java   |  63 +++++++
 .../coordinator/group/GroupMetadataManager.java    | 204 ++++++++++++++++++++-
 .../coordinator/group/streams/StreamsGroup.java    |   6 +-
 3 files changed, 265 insertions(+), 8 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 2eed6f395e3..7c153077b76 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -90,6 +90,20 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.image.MetadataDelta;
@@ -932,6 +946,55 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 );
                 break;
 
+            case 15:
+                groupMetadataManager.replay(
+                    (StreamsGroupMetadataKey) key.message(),
+                    (StreamsGroupMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case 16:
+                groupMetadataManager.replay(
+                    (StreamsGroupPartitionMetadataKey) key.message(),
+                    (StreamsGroupPartitionMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case 17:
+                groupMetadataManager.replay(
+                    (StreamsGroupMemberMetadataKey) key.message(),
+                    (StreamsGroupMemberMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case 18:
+                groupMetadataManager.replay(
+                    (StreamsGroupTargetAssignmentMetadataKey) key.message(),
+                    (StreamsGroupTargetAssignmentMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case 19:
+                groupMetadataManager.replay(
+                    (StreamsGroupTargetAssignmentMemberKey) key.message(),
+                    (StreamsGroupTargetAssignmentMemberValue) messageOrNull(value)
+                );
+                break;
+
+            case 20:
+                groupMetadataManager.replay(
+                    (StreamsGroupCurrentMemberAssignmentKey) key.message(),
+                    (StreamsGroupCurrentMemberAssignmentValue) messageOrNull(value)
+                );
+                break;
+
+            case 21:
+                groupMetadataManager.replay(
+                    (StreamsGroupTopologyKey) key.message(),
+                    (StreamsGroupTopologyValue) messageOrNull(value)
+                );
+                break;
+
             default:
                 throw new IllegalStateException("Received an unknown record type " + key.version()
                     + " in " + record);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 716d42e6701..fe4d7d7eaf6 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -107,6 +107,18 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
@@ -122,6 +134,9 @@ import org.apache.kafka.coordinator.group.modern.consumer.ResolvedRegularExpress
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupAssignmentBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
+import org.apache.kafka.coordinator.group.streams.StreamsTopology;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.image.TopicImage;
@@ -165,6 +180,7 @@ import static org.apache.kafka.common.requests.JoinGroupRequest.UNKNOWN_MEMBER_I
 import static org.apache.kafka.coordinator.group.Group.GroupType.CLASSIC;
 import static org.apache.kafka.coordinator.group.Group.GroupType.CONSUMER;
 import static org.apache.kafka.coordinator.group.Group.GroupType.SHARE;
+import static org.apache.kafka.coordinator.group.Group.GroupType.STREAMS;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupCurrentAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newConsumerGroupEpochRecord;
@@ -206,6 +222,7 @@ import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMe
 @SuppressWarnings("JavaNCSS")
 public class GroupMetadataManager {
 
+
     public static class Builder {
         private LogContext logContext = null;
         private SnapshotRegistry snapshotRegistry = null;
@@ -922,6 +939,46 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * The method should be called on the replay path.
+     * Gets or maybe creates a streams group and updates the groups map if a new group is created.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A StreamsGroup.
+     * @throws IllegalStateException if the group does not exist and createIfNotExists is false or
+     *                               if the group is not a consumer group.
+     * Package private for testing.
+     */
+    StreamsGroup getOrMaybeCreatePersistedStreamsGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new IllegalStateException(String.format("Streams group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, groupId, metrics);
+            groups.put(groupId, streamsGroup);
+            // ToDo: migrate to streams group
+//            metrics.onConsumerGroupStateTransition(null, streamsGroup.state());
+            return streamsGroup;
+        } else {
+            if (group.type() == STREAMS) {
+                return (StreamsGroup) group;
+            } else {
+                // We don't support upgrading/downgrading between protocols at the moment so
+                // we throw an exception if a group exists with the wrong type.
+                throw new IllegalStateException(String.format("Group %s is not a streams group.", groupId));
+            }
+        }
+    }
+
     /**
      * Gets or maybe creates a classic group.
      *
@@ -3768,12 +3825,24 @@ public class GroupMetadataManager {
         StreamsGroupTopologyKey key,
         StreamsGroupTopologyValue value
     ) {
-
-        // TODO: Insert the topology information to the in-memory representation. Needs the notion
-        //       of a Streams group
-//        String groupId = key.groupId();
-//        StreamsGroup streamsGroup = getOrMaybeCreatePersistedConsumerGroup(groupId, value != null);
-//        streamsGroup.setTopology(value);
+        String groupId = key.groupId();
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, value != null);
+        Set<String> oldSubscribedTopicNames = new HashSet<>(streamsGroup.subscriptionMetadata().keySet());
+        if (value != null) {
+            StreamsTopology topology = StreamsTopology.fromRecord(value);
+            streamsGroup.setTopology(topology);
+            Set<String> newSubscribedTopicNames = new HashSet<>();
+            topology.subtopologies().forEach(
+                (subtopologyId, subtopology) -> {
+                    newSubscribedTopicNames.addAll(subtopology.sourceTopics());
+                    newSubscribedTopicNames.addAll(subtopology.repartitionSourceTopics().stream()
+                        .map(StreamsGroupTopologyValue.TopicInfo::name).collect(Collectors.toSet()));
+                }
+            );
+            updateGroupsByTopics(groupId, oldSubscribedTopicNames, newSubscribedTopicNames);
+        } else {
+            updateGroupsByTopics(groupId, oldSubscribedTopicNames, Collections.emptySet());
+        }
     }
 
     /**
@@ -4217,7 +4286,6 @@ public class GroupMetadataManager {
             if (!shareGroup.members().isEmpty()) {
                 throw new IllegalStateException("Received a tombstone record to delete group " + groupId
                     + " but the group still has " + shareGroup.members().size() + " members.");
-            }
             if (!shareGroup.targetAssignment().isEmpty()) {
                 throw new IllegalStateException("Received a tombstone record to delete group " + groupId
                     + " but the target assignment still has " + shareGroup.targetAssignment().size()
@@ -4229,7 +4297,129 @@ public class GroupMetadataManager {
             }
             removeGroup(groupId);
         }
+    }
+
+    /**
+     * Replays StreamsGroupMemberMetadataKey/Value to update the hard state of
+     * the streams group. It updates the subscription part of the member or
+     * deletes the member.
+     *
+     * @param key   A StreamsGroupMemberMetadataKey key.
+     * @param value A StreamsGroupMemberMetadataValue record.
+     */
+    public void replay(
+        StreamsGroupMemberMetadataKey key,
+        StreamsGroupMemberMetadataValue value
+    ) {
+        String groupId = key.groupId();
+        String memberId = key.memberId();
+
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, value != null);
+        Set<String> oldSubscribedTopicNames = new HashSet<>(streamsGroup.subscriptionMetadata().keySet());
+
+        if (value != null) {
+            StreamsGroupMember oldMember = streamsGroup.getOrMaybeCreateMember(memberId, true);
+            streamsGroup.updateMember(new StreamsGroupMember.Builder(oldMember)
+                .updateWith(value)
+                .build());
+        } else {
+            StreamsGroupMember oldMember = streamsGroup.getOrMaybeCreateMember(memberId, false);
+            if (oldMember.memberEpoch() != LEAVE_GROUP_MEMBER_EPOCH) {
+                throw new IllegalStateException("Received a tombstone record to delete member " + memberId
+                    + " but did not receive StreamsGroupCurrentMemberAssignmentValue tombstone.");
+            }
+            if (streamsGroup.targetAssignment().containsKey(memberId)) {
+                throw new IllegalStateException("Received a tombstone record to delete member " + memberId
+                    + " but did not receive StreamsGroupTargetAssignmentMetadataValue tombstone.");
+            }
+            streamsGroup.removeMember(memberId);
+        }
 
+        // ToDo: this is probably a no-op for a streams group since the subscribed topics do not change
+        // between group members.
+        updateGroupsByTopics(groupId, oldSubscribedTopicNames, streamsGroup.subscriptionMetadata().keySet());
+    }
+
+    /**
+     * Replays StreamsGroupTargetAssignmentMetadataKey/Value to update the hard state of
+     * the streams group. It updates the target assignment epoch or set it to -1 to signal
+     * that it has been deleted.
+     *
+     * @param key   A StreamsGroupTargetAssignmentMetadataKey key.
+     * @param value A StreamsGroupTargetAssignmentMetadataValue record.
+     */
+    public void replay(
+        StreamsGroupTargetAssignmentMetadataKey key,
+        StreamsGroupTargetAssignmentMetadataValue value
+    ) {
+        String groupId = key.groupId();
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
+
+        if (value != null) {
+            streamsGroup.setTargetAssignmentEpoch(value.assignmentEpoch());
+        } else {
+            if (!streamsGroup.targetAssignment().isEmpty()) {
+                throw new IllegalStateException("Received a tombstone record to delete target assignment of " + groupId
+                    + " but the assignment still has " + streamsGroup.targetAssignment().size() + " members.");
+            }
+            streamsGroup.setTargetAssignmentEpoch(-1);
+        }
+    }
+
+    /**
+     * Replays StreamsGroupTargetAssignmentMemberKey/Value to update the hard state of
+     * the consumer group. It updates the target assignment of the member or deletes it.
+     *
+     * @param key   A ConsumerGroupTargetAssignmentMemberKey key.
+     * @param value A ConsumerGroupTargetAssignmentMemberValue record.
+     */
+    public void replay(
+        StreamsGroupTargetAssignmentMemberKey key,
+        StreamsGroupTargetAssignmentMemberValue value
+    ) {
+        String groupId = key.groupId();
+        String memberId = key.memberId();
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
+
+        if (value != null) {
+            streamsGroup.updateTargetAssignment(memberId, org.apache.kafka.coordinator.group.streams.Assignment.fromRecord(value));
+        } else {
+            streamsGroup.removeTargetAssignment(memberId);
+        }
+    }
+
+    /**
+     * Replays ConsumerGroupCurrentMemberAssignmentKey/Value to update the hard state of
+     * the consumer group. It updates the assignment of a member or deletes it.
+     *
+     * @param key   A ConsumerGroupCurrentMemberAssignmentKey key.
+     * @param value A ConsumerGroupCurrentMemberAssignmentValue record.
+     */
+    public void replay(
+        StreamsGroupCurrentMemberAssignmentKey key,
+        StreamsGroupCurrentMemberAssignmentValue value
+    ) {
+        String groupId = key.groupId();
+        String memberId = key.memberId();
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
+        StreamsGroupMember oldMember = streamsGroup.getOrMaybeCreateMember(memberId, false);
+
+        if (value != null) {
+            StreamsGroupMember newMember = new StreamsGroupMember.Builder(oldMember)
+                .updateWith(value)
+                .build();
+            streamsGroup.updateMember(newMember);
+        } else {
+            StreamsGroupMember newMember = new StreamsGroupMember.Builder(oldMember)
+                .setMemberEpoch(LEAVE_GROUP_MEMBER_EPOCH)
+                .setPreviousMemberEpoch(LEAVE_GROUP_MEMBER_EPOCH)
+                .setAssignedActiveTasks(Collections.emptyMap())
+                .setAssignedStandbyTasks(Collections.emptyMap())
+                .setAssignedWarmupTasks(Collections.emptyMap())
+                .setActiveTasksPendingRevocation(Collections.emptyMap())
+                .build();
+            streamsGroup.updateMember(newMember);
+        }
     }
 
     /**
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 4ba97bc2288..d90e749e303 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -173,7 +173,7 @@ public class StreamsGroup implements Group {
     /**
      * The Streams topology.
      */
-    private final StreamsTopology topology;
+    private StreamsTopology topology;
 
     /**
      * The metadata refresh deadline. It consists of a timestamp in milliseconds together with the group epoch at the time of setting it.
@@ -247,6 +247,10 @@ public class StreamsGroup implements Group {
         return topology;
     }
 
+    public void setTopology(StreamsTopology topology) {
+        this.topology = topology;
+    }
+
     /**
      * @return The group id.
      */


(kafka) 38/42: Correctness updates from rebase

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit e19b7e0873701cc369d4027c3a9cc4c11219a49e
Author: Bill <bb...@apache.org>
AuthorDate: Mon Nov 25 17:35:16 2024 -0500

    Correctness updates from rebase
---
 .../clients/consumer/internals/AsyncKafkaConsumer.java  |  4 +---
 .../consumer/internals/StreamsMembershipManager.java    |  1 +
 .../events/StreamsOnAssignmentCallbackNeededEvent.java  |  1 -
 .../consumer/internals/AsyncKafkaConsumerTest.java      |  5 +++--
 .../internals/StreamsMembershipManagerTest.java         |  2 +-
 .../kafka/coordinator/group/GroupCoordinatorShard.java  | 17 +++++++++--------
 .../kafka/coordinator/group/streams/StreamsGroup.java   |  1 +
 .../group/streams/topics/InternalTopicManager.java      |  1 +
 .../message/ConsumerGroupRegularExpressionKey.json      |  4 ++--
 .../message/StreamsGroupPartitionMetadataKey.json       |  4 ++--
 .../coordinator/group/GroupMetadataManagerTest.java     |  3 +++
 .../group/streams/StreamsConfiguredTopologyTest.java    |  1 +
 .../coordinator/group/streams/StreamsGroupTest.java     |  1 +
 .../coordinator/group/streams/StreamsTopologyTest.java  |  1 +
 .../group/streams/topics/InternalTopicManagerTest.java  |  1 +
 .../KafkaStreamsTelemetryIntegrationTest.java           |  6 ++++++
 .../integration/SmokeTestDriverIntegrationTest.java     |  4 ++--
 17 files changed, 36 insertions(+), 21 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
index 65cea62ea64..459d26c6010 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
@@ -276,7 +276,7 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
         }
     };
 
-   public AsyncKafkaConsumer(final ConsumerConfig config,
+    public AsyncKafkaConsumer(final ConsumerConfig config,
                               final Deserializer<K> keyDeserializer,
                               final Deserializer<V> valueDeserializer,
                               final Optional<StreamsAssignmentInterface> streamsAssignmentInterface) {
@@ -373,7 +373,6 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
                     metrics,
                     offsetCommitCallbackInvoker,
                     memberStateListener,
-                    this::updateGroupMetadata,
                     streamsAssignmentInterface
             );
             final Supplier<ApplicationEventProcessor> applicationEventProcessorSupplier = ApplicationEventProcessor.supplier(logContext,
@@ -548,7 +547,6 @@ public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
             metrics,
             offsetCommitCallbackInvoker,
             memberStateListener,
-            this::updateGroupMetadata,
             streamsInstanceMetadata
         );
         Supplier<ApplicationEventProcessor> applicationEventProcessorSupplier = ApplicationEventProcessor.supplier(
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
index ef39f661f67..fb34f50847b 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java
@@ -32,6 +32,7 @@ import org.apache.kafka.common.telemetry.internals.ClientTelemetryProvider;
 import org.apache.kafka.common.telemetry.internals.ClientTelemetryReporter;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
+
 import org.slf4j.Logger;
 
 import java.util.Collections;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
index 8c2f5a3bc81..5ef6cd9c462 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/StreamsOnAssignmentCallbackNeededEvent.java
@@ -39,4 +39,3 @@ public class StreamsOnAssignmentCallbackNeededEvent extends CompletableBackgroun
             ", assignment=" + assignment;
     }
 }
-
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
index 3ba8e2a1cab..2079d0c44ac 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumerTest.java
@@ -204,7 +204,8 @@ public class AsyncKafkaConsumerTest {
             a -> backgroundEventReaper,
             (a, b, c, d, e, f, g) -> fetchCollector,
             (a, b, c, d) -> metadata,
-            backgroundEventQueue
+            backgroundEventQueue,
+                Optional.empty()
         );
     }
 
@@ -219,7 +220,7 @@ public class AsyncKafkaConsumerTest {
             (a, b, c, d, e, f, g) -> fetchCollector,
             (a, b, c, d) -> metadata,
             backgroundEventQueue,
-            Optional.empty()
+                Optional.empty()
         );
     }
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
index 4965f05198b..7d954477da9 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManagerTest.java
@@ -28,9 +28,9 @@ import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.utils.LogContext;
-
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
+
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 895a7508696..4270e0d80c9 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -110,6 +110,7 @@ import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.timeline.SnapshotRegistry;
+
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
@@ -945,56 +946,56 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 );
                 break;
 
-            case 16:
+            case 15:
                 groupMetadataManager.replay(
                     (ConsumerGroupRegularExpressionKey) key.message(),
                     (ConsumerGroupRegularExpressionValue) Utils.messageOrNull(value)
                 );
                 break;
 
-            case 15:
+            case 16:
                 groupMetadataManager.replay(
                     (StreamsGroupMetadataKey) key.message(),
                     (StreamsGroupMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 16:
+            case 17:
                 groupMetadataManager.replay(
                     (StreamsGroupPartitionMetadataKey) key.message(),
                     (StreamsGroupPartitionMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 17:
+            case 18:
                 groupMetadataManager.replay(
                     (StreamsGroupMemberMetadataKey) key.message(),
                     (StreamsGroupMemberMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 18:
+            case 19:
                 groupMetadataManager.replay(
                     (StreamsGroupTargetAssignmentMetadataKey) key.message(),
                     (StreamsGroupTargetAssignmentMetadataValue) messageOrNull(value)
                 );
                 break;
 
-            case 19:
+            case 20:
                 groupMetadataManager.replay(
                     (StreamsGroupTargetAssignmentMemberKey) key.message(),
                     (StreamsGroupTargetAssignmentMemberValue) messageOrNull(value)
                 );
                 break;
 
-            case 20:
+            case 21:
                 groupMetadataManager.replay(
                     (StreamsGroupCurrentMemberAssignmentKey) key.message(),
                     (StreamsGroupCurrentMemberAssignmentValue) messageOrNull(value)
                 );
                 break;
 
-            case 21:
+            case 22:
                 groupMetadataManager.replay(
                     (StreamsGroupTopologyKey) key.message(),
                     (StreamsGroupTopologyValue) messageOrNull(value)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index fac219c5ed4..5ec4d1559bf 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -41,6 +41,7 @@ import org.apache.kafka.timeline.SnapshotRegistry;
 import org.apache.kafka.timeline.TimelineHashMap;
 import org.apache.kafka.timeline.TimelineInteger;
 import org.apache.kafka.timeline.TimelineObject;
+
 import org.slf4j.Logger;
 
 import java.util.Collections;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
index cc2383fae42..9ebec6c30cb 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManager.java
@@ -22,6 +22,7 @@ import org.apache.kafka.common.message.CreateTopicsRequestData.CreatableTopicCon
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.streams.TopicMetadata;
+
 import org.slf4j.Logger;
 
 import java.util.Collection;
diff --git a/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json b/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
index 3f761b694e4..2cb82e4de10 100644
--- a/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
+++ b/group-coordinator/src/main/resources/common/message/ConsumerGroupRegularExpressionKey.json
@@ -20,9 +20,9 @@
   "validVersions": "16",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "16",
+    { "name": "GroupId", "type": "string", "versions": "44",
       "about": "The group id." },
-    { "name": "RegularExpression", "type": "string", "versions": "16",
+    { "name": "RegularExpression", "type": "string", "versions": "44",
       "about": "The regular expression." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
index 0d91a992d0c..618fbc78451 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupPartitionMetadataKey",
-  "validVersions": "16",
+  "validVersions": "56",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "16",
+    { "name": "GroupId", "type": "string", "versions": "56",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 4cf7f099d26..e120a057642 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -114,7 +114,10 @@ import org.junit.jupiter.params.provider.ValueSource;
 import org.opentest4j.AssertionFailedError;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java
index 9e91b36f0b2..e965ea58fac 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsConfiguredTopologyTest.java
@@ -19,6 +19,7 @@ package org.apache.kafka.coordinator.group.streams;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.streams.topics.ConfiguredInternalTopic;
 import org.apache.kafka.coordinator.group.streams.topics.ConfiguredSubtopology;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.Collections;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 1269587d6c4..dc928dd695d 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -30,6 +30,7 @@ import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState;
 import org.apache.kafka.timeline.SnapshotRegistry;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
index 54f8de1a3da..44074612a93 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -19,6 +19,7 @@ package org.apache.kafka.coordinator.group.streams;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
index ecde45d96d5..09e53428c08 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/topics/InternalTopicManagerTest.java
@@ -24,6 +24,7 @@ import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.streams.TopicMetadata;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
index 18dbd2fa6d8..fc90c621435 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
@@ -22,6 +22,7 @@ import org.apache.kafka.clients.admin.AdminClientConfig;
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.producer.KafkaProducer;
 import org.apache.kafka.clients.producer.Producer;
 import org.apache.kafka.common.Metric;
@@ -430,6 +431,11 @@ public class KafkaStreamsTelemetryIntegrationTest {
             return consumer;
         }
 
+        @Override
+        public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(Map<String, Object> config, StreamsAssignmentInterface assignmentInterface) {
+            return null;
+        }
+
         @Override
         public Consumer<byte[], byte[]> getRestoreConsumer(final Map<String, Object> config) {
             return new KafkaConsumer<>(config, new ByteArrayDeserializer(), new ByteArrayDeserializer());
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index 498613ce783..4ed0e946426 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.streams.integration;
 
-import kafka.api.IntegrationTestHarness;
+
 
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.common.utils.Exit;
@@ -44,7 +44,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 @Timeout(600)
 @Tag("integration")
-public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
+public class SmokeTestDriverIntegrationTest {
 
     @Override
     public int brokerCount() {


(kafka) 27/42: Add broker configs for streams group

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 51155f993e68e4a7a2a1c60e9d1e0cff86901b1e
Author: Matthias J. Sax <ma...@confluent.io>
AuthorDate: Thu Sep 5 07:27:15 2024 -0700

    Add broker configs for streams group
    
    Adds broker configs for Streams group for the MVP.
---
 .../consumer/internals/AsyncKafkaConsumer.java     |  1 +
 .../coordinator/group/GroupCoordinatorConfig.java  | 51 ++++++++++++++++++++++
 .../coordinator/group/GroupCoordinatorShard.java   |  2 +-
 .../metrics/GroupCoordinatorMetricsShard.java      |  6 +++
 .../group/GroupCoordinatorConfigTest.java          | 28 +++++++++++-
 .../kafka/server/config/AbstractKafkaConfig.java   |  1 +
 6 files changed, 87 insertions(+), 2 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
index 807c900f6b9..65cea62ea64 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java
@@ -159,6 +159,7 @@ import static org.apache.kafka.common.utils.Utils.swallow;
  * This class should not be invoked directly; users should instead create a {@link KafkaConsumer} as before.
  * This consumer implements the new consumer group protocol and is intended to be the default in coming releases.
  */
+@SuppressWarnings("this-escape")
 public class AsyncKafkaConsumer<K, V> implements ConsumerDelegate<K, V> {
 
     private static final long NO_CURRENT_THREAD = -1L;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfig.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfig.java
index f94b2cc706b..cf1aa60e52f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfig.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfig.java
@@ -162,6 +162,19 @@ public class GroupCoordinatorConfig {
     public static final int SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_DEFAULT = 15000;
     public static final String SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_DOC = "The maximum heartbeat interval for share group members.";
 
+    /** Streams group configs */
+    public static final String STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG = "group.streams.session.timeout.ms";
+    public static final int STREAMS_GROUP_SESSION_TIMEOUT_MS_DEFAULT = 45000;
+    public static final String STREAMS_GROUP_SESSION_TIMEOUT_MS_DOC = "The timeout to detect client failures when using the streams group protocol.";
+
+    public static final String STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG = "group.streams.heartbeat.interval.ms";
+    public static final int STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_DEFAULT = 5000;
+    public static final String STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_DOC = "The heartbeat interval given to the members of a streams group.";
+
+    public static final String STREAMS_GROUP_NUM_STANDBY_REPLICAS_CONFIG = "group.streams.num.standby.replicas";
+    public static final int STREAMS_GROUP_NUM_STANDBY_REPLICAS_DEFAULT = 0;
+    public static final String STREAMS_GROUP_NUM_STANDBY_REPLICAS_DOC = "The number of standby replicas for each task.";
+
     public static final String OFFSET_METADATA_MAX_SIZE_CONFIG = "offset.metadata.max.bytes";
     public static final int OFFSET_METADATA_MAX_SIZE_DEFAULT = 4096;
     public static final String OFFSET_METADATA_MAX_SIZE_DOC = "The maximum size for a metadata entry associated with an offset commit.";
@@ -248,6 +261,10 @@ public class GroupCoordinatorConfig {
             .define(SHARE_GROUP_MIN_HEARTBEAT_INTERVAL_MS_CONFIG, INT, SHARE_GROUP_MIN_HEARTBEAT_INTERVAL_MS_DEFAULT, atLeast(1), MEDIUM, SHARE_GROUP_MIN_HEARTBEAT_INTERVAL_MS_DOC)
             .define(SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_CONFIG, INT, SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_DEFAULT, atLeast(1), MEDIUM, SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_DOC)
             .define(SHARE_GROUP_MAX_SIZE_CONFIG, INT, SHARE_GROUP_MAX_SIZE_DEFAULT, between(10, 1000), MEDIUM, SHARE_GROUP_MAX_SIZE_DOC);
+    public static final ConfigDef STREAMS_GROUP_CONFIG_DEF =  new ConfigDef()
+            .define(STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG, INT, STREAMS_GROUP_SESSION_TIMEOUT_MS_DEFAULT, atLeast(1), MEDIUM, STREAMS_GROUP_SESSION_TIMEOUT_MS_DOC)
+            .define(STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, INT, STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_DEFAULT, atLeast(1), MEDIUM, STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_DOC)
+            .define(STREAMS_GROUP_NUM_STANDBY_REPLICAS_CONFIG, INT, STREAMS_GROUP_NUM_STANDBY_REPLICAS_DEFAULT, atLeast(0), MEDIUM, STREAMS_GROUP_NUM_STANDBY_REPLICAS_DOC);
 
     /**
      * The timeout used to wait for a new member in milliseconds.
@@ -286,6 +303,11 @@ public class GroupCoordinatorConfig {
     private final int shareGroupHeartbeatIntervalMs;
     private final int shareGroupMinHeartbeatIntervalMs;
     private final int shareGroupMaxHeartbeatIntervalMs;
+    // Streams group configurations
+    private final int streamsGroupSessionTimeoutMs;
+    private final int streamsGroupHeartbeatIntervalMs;
+    private final int streamsGroupNumStandbyReplicas;
+
 
     public GroupCoordinatorConfig(AbstractConfig config) {
         this.numThreads = config.getInt(GroupCoordinatorConfig.GROUP_COORDINATOR_NUM_THREADS_CONFIG);
@@ -324,6 +346,10 @@ public class GroupCoordinatorConfig {
         this.shareGroupMinHeartbeatIntervalMs = config.getInt(GroupCoordinatorConfig.SHARE_GROUP_MIN_HEARTBEAT_INTERVAL_MS_CONFIG);
         this.shareGroupMaxHeartbeatIntervalMs = config.getInt(GroupCoordinatorConfig.SHARE_GROUP_MAX_HEARTBEAT_INTERVAL_MS_CONFIG);
         this.shareGroupMaxSize = config.getInt(GroupCoordinatorConfig.SHARE_GROUP_MAX_SIZE_CONFIG);
+        // Streams group configurations
+        this.streamsGroupSessionTimeoutMs = config.getInt(GroupCoordinatorConfig.STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG);
+        this.streamsGroupHeartbeatIntervalMs = config.getInt(GroupCoordinatorConfig.STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG);
+        this.streamsGroupNumStandbyReplicas = config.getInt(GroupCoordinatorConfig.STREAMS_GROUP_NUM_STANDBY_REPLICAS_CONFIG);
 
         // New group coordinator configs validation.
         require(consumerGroupMaxHeartbeatIntervalMs >= consumerGroupMinHeartbeatIntervalMs,
@@ -365,6 +391,10 @@ public class GroupCoordinatorConfig {
         require(shareGroupHeartbeatIntervalMs < shareGroupSessionTimeoutMs,
             String.format("%s must be less than %s",
                 SHARE_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, SHARE_GROUP_SESSION_TIMEOUT_MS_CONFIG));
+
+        // Streams group configs validation.
+        require(streamsGroupHeartbeatIntervalMs <= streamsGroupSessionTimeoutMs,
+                String.format("%s must be less than or equals to %s", STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG));
     }
 
     /**
@@ -625,4 +655,25 @@ public class GroupCoordinatorConfig {
     public int shareGroupMaxHeartbeatIntervalMs() {
         return shareGroupMaxHeartbeatIntervalMs;
     }
+
+    /**
+     * The streams group session timeout in milliseconds.
+     */
+    public int streamsGroupSessionTimeoutMs() {
+        return streamsGroupSessionTimeoutMs;
+    }
+
+    /**
+     * The streams group heartbeat interval in milliseconds.
+     */
+    public int streamsGroupHeartbeatIntervalMs() {
+        return streamsGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * The streams group number of standby replicas
+     */
+    public int streamsGroupNumStandbyReplicas() {
+        return streamsGroupNumStandbyReplicas;
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 1809db63f13..6a2ad52ec3a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -135,7 +135,7 @@ import static org.apache.kafka.coordinator.group.Utils.messageOrNull;
  * 2) The replay methods which apply records to the hard state. Those are used in the request
  *    handling as well as during the initial loading of the records from the partitions.
  */
-@SuppressWarnings("ClassFanOutComplexity")
+@SuppressWarnings({"ClassFanOutComplexity", "CyclomaticComplexity"})
 public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord> {
 
     public static class Builder implements CoordinatorShardBuilder<GroupCoordinatorShard, CoordinatorRecord> {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
index 9a50c0a32cc..a2de5ea0d2c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
@@ -522,6 +522,9 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                     break;
                 case DEAD:
                     incrementNumStreamsGroups(StreamsGroupState.DEAD);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unknown new state for streams group: " + newState);
             }
         }
 
@@ -544,6 +547,9 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                     break;
                 case DEAD:
                     decrementNumStreamsGroups(StreamsGroupState.DEAD);
+                    break;
+                default:
+                    throw new IllegalArgumentException("Unknown old state for streams group: " + newState);
             }
         }
     }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
index 4956acaf386..baf55529fa5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
@@ -42,7 +42,8 @@ public class GroupCoordinatorConfigTest {
             GroupCoordinatorConfig.NEW_GROUP_CONFIG_DEF,
             GroupCoordinatorConfig.OFFSET_MANAGEMENT_CONFIG_DEF,
             GroupCoordinatorConfig.CONSUMER_GROUP_CONFIG_DEF,
-            GroupCoordinatorConfig.SHARE_GROUP_CONFIG_DEF);
+            GroupCoordinatorConfig.SHARE_GROUP_CONFIG_DEF,
+            GroupCoordinatorConfig.STREAMS_GROUP_CONFIG_DEF);
 
     @Test
     public void testConfigs() {
@@ -71,6 +72,9 @@ public class GroupCoordinatorConfigTest {
         configs.put(GroupCoordinatorConfig.CONSUMER_GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG, 666);
         configs.put(GroupCoordinatorConfig.CONSUMER_GROUP_MIN_HEARTBEAT_INTERVAL_MS_CONFIG, 111);
         configs.put(GroupCoordinatorConfig.CONSUMER_GROUP_MAX_HEARTBEAT_INTERVAL_MS_CONFIG, 222);
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG, 73);
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, 42);
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_NUM_STANDBY_REPLICAS_CONFIG, 2);
 
         GroupCoordinatorConfig config = createConfig(configs);
 
@@ -99,6 +103,9 @@ public class GroupCoordinatorConfigTest {
         assertEquals(666, config.consumerGroupMaxSessionTimeoutMs());
         assertEquals(111, config.consumerGroupMinHeartbeatIntervalMs());
         assertEquals(222, config.consumerGroupMaxHeartbeatIntervalMs());
+        assertEquals(73, config.streamsGroupSessionTimeoutMs());
+        assertEquals(42, config.streamsGroupHeartbeatIntervalMs());
+        assertEquals(2, config.streamsGroupNumStandbyReplicas());
     }
 
     @Test
@@ -179,7 +186,26 @@ public class GroupCoordinatorConfigTest {
         configs.put(GroupCoordinatorConfig.SHARE_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, 50000);
         configs.put(GroupCoordinatorConfig.SHARE_GROUP_SESSION_TIMEOUT_MS_CONFIG, 50000);
         assertEquals("group.share.heartbeat.interval.ms must be less than group.share.session.timeout.ms",
+        
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG, 0);
+        assertEquals("Invalid value 0 for configuration group.streams.session.timeout.ms: Value must be at least 1",
+                assertThrows(ConfigException.class, () -> createConfig(configs)).getMessage());
+
+        configs.clear();
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, 0);
+        assertEquals("Invalid value 0 for configuration group.streams.heartbeat.interval.ms: Value must be at least 1",
+                assertThrows(ConfigException.class, () -> createConfig(configs)).getMessage());
+
+        configs.clear();
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG, 42);
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, 43);
+        assertEquals("group.streams.heartbeat.interval.ms must be less than or equals to group.streams.session.timeout.ms",
                 assertThrows(IllegalArgumentException.class, () -> createConfig(configs)).getMessage());
+
+        configs.clear();
+        configs.put(GroupCoordinatorConfig.STREAMS_GROUP_NUM_STANDBY_REPLICAS_CONFIG, -1);
+        assertEquals("Invalid value -1 for configuration group.streams.num.standby.replicas: Value must be at least 0",
+                assertThrows(ConfigException.class, () -> createConfig(configs)).getMessage());
     }
 
     public static GroupCoordinatorConfig createGroupCoordinatorConfig(
diff --git a/server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java b/server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java
index 537b0869d52..e7c7c18a51b 100644
--- a/server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java
+++ b/server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java
@@ -55,6 +55,7 @@ public abstract class AbstractKafkaConfig extends AbstractConfig {
             GroupCoordinatorConfig.OFFSET_MANAGEMENT_CONFIG_DEF,
             GroupCoordinatorConfig.CONSUMER_GROUP_CONFIG_DEF,
             GroupCoordinatorConfig.SHARE_GROUP_CONFIG_DEF,
+            GroupCoordinatorConfig.STREAMS_GROUP_CONFIG_DEF,
             CleanerConfig.CONFIG_DEF,
             LogConfig.SERVER_CONFIG_DEF,
             ShareGroupConfig.CONFIG_DEF,


(kafka) 39/42: Fixes from rebase

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 1e8284b71d2c550a202f42a5455ffed62a99bbb7
Author: Bill <bb...@apache.org>
AuthorDate: Tue Nov 26 14:15:52 2024 -0500

    Fixes from rebase
---
 .../kafka/api/IntegrationTestHarness.scala         |  4 --
 .../scala/unit/kafka/server/KafkaApisTest.scala    |  1 -
 .../KafkaStreamsTelemetryIntegrationTest.java      |  3 +-
 .../SmokeTestDriverIntegrationTest.java            | 67 ++++++++--------------
 4 files changed, 27 insertions(+), 48 deletions(-)

diff --git a/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala b/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
index a66752c30f3..b7efed1d495 100644
--- a/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
+++ b/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
@@ -74,10 +74,6 @@ abstract class IntegrationTestHarness extends KafkaServerTestHarness {
       cfgs.foreach(_.setProperty(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,consumer,share"))
       cfgs.foreach(_.setProperty(ServerConfigs.UNSTABLE_API_VERSIONS_ENABLE_CONFIG, "true"))
     }
-    if (isStreamsGroupTest()) {
-      cfgs.foreach(_.setProperty(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,consumer,streams"))
-      cfgs.foreach(_.setProperty(ServerConfigs.UNSTABLE_API_VERSIONS_ENABLE_CONFIG, "true"))
-    }
 
     if(isKRaftTest()) {
       cfgs.foreach(_.setProperty(KRaftConfigs.METADATA_LOG_DIR_CONFIG, TestUtils.tempDir().getAbsolutePath))
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index d3edc955211..39a77f7de52 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -77,7 +77,6 @@ import org.apache.kafka.common.utils.{ImplicitLinkedHashCollection, ProducerIdAn
 import org.apache.kafka.coordinator.group.GroupConfig.{CONSUMER_HEARTBEAT_INTERVAL_MS_CONFIG, CONSUMER_SESSION_TIMEOUT_MS_CONFIG, SHARE_AUTO_OFFSET_RESET_CONFIG, SHARE_HEARTBEAT_INTERVAL_MS_CONFIG, SHARE_RECORD_LOCK_DURATION_MS_CONFIG, SHARE_SESSION_TIMEOUT_MS_CONFIG}
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupConfig
 import org.apache.kafka.coordinator.group.{GroupConfig, GroupCoordinator, GroupCoordinatorConfig}
-import org.apache.kafka.coordinator.group.{GroupCoordinator, GroupCoordinatorConfig}
 import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult
 import org.apache.kafka.coordinator.share.{ShareCoordinator, ShareCoordinatorConfigTest}
 import org.apache.kafka.coordinator.transaction.TransactionLogConfig
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
index fc90c621435..1de8fa21307 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsTelemetryIntegrationTest.java
@@ -432,7 +432,8 @@ public class KafkaStreamsTelemetryIntegrationTest {
         }
 
         @Override
-        public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(Map<String, Object> config, StreamsAssignmentInterface assignmentInterface) {
+        public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config,
+                                                                            final StreamsAssignmentInterface assignmentInterface) {
             return null;
         }
 
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index 4ed0e946426..88da4f1aa0c 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -16,21 +16,26 @@
  */
 package org.apache.kafka.streams.integration;
 
-
-
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig;
+import org.apache.kafka.server.config.ServerConfigs;
 import org.apache.kafka.streams.GroupProtocol;
 import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.StreamsConfig.InternalConfig;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
 import org.apache.kafka.streams.tests.SmokeTestClient;
 import org.apache.kafka.streams.tests.SmokeTestDriver;
 
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Tag;
 import org.junit.jupiter.api.Timeout;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 
+import java.io.IOException;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Locale;
@@ -45,12 +50,25 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 @Timeout(600)
 @Tag("integration")
 public class SmokeTestDriverIntegrationTest {
+    
+    
+    public static EmbeddedKafkaCluster cluster;
+
+    @BeforeAll
+    public static void startCluster() throws IOException {
+        final Properties props = new Properties();
+        props.setProperty(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,consumer,streams");
+        props.setProperty(ServerConfigs.UNSTABLE_API_VERSIONS_ENABLE_CONFIG, "true");
+        cluster = new EmbeddedKafkaCluster(3, props);
+        cluster.start();
+    }
 
-    @Override
-    public int brokerCount() {
-        return 3;
+    @AfterAll
+    public static void closeCluster() {
+        cluster.stop();
     }
 
+
     private static class Driver extends Thread {
         private final String bootstrapServers;
         private final int numKeys;
@@ -86,21 +104,6 @@ public class SmokeTestDriverIntegrationTest {
 
     }
 
-    @Override
-    public boolean isStreamsGroupTest() {
-        return true;
-    }
-
-    @Override
-    public boolean isZkMigrationTest() {
-        return false;
-    }
-
-    @Override
-    public boolean isKRaftTest() {
-        return true;
-    }
-
     // In this test, we try to keep creating new stream, and closing the old one, to maintain only 3 streams alive.
     // During the new stream added and old stream left, the stream process should still complete without issue.
     // We set 2 timeout condition to fail the test before passing the verification:
@@ -122,27 +125,9 @@ public class SmokeTestDriverIntegrationTest {
         int numClientsCreated = 0;
         final ArrayList<SmokeTestClient> clients = new ArrayList<>();
 
-        for (final String topic: SmokeTestDriver.topics()) {
-            deleteTopic(topic, listenerName());
-        }
-
-        for (final String topic: new String[]{
-            "data",
-            "echo",
-            "max",
-            "min", "min-suppressed", "min-raw",
-            "dif",
-            "sum",
-            "sws-raw", "sws-suppressed",
-            "cnt",
-            "avg",
-            "tagg",
-            "fk"
-        }) {
-            createTopic(topic, 3, 1, new Properties(), listenerName(), new Properties());
-        }
+        IntegrationTestUtils.cleanStateBeforeTest(cluster, SmokeTestDriver.topics());
 
-        final String bootstrapServers = bootstrapServers(listenerName());
+        final String bootstrapServers = cluster.bootstrapServers();
         final Driver driver = new Driver(bootstrapServers, 10, 1000);
         driver.start();
         System.out.println("started driver");
@@ -202,7 +187,5 @@ public class SmokeTestDriverIntegrationTest {
             throw new AssertionError(driver.exception());
         }
         assertTrue(driver.result().passed(), driver.result().result());
-
-
     }
 }


(kafka) 41/42: Remove superfluous record version

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit c7deec0e70c25b9367f25d3a150ebdac26aeede1
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Thu Nov 28 14:08:46 2024 +0100

    Remove superfluous record version
---
 .../org/apache/kafka/coordinator/group/GroupCoordinatorShard.java  | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 4af85ad97c9..414f23aab67 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -946,13 +946,6 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 );
                 break;
 
-            case 15:
-                groupMetadataManager.replay(
-                    (ConsumerGroupRegularExpressionKey) key.message(),
-                    (ConsumerGroupRegularExpressionValue) Utils.messageOrNull(value)
-                );
-                break;
-
             case 16:
                 groupMetadataManager.replay(
                     (ConsumerGroupRegularExpressionKey) key.message(),


(kafka) 17/42: Resolve conflicts from 11/25 rebase - Get SmokeTestDriverIntegrationTest working

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 7d73d52e8b6f21be7dd04ae104b762325b0b8748
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Thu Jun 20 16:09:44 2024 +0200

    Resolve conflicts from 11/25 rebase - Get SmokeTestDriverIntegrationTest working
    
    See https://github.com/lucasbru/kafka/pull/22
---
 checkstyle/suppressions.xml                        |    8 +-
 .../internals/StreamsAssignmentInterface.java      |   20 +-
 .../internals/StreamsHeartbeatRequestManager.java  |    6 +-
 .../internals/StreamsInitializeRequestManager.java |   27 +-
 .../org/apache/kafka/common/protocol/ApiKeys.java  |    3 +-
 .../message/StreamsGroupDescribeRequest.json       |   29 +
 .../message/StreamsGroupDescribeResponse.json      |  156 +++
 .../common/message/StreamsInitializeRequest.json   |    2 +
 .../kafka/server/QuorumTestHarness.scala           |    2 +-
 .../group/GroupCoordinatorRecordHelpers.java       |   15 +-
 .../coordinator/group/GroupCoordinatorShard.java   |    7 +
 .../coordinator/group/GroupMetadataManager.java    | 1159 +++++++++++++++++++-
 .../org/apache/kafka/coordinator/group/Utils.java  |   28 +
 .../group/metrics/GroupCoordinatorMetrics.java     |  113 +-
 .../metrics/GroupCoordinatorMetricsShard.java      |  128 +++
 .../group/streams/CurrentAssignmentBuilder.java    |   12 +-
 .../coordinator/group/streams/StreamsGroup.java    |   29 +-
 .../group/streams/StreamsGroupMember.java          |   30 +
 .../coordinator/group/streams/StreamsTopology.java |   10 +
 .../group/streams/TargetAssignmentBuilder.java     |   54 +-
 .../group/taskassignor/MemberAssignment.java       |    5 +
 .../common/message/StreamsGroupTopologyValue.json  |    2 +
 .../group/GroupMetadataManagerTest.java            |  278 ++---
 .../group/GroupMetadataManagerTestContext.java     |    3 +
 .../kafka/coordinator/group/MockTaskAssignor.java  |   46 +
 .../group/OffsetMetadataManagerTest.java           |    2 +
 .../streams/CurrentAssignmentBuilderTest.java      |   30 +-
 .../group/streams/TargetAssignmentBuilderTest.java |   22 +-
 .../SmokeTestDriverIntegrationTest.java            |   84 +-
 .../streams/processor/internals/TaskManager.java   |    6 +-
 streams/src/test/resources/log4j.properties        |    1 +
 31 files changed, 2024 insertions(+), 293 deletions(-)

diff --git a/checkstyle/suppressions.xml b/checkstyle/suppressions.xml
index 0bfed4f1df4..4563e985467 100644
--- a/checkstyle/suppressions.xml
+++ b/checkstyle/suppressions.xml
@@ -353,5 +353,11 @@
               files="(ReplicaFetcherThreadBenchmark).java"/>
 
      <!-- Add the new suppression rule for JaasTestUtils.java -->
-    <suppress checks="ImportControl" files="(JaasTestUtils).java" />
+    <suppress checks="ImportControl"
+              files="kafka/security/JaasTestUtils.java" />
+
+    <!-- group coordinator -->
+    <suppress checks="JavaNCSS"
+              files="GroupMetadataManager.java"/>
+
 </suppressions>
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index d09ffbda4f4..27450041b95 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -18,6 +18,7 @@ package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.common.TopicPartition;
 
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -100,14 +101,20 @@ public class StreamsAssignmentInterface {
         this.taskLags = taskLags;
     }
 
-    public final AtomicReference<Assignment> reconciledAssignment = new AtomicReference<>();
+    public final AtomicReference<Assignment> reconciledAssignment = new AtomicReference<>(
+        new Assignment(
+            new HashSet<>(),
+            new HashSet<>(),
+            new HashSet<>()
+        )
+    );
 
     public final AtomicReference<Assignment> targetAssignment = new AtomicReference<>();
 
     /**
      * List of partitions available on each host. Updated by the streams protocol client.
      */
-    public final AtomicReference<Map<HostInfo, List<TopicPartition>>> partitionsByHost = new AtomicReference<>();
+    public final AtomicReference<Map<HostInfo, List<TopicPartition>>> partitionsByHost = new AtomicReference<>(Collections.emptyMap());
 
     public static class HostInfo {
 
@@ -169,6 +176,15 @@ public class StreamsAssignmentInterface {
         public Assignment copy() {
             return new Assignment(activeTasks, standbyTasks, warmupTasks);
         }
+
+        @Override
+        public String toString() {
+            return "Assignment{" +
+                "activeTasks=" + activeTasks +
+                ", standbyTasks=" + standbyTasks +
+                ", warmupTasks=" + warmupTasks +
+                '}';
+        }
     }
 
     public static class TopicInfo {
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
index 4f4d80104fd..5600d550187 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
@@ -213,7 +213,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
                 exception.getMessage());
             logger.debug(message);
         } else {
-            logger.error("StreamsHeartbeatRequest failed due to fatal error: {}", exception.getMessage());
+            logger.error("StreamsHeartbeatRequest failed due to fatal error", exception);
             handleFatalFailure(exception);
         }
     }
@@ -576,7 +576,9 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
                     tag.setValue(entry.getValue());
                     return tag;
                 }).collect(Collectors.toList()));
-                data.setAssignmentConfigs(streamsInterface.assignmentConfiguration().entrySet().stream().map(entry -> {
+                data.setAssignmentConfigs(streamsInterface.assignmentConfiguration().entrySet().stream().filter(
+                    entry -> entry.getValue() != null
+                ).map(entry -> {
                     StreamsHeartbeatRequestData.KeyValue config = new StreamsHeartbeatRequestData.KeyValue();
                     config.setKey(entry.getKey());
                     config.setValue(entry.getValue().toString());
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
index 2bc4f79f548..07b6dee16bd 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -19,7 +19,9 @@ package org.apache.kafka.clients.consumer.internals;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.StreamsInitializeRequest;
+import org.apache.kafka.common.requests.StreamsInitializeResponse;
 import org.apache.kafka.common.utils.LogContext;
 import org.slf4j.Logger;
 
@@ -50,7 +52,9 @@ public class StreamsInitializeRequestManager implements RequestManager {
 
     @Override
     public PollResult poll(final long currentTimeMs) {
-        return unsentRequest.map(PollResult::new).orElse(PollResult.EMPTY);
+        final PollResult pollResult = unsentRequest.map(PollResult::new).orElse(PollResult.EMPTY);
+        unsentRequest = Optional.empty();
+        return pollResult;
     }
 
     public void initialize() {
@@ -121,8 +125,25 @@ public class StreamsInitializeRequestManager implements RequestManager {
             // todo: handle error
             logger.error("Error during Streams initialization: ", exception);
         } else {
-            // todo: handle success
-            logger.info("Streams initialization successful");
+            onResponse((StreamsInitializeResponse) response.responseBody());
         }
     }
+
+    private void onResponse(final StreamsInitializeResponse response) {
+        if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
+            onSuccessResponse(response);
+        } else {
+            onErrorResponse(response);
+        }
+    }
+
+    private void onErrorResponse(final StreamsInitializeResponse response) {
+        // todo: handle error
+        logger.error("Error during Streams initialization: {}", response);
+    }
+
+    private void onSuccessResponse(final StreamsInitializeResponse response) {
+        // todo: handle success
+        logger.info("Streams initialization successful {}", response);
+    }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index 7924677af3f..34ed496e1ec 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -134,7 +134,8 @@ public enum ApiKeys {
     STREAMS_HEARTBEAT(ApiMessageType.STREAMS_HEARTBEAT),
     STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE),
     STREAMS_INSTALL_ASSIGNMENT(ApiMessageType.STREAMS_INSTALL_ASSIGNMENT),
-    STREAMS_PREPARE_ASSIGNMENT(ApiMessageType.STREAMS_PREPARE_ASSIGNMENT);
+    STREAMS_PREPARE_ASSIGNMENT(ApiMessageType.STREAMS_PREPARE_ASSIGNMENT),
+    STREAMS_GROUP_DESCRIBE(ApiMessageType.STREAMS_GROUP_DESCRIBE);
     
 
     private static final Map<ApiMessageType.ListenerType, EnumSet<ApiKeys>> APIS_BY_LISTENER =
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
new file mode 100644
index 00000000000..426e9dd81ed
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
@@ -0,0 +1,29 @@
+// 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.
+
+{
+  "apiKey": 80,
+  "type": "request",
+  "listeners": ["zkBroker", "broker"],
+  "name": "StreamsGroupDescribeRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupIds", "type": "[]string", "versions": "0+", "entityType": "groupId",
+      "about": "The ids of the groups to describe" },
+    { "name": "IncludeAuthorizedOperations", "type": "bool", "versions": "0+",
+      "about": "Whether to include authorized operations." }
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
new file mode 100644
index 00000000000..3080631d66d
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -0,0 +1,156 @@
+// 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.
+
+{
+  "apiKey": 80,
+  "type": "response",
+  "name": "StreamsGroupDescribeResponse",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  // Supported errors:
+  // - GROUP_AUTHORIZATION_FAILED (version 0+)
+  // - NOT_COORDINATOR (version 0+)
+  // - COORDINATOR_NOT_AVAILABLE (version 0+)
+  // - COORDINATOR_LOAD_IN_PROGRESS (version 0+)
+  // - INVALID_REQUEST (version 0+)
+  // - INVALID_GROUP_ID (version 0+)
+  // - GROUP_ID_NOT_FOUND (version 0+)
+  "fields": [
+    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
+      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
+    { "name": "Groups", "type": "[]DescribedGroup", "versions": "0+",
+      "about": "Each described group.",
+      "fields": [
+        { "name": "ErrorCode", "type": "int16", "versions": "0+",
+          "about": "The describe error, or 0 if there was no error." },
+        { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+          "about": "The top-level error message, or null if there was no error." },
+        { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+          "about": "The group ID string." },
+        { "name": "GroupState", "type": "string", "versions": "0+",
+          "about": "The group state string, or the empty string." },
+        { "name": "GroupEpoch", "type": "int32", "versions": "0+",
+          "about": "The group epoch." },
+        { "name": "AssignmentEpoch", "type": "int32", "versions": "0+",
+          "about": "The assignment epoch." },
+        { "name": "AssignorName", "type": "string", "versions": "0+",
+          "about": "The selected assignor." },
+        { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
+          "about": "The sub-topologies of the streams application.",
+          "fields": [
+            { "name": "Subtopology", "type": "string", "versions": "0+",
+              "about": "String to uniquely identify the subtopology." },
+            { "name": "SourceTopics", "type": "[]string", "versions": "0+",
+              "about": "The topics the topology reads from." },
+            { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
+              "about": "The regular expressions identifying topics the topology reads from." },
+            { "name": "SinkTopics", "type": "[]string", "versions": "0+",
+              "about": "The topics the topology writes to." },
+            { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
+              "about": "The set of state changelog topics associated with this subtopology. Created automatically." },
+            { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
+              "about": "The set of source topics that are internally created repartition topics. Created automatically." }
+          ]
+        },
+        { "name": "Members", "type": "[]Member", "versions": "0+",
+          "about": "The members.",
+          "fields": [
+            { "name": "MemberId", "type": "string", "versions": "0+",
+              "about": "The member ID." },
+            { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+              "about": "The member epoch." },
+            { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+              "about": "The member instance ID." },
+            { "name": "RackId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+              "about": "The rack ID." },
+
+            { "name": "ClientId", "type": "string", "versions": "0+",
+              "about": "The client ID." },
+            { "name": "ClientHost", "type": "string", "versions": "0+",
+              "about": "The client host." },
+
+            { "name": "TopologyHash", "type": "bytes", "versions": "0+",
+              "about": "The hash of the topology." },
+
+            { "name": "ProcessId", "type": "uuid", "versions": "0+",
+              "about": "Identity of the streams instance that may have multiple clients. " },
+            { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
+              "about": "Used for rack-aware assignment algorithm." },
+            { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
+              "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
+            { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
+              "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
+              "fields": [
+                { "name": "Subtopology", "type": "string", "versions": "0+",
+                  "about": "A unique identifier of the subtopology." },
+                { "name": "Partition", "type": "int32", "versions": "0+",
+                  "about": "The partition of the input topics." },
+                { "name": "Offset", "type": "int64", "versions": "0+",
+                  "about": "The cumulative offset for the task" }
+              ]
+            },
+            { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
+              "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
+            { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
+              "about": "Generic array of assignment configuration strings."},
+
+            { "name": "Assignment", "type": "Assignment", "versions": "0+",
+              "about": "The current assignment." },
+            { "name": "TargetAssignment", "type": "Assignment", "versions": "0+",
+              "about": "The target assignment." }
+          ]},
+        { "name": "AuthorizedOperations", "type": "int32", "versions": "0+", "default": "-2147483648",
+          "about": "32-bit bitfield to represent authorized operations for this group." }
+      ]
+    }
+  ],
+  "commonStructs": [
+    { "name": "Assignment", "versions": "0+", "fields": [
+      { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
+        "about": "Active tasks for this client." },
+      { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
+        "about": "Standby tasks for this client." },
+      { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
+        "about": "Warming up tasks for this client. " }
+    ]},
+    { "name": "TaskIds", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "subtopology ID" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]},
+    { "name": "KeyValue", "versions": "0+", "fields": [
+      { "name": "Key", "type": "string", "versions": "0+",
+        "about": "key of the config" },
+      { "name": "Value", "type": "string", "versions": "0+",
+        "about": "value of the config" }
+    ]},
+    { "name": "TopicConfig", "versions": "0+", "fields": [
+      { "name": "key", "type": "string", "versions": "0+",
+        "about": "The key of the topic-level configuration." },
+      { "name": "value", "type": "string", "versions": "0+",
+        "about": "The value of the topic-level configuration," }
+    ]},
+    { "name": "TopicInfo", "versions": "0+", "fields": [
+      { "name": "Name", "type": "string", "versions": "0+",
+        "about": "The name of the topic." },
+      { "name": "Partitions", "type": "int32", "versions": "0+",
+        "about": "The number of partitions in the topic. Can be 0 if no specific number of partitions is enforced. Always 0 for changelog topics." },
+      { "name": "TopicConfigs", "type": "[]TopicConfig", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "Topic-level configurations as key-value pairs."
+      }
+    ]}
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
index 7f18cd455d0..5acc772321c 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
@@ -30,6 +30,8 @@
           "about": "String to uniquely identify the subtopology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
+        { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
+          "about": "The regular expressions identifying topics the topology reads from." },
         { "name": "SinkTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology writes to." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
diff --git a/core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala b/core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
index 45712240ecd..b5a9153402f 100755
--- a/core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
+++ b/core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
@@ -297,7 +297,7 @@ abstract class QuorumTestHarness extends Logging {
     val name = testInfo.getTestMethod.toScala
       .map(_.toString)
       .getOrElse("[unspecified]")
-    if (TestInfoUtils.isKRaft(testInfo)) {
+    if (isKRaftTest()) {
       info(s"Running KRAFT test $name")
       implementation = newKRaftQuorum(testInfo)
     } else {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index da399312e30..842df9d7cbb 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -167,6 +167,7 @@ public class GroupCoordinatorRecordHelpers {
                     .setTopologyHash(member.topologyHash())
                     .setProcessId(member.processId())
                     .setHostInfo(member.hostInfo())
+                    .setAssignor(member.assignor().orElse(null))
                     .setClientTags(member.clientTags().entrySet().stream().map(e ->
                         new StreamsGroupMemberMetadataValue.KeyValue()
                             .setKey(e.getKey())
@@ -190,7 +191,7 @@ public class GroupCoordinatorRecordHelpers {
      * @param memberId The streams group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsMemberSubscriptionTombstoneRecord(
+    public static CoordinatorRecord newStreamsGroupMemberTombstoneRecord(
         String groupId,
         String memberId
     ) {
@@ -264,7 +265,7 @@ public class GroupCoordinatorRecordHelpers {
      * @param newSubscriptionMetadata The subscription metadata.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsGroupSubscriptionMetadataRecord(
+    public static CoordinatorRecord newStreamsGroupPartitionMetadataRecord(
         String groupId,
         Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> newSubscriptionMetadata
     ) {
@@ -307,7 +308,7 @@ public class GroupCoordinatorRecordHelpers {
      * @param groupId The streams group id.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsGroupSubscriptionMetadataTombstoneRecord(
+    public static CoordinatorRecord newStreamsGroupPartitionMetadataTombstoneRecord(
         String groupId
     ) {
         return new CoordinatorRecord(
@@ -1336,17 +1337,17 @@ public class GroupCoordinatorRecordHelpers {
         subtopologies.forEach(subtopology -> {
             List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
                 .map(topicInfo -> {
-                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs().stream()
+                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
                         .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                        .collect(Collectors.toList());
+                        .collect(Collectors.toList()) : null;
                     return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
                         .setPartitions(topicInfo.partitions());
                 }).collect(Collectors.toList());
 
             List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
-                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs().stream()
+                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
                     .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
-                    .collect(Collectors.toList());
+                    .collect(Collectors.toList()) : null;
                 return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
             }).collect(Collectors.toList());
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 7c153077b76..2d8e5229230 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -106,6 +106,7 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.coordinator.group.taskassignor.MockAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -114,6 +115,7 @@ import org.apache.kafka.timeline.SnapshotRegistry;
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -250,6 +252,11 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 .withShareGroupMaxSize(config.shareGroupMaxSize())
                 .withShareGroupSessionTimeout(config.shareGroupSessionTimeoutMs())
                 .withShareGroupHeartbeatInterval(config.shareGroupHeartbeatIntervalMs())
+               // TODO: Do we need separate configs for streams groups?
+                .withStreamsGroupAssignors(Collections.singletonList(new MockAssignor()))
+                .withStreamsGroupMaxSize(config.consumerGroupMaxSize)
+                .withStreamsGroupSessionTimeout(config.consumerGroupSessionTimeoutMs)
+                .withStreamsGroupHeartbeatInterval(config.consumerGroupHeartbeatIntervalMs)
                 .withGroupCoordinatorMetricsShard(metricsShard)
                 .build();
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index fe4d7d7eaf6..5997591b812 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -54,6 +54,10 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.KeyValue;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskIds;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskOffset;
 import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
@@ -136,6 +140,7 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroupAssignmentBuild
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.coordinator.group.streams.StreamsTopology;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
@@ -195,9 +200,17 @@ import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.n
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupMemberSubscriptionTombstoneRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupSubscriptionMetadataRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newShareGroupTargetAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupMemberRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupMemberTombstoneRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupPartitionMetadataRecord;
 import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsGroupTopologyRecord;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpers.newStreamsTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.Utils.assignmentToString;
 import static org.apache.kafka.coordinator.group.Utils.ofSentinel;
+import static org.apache.kafka.coordinator.group.Utils.taskAssignmentToString;
 import static org.apache.kafka.coordinator.group.Utils.toConsumerProtocolAssignment;
 import static org.apache.kafka.coordinator.group.Utils.toTopicPartitions;
 import static org.apache.kafka.coordinator.group.classic.ClassicGroupMember.EMPTY_ASSIGNMENT;
@@ -208,7 +221,12 @@ import static org.apache.kafka.coordinator.group.classic.ClassicGroupState.PREPA
 import static org.apache.kafka.coordinator.group.classic.ClassicGroupState.STABLE;
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.CLASSIC_GROUP_COMPLETED_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.CONSUMER_GROUP_REBALANCES_SENSOR_NAME;
+import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.STREAMS_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember.hasAssignedPartitionsChanged;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedActiveTasksChanged;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedStandbyTasksChanged;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedWarmupTasksChanged;
+
 
 /**
  * The GroupMetadataManager manages the metadata of all classic and consumer groups. It holds
@@ -219,10 +237,9 @@ import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMe
  * 2) The replay methods which apply records to the hard state. Those are used in the request
  *    handling as well as during the initial loading of the records from the partitions.
  */
-@SuppressWarnings("JavaNCSS")
+@SuppressWarnings("javancss")
 public class GroupMetadataManager {
 
-
     public static class Builder {
         private LogContext logContext = null;
         private SnapshotRegistry snapshotRegistry = null;
@@ -236,6 +253,11 @@ public class GroupMetadataManager {
         private int consumerGroupMetadataRefreshIntervalMs = Integer.MAX_VALUE;
         private MetadataImage metadataImage = null;
         private int consumerGroupSessionTimeoutMs = 45000;
+        private List<TaskAssignor> streamsGroupAssignors = null;
+        private int streamsGroupMaxSize = Integer.MAX_VALUE;
+        private int streamsGroupHeartbeatIntervalMs = 5000;
+        private int streamsGroupMetadataRefreshIntervalMs = Integer.MAX_VALUE;
+        private int streamsGroupSessionTimeoutMs = 45000;
         private int classicGroupMaxSize = Integer.MAX_VALUE;
         private int classicGroupInitialRebalanceDelayMs = 3000;
         private int classicGroupNewMemberJoinTimeoutMs = 5 * 60 * 1000;
@@ -304,6 +326,31 @@ public class GroupMetadataManager {
             return this;
         }
 
+        Builder withStreamsGroupAssignors(List<TaskAssignor> streamsGroupAssignors) {
+            this.streamsGroupAssignors = streamsGroupAssignors;
+            return this;
+        }
+
+        Builder withStreamsGroupMaxSize(int streamsGroupMaxSize) {
+            this.streamsGroupMaxSize = streamsGroupMaxSize;
+            return this;
+        }
+
+        Builder withStreamsGroupSessionTimeout(int streamsGroupSessionTimeoutMs) {
+            this.streamsGroupSessionTimeoutMs = streamsGroupSessionTimeoutMs;
+            return this;
+        }
+
+        Builder withStreamsGroupHeartbeatInterval(int streamsGroupHeartbeatIntervalMs) {
+            this.streamsGroupHeartbeatIntervalMs = streamsGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withStreamsGroupMetadataRefreshIntervalMs(int streamsGroupMetadataRefreshIntervalMs) {
+            this.streamsGroupMetadataRefreshIntervalMs = streamsGroupMetadataRefreshIntervalMs;
+            return this;
+        }
+
         Builder withMetadataImage(MetadataImage metadataImage) {
             this.metadataImage = metadataImage;
             return this;
@@ -412,7 +459,12 @@ public class GroupMetadataManager {
                 shareGroupMaxSize,
                 shareGroupSessionTimeoutMs,
                 shareGroupHeartbeatIntervalMs,
-                shareGroupMetadataRefreshIntervalMs
+                shareGroupMetadataRefreshIntervalMs,
+                streamsGroupAssignors,
+                streamsGroupMaxSize,
+                streamsGroupSessionTimeoutMs,
+                streamsGroupHeartbeatIntervalMs,
+                streamsGroupMetadataRefreshIntervalMs
             );
         }
     }
@@ -503,6 +555,36 @@ public class GroupMetadataManager {
      */
     private final int consumerGroupMetadataRefreshIntervalMs;
 
+    /**
+     * The supported task assignors keyed by their name.
+     */
+    private final Map<String, TaskAssignor> taskAssignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final TaskAssignor defaultTaskAssignor;
+
+    /**
+     * The maximum number of members allowed in a single streams group.
+     */
+    private final int streamsGroupMaxSize;
+
+    /**
+     * The heartbeat interval for streams groups.
+     */
+    private final int streamsGroupHeartbeatIntervalMs;
+
+    /**
+     * The session timeout for streams groups.
+     */
+    private final int streamsGroupSessionTimeoutMs;
+
+    /**
+     * The metadata refresh interval.
+     */
+    private final int streamsGroupMetadataRefreshIntervalMs;
+
     /**
      * The metadata image.
      */
@@ -602,7 +684,12 @@ public class GroupMetadataManager {
         int shareGroupMaxSize,
         int shareGroupSessionTimeoutMs,
         int shareGroupHeartbeatIntervalMs,
-        int shareGroupMetadataRefreshIntervalMs
+        int shareGroupMetadataRefreshIntervalMs,
+        List<TaskAssignor> taskAssignors,
+        int streamsGroupMaxSize,
+        int streamsGroupSessionTimeoutMs,
+        int streamsGroupHeartbeatIntervalMs,
+        int streamsGroupMetadataRefreshIntervalMs
     ) {
         this.logContext = logContext;
         this.log = logContext.logger(GroupMetadataManager.class);
@@ -626,6 +713,12 @@ public class GroupMetadataManager {
         this.classicGroupNewMemberJoinTimeoutMs = classicGroupNewMemberJoinTimeoutMs;
         this.classicGroupMinSessionTimeoutMs = classicGroupMinSessionTimeoutMs;
         this.classicGroupMaxSessionTimeoutMs = classicGroupMaxSessionTimeoutMs;
+        this.streamsGroupMaxSize = streamsGroupMaxSize;
+        this.streamsGroupSessionTimeoutMs = streamsGroupSessionTimeoutMs;
+        this.streamsGroupHeartbeatIntervalMs = streamsGroupHeartbeatIntervalMs;
+        this.streamsGroupMetadataRefreshIntervalMs = streamsGroupMetadataRefreshIntervalMs;
+        this.taskAssignors = taskAssignors.stream().collect(Collectors.toMap(TaskAssignor::name, Function.identity()));
+        this.defaultTaskAssignor = taskAssignors.get(0);
         this.consumerGroupMigrationPolicy = consumerGroupMigrationPolicy;
         this.shareGroupAssignor = shareGroupAssignor;
         this.shareGroupMaxSize = shareGroupMaxSize;
@@ -863,6 +956,80 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Gets or maybe creates a streams group without updating the groups map.
+     * The group will be materialized during the replay.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist or is an empty classic group.
+     * @param records           The record list to which the group tombstones are written
+     *                          if the group is empty and is a classic group.
+     *
+     * @return A StreamsGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a streams group.
+     *
+     * Package private for testing.
+     */
+    StreamsGroup getOrMaybeCreateStreamsGroup(
+        String groupId,
+        boolean createIfNotExists,
+        List<CoordinatorRecord> records
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Streams group %s not found.", groupId));
+        }
+
+        if (group == null || (createIfNotExists && maybeDeleteEmptyClassicGroup(group, records))) {
+            log.info("Creating streams group {}", groupId);
+            return new StreamsGroup(snapshotRegistry, groupId, metrics);
+        } else {
+            if (group.type() == STREAMS) {
+                return (StreamsGroup) group;
+            } else {
+                throw new GroupIdNotFoundException(String.format("Group %s is not a streams group.",
+                    groupId));
+            }
+        }
+    }
+
+    /**
+     * Gets a streams group by committed offset.
+     *
+     * @param groupId           The group id.
+     * @param committedOffset   A specified committed offset corresponding to this shard.
+     *
+     * @return A StreamsGroup.
+     * @throws GroupIdNotFoundException if the group does not exist or is not a streams group.
+     */
+    public StreamsGroup streamsGroup(
+        String groupId,
+        long committedOffset
+    ) throws GroupIdNotFoundException {
+        Group group = group(groupId, committedOffset);
+
+        if (group.type() == STREAMS) {
+            return (StreamsGroup) group;
+        } else {
+            // We don't support upgrading/downgrading between protocols at the moment so
+            // we throw an exception if a group exists with the wrong type.
+            throw new GroupIdNotFoundException(String.format("Group %s is not a streams group.",
+                groupId));
+        }
+    }
+
+    /**
+     * An overloaded method of {@link GroupMetadataManager#streamsGroup(String, long)}
+     */
+    StreamsGroup streamsGroup(
+        String groupId
+    ) throws GroupIdNotFoundException {
+        return streamsGroup(groupId, Long.MAX_VALUE);
+    }
+
     /**
      * Gets a consumer group by committed offset.
      *
@@ -949,7 +1116,7 @@ public class GroupMetadataManager {
      *
      * @return A StreamsGroup.
      * @throws IllegalStateException if the group does not exist and createIfNotExists is false or
-     *                               if the group is not a consumer group.
+     *                               if the group is not a streams group.
      * Package private for testing.
      */
     StreamsGroup getOrMaybeCreatePersistedStreamsGroup(
@@ -963,10 +1130,10 @@ public class GroupMetadataManager {
         }
 
         if (group == null) {
+            log.info("Reading persisted streams group {}", groupId);
             StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, groupId, metrics);
             groups.put(groupId, streamsGroup);
-            // ToDo: migrate to streams group
-//            metrics.onConsumerGroupStateTransition(null, streamsGroup.state());
+            metrics.onStreamsGroupStateTransition(null, streamsGroup.state());
             return streamsGroup;
         } else {
             if (group.type() == STREAMS) {
@@ -1332,6 +1499,10 @@ public class GroupMetadataManager {
                     ConsumerGroup consumerGroup = (ConsumerGroup) group;
                     metrics.onConsumerGroupStateTransition(consumerGroup.state(), null);
                     break;
+                case STREAMS:
+                    StreamsGroup streamsGroup = (StreamsGroup) group;
+                    metrics.onStreamsGroupStateTransition(streamsGroup.state(), null);
+                    break;
                 case CLASSIC:
                     // The classic group size counter is implemented as scheduled task.
                     break;
@@ -1544,7 +1715,7 @@ public class GroupMetadataManager {
      *
      * @return A boolean indicating whether the owned partitions are a subset or not.
      */
-    private boolean isSubset(
+    private boolean isPartitionSubset(
         List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions,
         Map<Uuid, Set<Integer>> target
     ) {
@@ -1561,6 +1732,34 @@ public class GroupMetadataManager {
         return true;
     }
 
+    /**
+     * Verifies that the tasks currently owned by the member (the ones set in the
+     * request) matches the ones that the member should own. It matches if the streams
+     * only owns tasks which are in the assigned tasks. It does not match if
+     * it owns any other tasks.
+     *
+     * @param ownedTasks  The tasks provided by the streams in the request.
+     * @param target      The tasks that the member should have.
+     *
+     * @return A boolean indicating whether the owned partitions are a subset or not.
+     */
+    private boolean isTaskSubset(
+        List<StreamsHeartbeatRequestData.TaskIds> ownedTasks,
+        Map<String, Set<Integer>> target
+    ) {
+        if (ownedTasks == null) return false;
+
+        for (StreamsHeartbeatRequestData.TaskIds topicPartitions : ownedTasks) {
+            Set<Integer> partitions = target.get(topicPartitions.subtopology());
+            if (partitions == null) return false;
+            for (Integer partitionId : topicPartitions.partitions()) {
+                if (!partitions.contains(partitionId)) return false;
+            }
+        }
+
+        return true;
+    }
+
     /**
      * Checks whether the consumer group can accept a new member or not based on the
      * max group size defined.
@@ -1625,7 +1824,7 @@ public class GroupMetadataManager {
         } else if (receivedMemberEpoch < member.memberEpoch()) {
             // If the member comes with the previous epoch and has a subset of the current assignment partitions,
             // we accept it because the response with the bumped epoch may have been lost.
-            if (receivedMemberEpoch != member.previousMemberEpoch() || !isSubset(ownedTopicPartitions, member.assignedPartitions())) {
+            if (receivedMemberEpoch != member.previousMemberEpoch() || !this.isPartitionSubset(ownedTopicPartitions, member.assignedPartitions())) {
                 throw new FencedMemberEpochException("The consumer group member has a smaller member "
                     + "epoch (" + receivedMemberEpoch + ") than the one known by the group coordinator ("
                     + member.memberEpoch() + "). The member must abandon all its partitions and rejoin.");
@@ -1714,6 +1913,117 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Checks whether the streams group can accept a new member or not based on the
+     * max group size defined.
+     *
+     * @param group     The streams group.
+     * @param memberId  The member id.
+     *
+     * @throws GroupMaxSizeReachedException if the maximum capacity has been reached.
+     */
+    private void throwIfStreamsGroupIsFull(
+        StreamsGroup group,
+        String memberId
+    ) throws GroupMaxSizeReachedException {
+        // If the streams group has reached its maximum capacity, the member is rejected if it is not
+        // already a member of the streams group.
+        if (group.numMembers() >= streamsGroupMaxSize && (memberId.isEmpty() || !group.hasMember(memberId))) {
+            throw new GroupMaxSizeReachedException("The streams group has reached its maximum capacity of "
+                + streamsGroupMaxSize + " members.");
+        }
+    }
+
+    /**
+     * Validates the member epoch provided in the heartbeat request.
+     *
+     * @param member                The streams group member.
+     * @param receivedMemberEpoch   The member epoch.
+     * @param ownedActiveTasks      The owned active tasks.
+     * @param ownedStandbyTasks     The owned standby tasks.
+     * @param ownedWarmupTasks      The owned warmup tasks.
+     *
+     * @throws FencedMemberEpochException if the provided epoch is ahead or behind the epoch known
+     *                                    by this coordinator.
+     */
+    private void throwIfMemberEpochIsInvalid(
+        StreamsGroupMember member,
+        int receivedMemberEpoch,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks
+    ) {
+        if (receivedMemberEpoch > member.memberEpoch()) {
+            throw new FencedMemberEpochException("The streams group member has a greater member "
+                + "epoch (" + receivedMemberEpoch + ") than the one known by the group coordinator ("
+                + member.memberEpoch() + "). The member must abandon all its partitions and rejoin.");
+        } else if (receivedMemberEpoch < member.memberEpoch()) {
+            // If the member comes with the previous epoch and has a subset of the current assignment partitions,
+            // we accept it because the response with the bumped epoch may have been lost.
+            if (receivedMemberEpoch != member.previousMemberEpoch()
+                || !isTaskSubset(ownedActiveTasks, member.assignedActiveTasks())
+                || !isTaskSubset(ownedStandbyTasks, member.assignedStandbyTasks())
+                || !isTaskSubset(ownedWarmupTasks, member.assignedWarmupTasks())) {
+                throw new FencedMemberEpochException("The streams group member has a smaller member "
+                    + "epoch (" + receivedMemberEpoch + ") than the one known by the group coordinator ("
+                    + member.memberEpoch() + "). The member must abandon all its partitions and rejoin.");
+            }
+        }
+    }
+
+    /**
+     * Validates if the received instanceId has been released from the group
+     *
+     * @param member                The streams group member.
+     * @param groupId               The streams group id.
+     * @param receivedMemberId      The member id received in the request.
+     * @param receivedInstanceId    The instance id received in the request.
+     *
+     * @throws UnreleasedInstanceIdException if the instance id received in the request is still in use by an existing static member.
+     */
+    private void throwIfInstanceIdIsUnreleased(StreamsGroupMember member, String groupId, String receivedMemberId, String receivedInstanceId) {
+        if (member.memberEpoch() != LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
+            // The new member can't join.
+            log.info("[GroupId {}] Static member {} with instance id {} cannot join the group because the instance id is" +
+                " is owned by member {}.", groupId, receivedMemberId, receivedInstanceId, member.memberId());
+            throw Errors.UNRELEASED_INSTANCE_ID.exception("Static member " + receivedMemberId + " with instance id "
+                + receivedInstanceId + " cannot join the group because the instance id is owned by " + member.memberId() + " member.");
+        }
+    }
+
+    /**
+     * Validates if the received instanceId has been released from the group
+     *
+     * @param member                The streams group member.
+     * @param groupId               The streams group id.
+     * @param receivedMemberId      The member id received in the request.
+     * @param receivedInstanceId    The instance id received in the request.
+     *
+     * @throws FencedInstanceIdException if the instance id provided is fenced because of another static member.
+     */
+    private void throwIfInstanceIdIsFenced(StreamsGroupMember member, String groupId, String receivedMemberId, String receivedInstanceId) {
+        if (!member.memberId().equals(receivedMemberId)) {
+            log.info("[GroupId {}] Static member {} with instance id {} is fenced by existing member {}.",
+                groupId, receivedMemberId, receivedInstanceId, member.memberId());
+            throw Errors.FENCED_INSTANCE_ID.exception("Static member " + receivedMemberId + " with instance id "
+                + receivedInstanceId + " was fenced by member " + member.memberId() + ".");
+        }
+    }
+
+    /**
+     * Validates if the received instanceId has been released from the group
+     *
+     * @param staticMember          The static member in the group.
+     * @param receivedInstanceId    The instance id received in the request.
+     *
+     * @throws UnknownMemberIdException if no static member exists in the group against the provided instance id.
+     */
+    private void throwIfStaticMemberIsUnknown(StreamsGroupMember staticMember, String receivedInstanceId) {
+        if (staticMember == null) {
+            throw Errors.UNKNOWN_MEMBER_ID.exception("Instance id " + receivedInstanceId + " is unknown.");
+        }
+    }
+
     /**
      * Validates if the received classic member protocols are supported by the group.
      *
@@ -1886,6 +2196,225 @@ public class GroupMetadataManager {
             .collect(Collectors.toList());
     }
 
+    /**
+     * Handles a regular heartbeat from a streams group member. It mainly consists of three parts: 1) The member is created or updated. The
+     * group epoch is bumped if the member has been created or updated. 2) The target assignment for the streams group is updated if the
+     * group epoch is larger than the current target assignment epoch. 3) The member's assignment is reconciled with the target assignment.
+     *
+     * @param groupId            The group id from the request.
+     * @param memberId           The member id from the request.
+     * @param memberEpoch        The member epoch from the request.
+     * @param instanceId         The instance id from the request or null.
+     * @param rackId             The rack id from the request or null.
+     * @param rebalanceTimeoutMs The rebalance timeout from the request or -1.
+     * @param topologyHash
+     * @param clientId           The client id.
+     * @param clientHost         The client host.
+     * @param assignorName       The assignor name from the request or null.
+     * @param ownedActiveTasks   The list of owned active tasks from the request or null.
+     * @param ownedStandbyTasks  The list of owned standby tasks from the request or null.
+     * @param ownedWarmupTasks   The list of owned warmup tasks from the request or null.
+     * @return A Result containing the StreamsHeartbeat response and a list of records to update the state machine.
+     */
+    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+        String groupId,
+        String memberId,
+        int memberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        final byte[] topologyHash,
+        String clientId,
+        String clientHost,
+        String assignorName,
+        List<TaskIds> ownedActiveTasks,
+        List<TaskIds> ownedStandbyTasks,
+        List<TaskIds> ownedWarmupTasks,
+        final String processId,
+        final HostInfo hostInfo,
+        final List<KeyValue> clientTags,
+        final byte taskOffsetUpdateReason,
+        final List<TaskOffset> taskOffsets,
+        final byte[] userData,
+        final List<KeyValue> assignmentConfigs,
+        final boolean shutdownApplication
+    ) throws ApiException {
+        final long currentTimeMs = time.milliseconds();
+        final List<CoordinatorRecord> records = new ArrayList<>();
+
+        // Get or create the streams group.
+        boolean createIfNotExists = memberEpoch == 0;
+        final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, createIfNotExists, records);
+        throwIfStreamsGroupIsFull(group, memberId);
+
+        // Get or create the member.
+        if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString();
+        StreamsGroupMember member;
+        StreamsGroupMember.Builder updatedMemberBuilder;
+        boolean staticMemberReplaced = false;
+        if (instanceId == null) {
+            member = group.getOrMaybeCreateMember(memberId, createIfNotExists);
+            throwIfMemberEpochIsInvalid(member, memberEpoch, ownedActiveTasks, ownedStandbyTasks, ownedWarmupTasks);
+            if (createIfNotExists) {
+                log.info("[GroupId {}] Member {} joins the streams group.", groupId, memberId);
+            }
+            updatedMemberBuilder = new StreamsGroupMember.Builder(member);
+        } else {
+            member = group.staticMember(instanceId);
+            if (memberEpoch == 0) {
+                // A new static member joins or the existing static member rejoins.
+                if (member == null) {
+                    // New static member.
+                    member = group.getOrMaybeCreateMember(memberId, createIfNotExists);
+                    updatedMemberBuilder = new StreamsGroupMember.Builder(member);
+                    log.info("[GroupId {}] Static member {} with instance id {} joins the streams group.", groupId, memberId, instanceId);
+                } else {
+                    // Static member rejoins with a different member id so it should replace
+                    // the previous instance iff the previous member had sent a leave group.
+                    throwIfInstanceIdIsUnreleased(member, groupId, memberId, instanceId);
+                    // Replace the current member.
+                    staticMemberReplaced = true;
+                    updatedMemberBuilder = new StreamsGroupMember.Builder(memberId)
+                        .setAssignedActiveTasks(member.assignedActiveTasks())
+                        .setAssignedStandbyTasks(member.assignedStandbyTasks())
+                        .setAssignedWarmupTasks(member.assignedWarmupTasks());
+                    // Remove the member without canceling its timers in case the change is reverted. If the
+                    // change is not reverted, the group validation will fail and the timer will do nothing.
+                    removeStreamsMember(records, groupId, member.memberId());
+                    log.info("[GroupId {}] Static member with unknown member id and instance id {} re-joins the streams group. " +
+                        "Created a new member {} to replace the existing member {}.", groupId, instanceId, memberId, member.memberId());
+                }
+            } else {
+                throwIfStaticMemberIsUnknown(member, instanceId);
+                throwIfInstanceIdIsFenced(member, groupId, memberId, instanceId);
+                throwIfMemberEpochIsInvalid(member, memberEpoch, ownedActiveTasks, ownedStandbyTasks, ownedWarmupTasks);
+                updatedMemberBuilder = new StreamsGroupMember.Builder(member);
+            }
+        }
+
+        // 1. Create or update the member. If the member is new or has changed, a StreamsMemberMetadataValue
+        // record is written to the __consumer_offsets partition to persist the change. If the subscriptions have
+        // changed, the subscription metadata is updated and persisted by writing a StreamsPartitionMetadataValue
+        // record to the __consumer_offsets partition. Finally, the group epoch is bumped if the subscriptions have
+        // changed, and persisted by writing a StreamsMetadataValue record to the partition.
+        StreamsGroupMember updatedMember = updatedMemberBuilder
+            .maybeUpdateInstanceId(Optional.ofNullable(instanceId))
+            .maybeUpdateRackId(Optional.ofNullable(rackId))
+            .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs))
+            .maybeUpdateAssignor(Optional.ofNullable(assignorName))
+            .maybeUpdateTopologyHash(Optional.ofNullable(topologyHash))
+            .setClientId(clientId)
+            .setClientHost(clientHost)
+            .maybeUpdateProcessId(Optional.ofNullable(processId))
+            .maybeUpdateClientTags(Optional.ofNullable(clientTags).map(x -> x.stream().collect(Collectors.toMap(KeyValue::key, KeyValue::value))))
+            .maybeUpdateUserData(Optional.ofNullable(userData))
+            .maybeUpdateAssignmentConfigs(Optional.ofNullable(assignmentConfigs).map(x -> x.stream().collect(Collectors.toMap(KeyValue::key, KeyValue::value))))
+            .maybeUpdateHostInfo(Optional.ofNullable(hostInfo).map(x -> new StreamsGroupMemberMetadataValue.HostInfo().setHost(x.host()).setPort(x.port())))
+            .build();
+
+        int groupEpoch = group.groupEpoch();
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = group.subscriptionMetadata();
+
+        boolean bumpGroupEpoch = hasStreamsMemberMetadataChanged(
+            groupId,
+            member,
+            updatedMember,
+            records
+        );
+
+        if (bumpGroupEpoch || group.hasMetadataExpired(currentTimeMs)) {
+            // The subscription metadata is updated when the refresh deadline has been reached.
+            subscriptionMetadata = group.computeSubscriptionMetadata(
+                metadataImage.topics(),
+                metadataImage.cluster()
+            );
+
+            if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
+                log.info("[GroupId {}] Computed new partition metadata: {}.",
+                    groupId, subscriptionMetadata);
+                bumpGroupEpoch = true;
+                records.add(newStreamsGroupPartitionMetadataRecord(groupId, subscriptionMetadata));
+            }
+
+            if (bumpGroupEpoch) {
+                groupEpoch += 1;
+                records.add(newStreamsGroupEpochRecord(groupId, groupEpoch));
+                log.info("[GroupId {}] Bumped streams group epoch to {}.", groupId, groupEpoch);
+                metrics.record(STREAMS_GROUP_REBALANCES_SENSOR_NAME);
+            }
+
+            group.setMetadataRefreshDeadline(currentTimeMs + streamsGroupMetadataRefreshIntervalMs, groupEpoch);
+        }
+
+        // 2. Update the target assignment if the group epoch is larger than the target assignment epoch or a static member
+        // replaces an existing static member. The delta between the existing and the new target assignment is persisted to the partition.
+        int targetAssignmentEpoch = group.assignmentEpoch();
+        org.apache.kafka.coordinator.group.streams.Assignment targetAssignment = group.targetAssignment(memberId);
+        if (groupEpoch > targetAssignmentEpoch || staticMemberReplaced) {
+            targetAssignment = updateTargetAssignment(
+                group,
+                groupEpoch,
+                member,
+                updatedMember,
+                subscriptionMetadata,
+                staticMemberReplaced,
+                records
+            );
+            targetAssignmentEpoch = groupEpoch;
+        }
+
+        // 3. Reconcile the member's assignment with the target assignment if the member is not
+        // fully reconciled yet.
+        updatedMember = maybeReconcile(
+            groupId,
+            updatedMember,
+            group::currentActiveTaskEpoch,
+            targetAssignmentEpoch,
+            targetAssignment,
+            ownedActiveTasks,
+            ownedStandbyTasks,
+            ownedWarmupTasks,
+            records
+        );
+
+        scheduleStreamsGroupSessionTimeout(groupId, memberId);
+
+        if (group.topology() == null) {
+            log.info("Asking member {} at {} to initialize the topology", memberId, clientHost);
+        }
+
+        // Prepare the response.
+        StreamsHeartbeatResponseData response = new StreamsHeartbeatResponseData()
+            .setMemberId(updatedMember.memberId())
+            .setMemberEpoch(updatedMember.memberEpoch())
+            .setShouldInitializeTopology(group.topology() == null)
+            .setHeartbeatIntervalMs(streamsGroupHeartbeatIntervalMs);
+
+        // The assignment is only provided in the following cases:
+        // 1. The member sent a full request.
+        // 2. The member's assignment has been updated.
+        boolean isFullRequest = memberEpoch == 0;
+        if (isFullRequest
+            || hasAssignedActiveTasksChanged(member, updatedMember)
+            || hasAssignedStandbyTasksChanged(member, updatedMember)
+            || hasAssignedWarmupTasksChanged(member, updatedMember)
+        ) {
+            response.setActiveTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedActiveTasks()));
+            response.setStandbyTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedStandbyTasks()));
+            response.setWarmupTasks(createStreamsHeartbeatResponseTaskIds(updatedMember.assignedWarmupTasks()));
+        }
+
+        return new CoordinatorResult<>(records, response);
+    }
+
+    private List<StreamsHeartbeatResponseData.TaskIds> createStreamsHeartbeatResponseTaskIds(final Map<String, Set<Integer>> taskIds) {
+        return taskIds.entrySet().stream()
+            .map(entry -> new StreamsHeartbeatResponseData.TaskIds()
+                .setSubtopology(entry.getKey())
+                .setPartitions(new ArrayList<>(entry.getValue())))
+            .collect(Collectors.toList());
+    }
+
     /**
      * Handles a regular heartbeat from a consumer group member. It mainly consists of
      * three parts:
@@ -2110,9 +2639,10 @@ public class GroupMetadataManager {
         throws ApiException {
         final List<CoordinatorRecord> records = new ArrayList<>();
 
-        // TODO: Throw if group does not exist or is not a streams group. Needs model of
-        //       similar to  final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, createIfNotExists, records);
-        //                   throwIfNull(group);
+        log.info("Initializing topology for group {} to {}", groupId, subtopologies);
+
+        final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, false, records);
+        throwIfNull(group, "group does not exist");
 
         // TODO: For the POC, only check if internal topics exist
         Set<String> missingTopics = new HashSet<>();
@@ -2959,6 +3489,38 @@ public class GroupMetadataManager {
         return false;
     }
 
+    /**
+     * Creates the member subscription record if the updatedMember is different from
+     * the old member. Returns true if the subscribedTopicNames/subscribedTopicRegex
+     * has changed.
+     *
+     * @param groupId       The group id.
+     * @param member        The old member.
+     * @param updatedMember The updated member.
+     * @param records       The list to accumulate any new records.
+     * @return A boolean indicating whether the group epoch should be bumped
+     *         following this change
+     */
+    private boolean hasStreamsMemberMetadataChanged(
+        String groupId,
+        StreamsGroupMember member,
+        StreamsGroupMember updatedMember,
+        List<CoordinatorRecord> records
+    ) {
+        String memberId = updatedMember.memberId();
+        if (!updatedMember.equals(member)) {
+            records.add(newStreamsGroupMemberRecord(groupId, updatedMember));
+
+            if (updatedMember.topologyHash() != member.topologyHash()) {
+                log.info("[GroupId {}] Member {} updated its topology hash to: {}.",
+                    groupId, memberId, updatedMember.topologyHash());
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
     /**
      * Reconciles the current assignment of the member towards the target assignment if needed.
      *
@@ -3061,6 +3623,78 @@ public class GroupMetadataManager {
         return updatedMember;
     }
 
+    /**
+     * Reconciles the current assignment of the member towards the target assignment if needed.
+     *
+     * @param groupId               The group id.
+     * @param member                The member to reconcile.
+     * @param currentActiveTaskEpoch The function returning the current epoch of
+     *                              a given partition.
+     * @param targetAssignmentEpoch The target assignment epoch.
+     * @param targetAssignment      The target assignment.
+     * @param ownedActiveTasks      The list of active tasks owned by the member. This
+     *                              is reported in the StreamsHeartbeat API and
+     *                              it could be null if not provided.
+     * @param ownedStandbyTasks     The list of standby owned by the member. This
+     *                              is reported in the StreamsHeartbeat API and
+     *                              it could be null if not provided.
+     * @param ownedWarmupTasks      The list of warmup tasks owned by the member. This
+     *                              is reported in the StreamsHeartbeat API and
+     *                              it could be null if not provided.
+     * @param records               The list to accumulate any new records.
+     * @return The received member if no changes have been made; or a new
+     *         member containing the new assignment.
+     */
+    private StreamsGroupMember maybeReconcile(
+        String groupId,
+        StreamsGroupMember member,
+        BiFunction<String, Integer, Integer> currentActiveTaskEpoch,
+        int targetAssignmentEpoch,
+        org.apache.kafka.coordinator.group.streams.Assignment targetAssignment,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedActiveTasks,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedStandbyTasks,
+        List<StreamsHeartbeatRequestData.TaskIds> ownedWarmupTasks,
+        List<CoordinatorRecord> records
+    ) {
+        if (member.isReconciledTo(targetAssignmentEpoch)) {
+            return member;
+        }
+
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(targetAssignmentEpoch, targetAssignment)
+            .withCurrentActiveTaskEpoch(currentActiveTaskEpoch)
+            .withOwnedActiveTasks(ownedActiveTasks)
+            .withOwnedStandbyTasks(ownedStandbyTasks)
+            .withOwnedWarmupTasks(ownedWarmupTasks)
+            .build();
+
+        if (!updatedMember.equals(member)) {
+            records.add(newStreamsCurrentAssignmentRecord(groupId, updatedMember));
+
+            log.info("[GroupId {}] Member {} new assignment state: epoch={}, previousEpoch={}, state={}, "
+                    + "assignedActiveTasks={}, assignedStandbyTasks={}, assignedWarmupTasks={} and revokedPartitions={}.",
+                groupId, updatedMember.memberId(), updatedMember.memberEpoch(), updatedMember.previousMemberEpoch(), updatedMember.state(),
+                taskAssignmentToString(updatedMember.assignedActiveTasks()),
+                taskAssignmentToString(updatedMember.assignedStandbyTasks()),
+                taskAssignmentToString(updatedMember.assignedWarmupTasks()),
+                taskAssignmentToString(updatedMember.activeTasksPendingRevocation()));
+
+            // Schedule/cancel the rebalance timeout.
+            if (updatedMember.state() == org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS) {
+                scheduleStreamsGroupRebalanceTimeout(
+                    groupId,
+                    updatedMember.memberId(),
+                    updatedMember.memberEpoch(),
+                    updatedMember.rebalanceTimeoutMs()
+                );
+            } else {
+                cancelStreamsGroupRebalanceTimeout(groupId, updatedMember.memberId());
+            }
+        }
+
+        return updatedMember;
+    }
+
     /**
      * Updates the target assignment according to the updated member and subscription metadata.
      *
@@ -3189,6 +3823,67 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Updates the target assignment according to the updated member and subscription metadata.
+     *
+     * @param group                The StreamsGroup.
+     * @param groupEpoch           The group epoch.
+     * @param member               The existing member.
+     * @param updatedMember        The updated member.
+     * @param subscriptionMetadata The subscription metadata.
+     * @param staticMemberReplaced The boolean indicating whether the updated member is a static member that replaces the existing member.
+     * @param records              The list to accumulate any new records.
+     * @return The new target assignment.
+     */
+    private org.apache.kafka.coordinator.group.streams.Assignment updateTargetAssignment(
+        StreamsGroup group,
+        int groupEpoch,
+        StreamsGroupMember member,
+        StreamsGroupMember updatedMember,
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata,
+        boolean staticMemberReplaced,
+        List<CoordinatorRecord> records
+    ) {
+        String preferredServerAssignor = group.computePreferredServerAssignor(
+            member,
+            updatedMember
+        ).orElse(defaultTaskAssignor.name());
+        try {
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder assignmentResultBuilder =
+                new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(group.groupId(), groupEpoch, taskAssignors.get(preferredServerAssignor))
+                    .withMembers(group.members())
+                    .withTopology(group.topology())
+                    .withStaticMembers(group.staticMembers())
+                    .withSubscriptionMetadata(subscriptionMetadata)
+                    .withTargetAssignment(group.targetAssignment())
+                    .withTopicsImage(metadataImage.topics())
+                    .addOrUpdateMember(updatedMember.memberId(), updatedMember);
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult assignmentResult;
+            // A new static member is replacing an older one with the same subscriptions.
+            // We just need to remove the older member and add the newer one. The new member should
+            // reuse the target assignment of the older member.
+            if (staticMemberReplaced) {
+                assignmentResult = assignmentResultBuilder
+                    .removeMember(member.memberId())
+                    .build();
+            } else {
+                assignmentResult = assignmentResultBuilder
+                    .build();
+            }
+
+            log.info("[GroupId {}] Computed a new target assignment for epoch {} with '{}' assignor: {}.",
+                group.groupId(), groupEpoch, preferredServerAssignor, assignmentResult.targetAssignment());
+
+            records.addAll(assignmentResult.records());
+            return assignmentResult.targetAssignment().get(updatedMember.memberId());
+        } catch (PartitionAssignorException ex) {
+            String msg = String.format("Failed to compute a new target assignment for epoch %d: %s",
+                groupEpoch, ex.getMessage());
+            log.error("[GroupId {}] {}.", group.groupId(), msg);
+            throw new UnknownServerException(msg, ex);
+        }
+    }
+
     /**
      * Handles leave request from a consumer group member.
      * @param groupId       The group id from the request.
@@ -3229,6 +3924,46 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Handles leave request from a streams group member.
+     * @param groupId       The group id from the request.
+     * @param memberId      The member id from the request.
+     * @param memberEpoch   The member epoch from the request.
+     *
+     * @return A Result containing the StreamsHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsGroupLeave(
+        String groupId,
+        String instanceId,
+        String memberId,
+        int memberEpoch
+    ) throws ApiException {
+        StreamsGroup group = streamsGroup(groupId);
+        StreamsHeartbeatResponseData response = new StreamsHeartbeatResponseData()
+            .setMemberId(memberId)
+            .setMemberEpoch(memberEpoch);
+
+        if (instanceId == null) {
+            StreamsGroupMember member = group.getOrMaybeCreateMember(memberId, false);
+            log.info("[GroupId {}] Member {} left the streams group.", groupId, memberId);
+            return streamsGroupFenceMember(group, member, response);
+        } else {
+            StreamsGroupMember member = group.staticMember(instanceId);
+            throwIfStaticMemberIsUnknown(member, instanceId);
+            throwIfInstanceIdIsFenced(member, groupId, memberId, instanceId);
+            if (memberEpoch == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
+                log.info("[GroupId {}] Static Member {} with instance id {} temporarily left the streams group.",
+                    group.groupId(), memberId, instanceId);
+                return streamsGroupStaticMemberGroupLeave(group, member);
+            } else {
+                log.info("[GroupId {}] Static Member {} with instance id {} left the streams group.",
+                    group.groupId(), memberId, instanceId);
+                return streamsGroupFenceMember(group, member, response);
+            }
+        }
+    }
+
     /**
      * Handles the case when a static member decides to leave the group.
      * The member is not actually fenced from the group, and instead it's
@@ -3285,7 +4020,36 @@ public class GroupMetadataManager {
     }
 
     /**
-     * Fences a member from a consumer group and maybe downgrade the consumer group to a classic group.
+     * Handles the case when a static member decides to leave the group.
+     * The member is not actually fenced from the group, and instead it's
+     * member epoch is updated to -2 to reflect that a member using the given
+     * instance id decided to leave the group and would be back within session
+     * timeout.
+     *
+     * @param group     The group.
+     * @param member    The static member in the group for the instance id.
+     *
+     * @return A CoordinatorResult with a single record signifying that the static member is leaving.
+     */
+    private CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsGroupStaticMemberGroupLeave(
+        StreamsGroup group,
+        StreamsGroupMember member
+    ) {
+        // We will write a member epoch of -2 for this departing static member.
+        StreamsGroupMember leavingStaticMember = new StreamsGroupMember.Builder(member)
+            .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH)
+            .setActiveTasksPendingRevocation(Collections.emptyMap())
+            .build();
+
+        return new CoordinatorResult<>(
+            Collections.singletonList(newStreamsCurrentAssignmentRecord(group.groupId(), leavingStaticMember)),
+            new StreamsHeartbeatResponseData()
+                .setMemberId(member.memberId())
+                .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH)
+        );
+    }
+
+    /**     * Fences a member from a consumer group and maybe downgrade the consumer group to a classic group.
      *
      * @param group     The group.
      * @param member    The member.
@@ -3406,6 +4170,45 @@ public class GroupMetadataManager {
         ));
     }
 
+    /**
+     * Fences a member from a streams group and maybe downgrade the streams group to a classic group.
+     *
+     * @param group     The group.
+     * @param member    The member.
+     * @param response  The response of the CoordinatorResult.
+     *
+     * @return The CoordinatorResult to be applied.
+     */
+    private <T> CoordinatorResult<T, CoordinatorRecord> streamsGroupFenceMember(
+        StreamsGroup group,
+        StreamsGroupMember member,
+        T response
+    ) {
+        List<CoordinatorRecord> records = new ArrayList<>();
+        removeStreamsMember(records, group.groupId(), member.memberId());
+
+        // We bump the group epoch.
+        int groupEpoch = group.groupEpoch() + 1;
+        records.add(newStreamsGroupEpochRecord(group.groupId(), groupEpoch));
+
+        cancelTimers(group.groupId(), member.memberId());
+
+        return new CoordinatorResult<>(records, response);
+    }
+    
+    /**
+     * Write tombstones for the member. The order matters here.
+     *
+     * @param records       The list of records to append the member assignment tombstone records.
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void removeStreamsMember(List<CoordinatorRecord> records, String groupId, String memberId) {
+        records.add(newStreamsCurrentAssignmentTombstoneRecord(groupId, memberId));
+        records.add(newStreamsTargetAssignmentTombstoneRecord(groupId, memberId));
+        records.add(newStreamsGroupMemberTombstoneRecord(groupId, memberId));
+    }
+
     /**
      * Write tombstones for the member. The order matters here.
      *
@@ -3430,6 +4233,9 @@ public class GroupMetadataManager {
         cancelConsumerGroupRebalanceTimeout(groupId, memberId);
         cancelConsumerGroupJoinTimeout(groupId, memberId);
         cancelConsumerGroupSyncTimeout(groupId, memberId);
+        cancelStreamsGroupSessionTimeout(groupId, memberId);
+        cancelStreamsGroupRebalanceTimeout(groupId, memberId);
+        cancelStreamsGroupSyncTimeout(groupId, memberId);
     }
 
     /**
@@ -3445,6 +4251,19 @@ public class GroupMetadataManager {
         scheduleConsumerGroupSessionTimeout(groupId, memberId, consumerGroupSessionTimeoutMs(groupId));
     }
 
+    /**
+     * Schedules (or reschedules) the session timeout for the member.
+     *
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void scheduleStreamsGroupSessionTimeout(
+        String groupId,
+        String memberId
+    ) {
+        scheduleStreamsGroupSessionTimeout(groupId, memberId, streamsGroupSessionTimeoutMs);
+    }
+
     /**
      * Schedules (or reschedules) the session timeout for the member.
      *
@@ -3524,6 +4343,39 @@ public class GroupMetadataManager {
         return new CoordinatorResult<>(Collections.emptyList());
     }
 
+    /**
+     * Fences a member from a streams group. Returns an empty CoordinatorResult
+     * if the group or the member doesn't exist.
+     *
+     * @param groupId   The group id.
+     * @param memberId  The member id.
+     * @param reason    The reason for fencing the member.
+     *
+     * @return The CoordinatorResult to be applied.
+     */
+    private <T> CoordinatorResult<T, CoordinatorRecord> streamsGroupFenceMemberOperation(
+        String groupId,
+        String memberId,
+        String reason
+    ) {
+        try {
+            StreamsGroup group = streamsGroup(groupId);
+            StreamsGroupMember member = group.getOrMaybeCreateMember(memberId, false);
+            log.info("[GroupId {}] Member {} fenced from the group because {}.",
+                groupId, memberId, reason);
+
+            return streamsGroupFenceMember(group, member, null);
+        } catch (GroupIdNotFoundException ex) {
+            log.debug("[GroupId {}] Could not fence {} because the group does not exist.",
+                groupId, memberId);
+        } catch (UnknownMemberIdException ex) {
+            log.debug("[GroupId {}] Could not fence {} because the member does not exist.",
+                groupId, memberId);
+        }
+
+        return new CoordinatorResult<>(Collections.emptyList());
+    }
+    
     /**
      * Schedules (or reschedules) the session timeout for the member.
      *
@@ -3565,6 +4417,28 @@ public class GroupMetadataManager {
         );
     }
 
+    /**
+     * Schedules (or reschedules) the session timeout for the member.
+     *
+     * @param groupId           The group id.
+     * @param memberId          The member id.
+     * @param sessionTimeoutMs  The session timeout.
+     */
+    private void scheduleStreamsGroupSessionTimeout(
+        String groupId,
+        String memberId,
+        int sessionTimeoutMs
+    ) {
+        timer.schedule(
+            streamsGroupSessionTimeoutKey(groupId, memberId),
+            sessionTimeoutMs,
+            TimeUnit.MILLISECONDS,
+            true,
+            () -> streamsGroupFenceMemberOperation(groupId, memberId, "the member session expired.")
+        );
+    }
+    
+    /**
     /**
      * Cancels the session timeout of the member.
      *
@@ -3578,6 +4452,19 @@ public class GroupMetadataManager {
         timer.cancel(groupSessionTimeoutKey(groupId, memberId));
     }
 
+    /**
+     * Cancels the session timeout of the member.
+     *
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void cancelStreamsGroupSessionTimeout(
+        String groupId,
+        String memberId
+    ) {
+        timer.cancel(streamsGroupSessionTimeoutKey(groupId, memberId));
+    }
+
     /**
      * Schedules a rebalance timeout for the member.
      *
@@ -3621,6 +4508,49 @@ public class GroupMetadataManager {
         });
     }
 
+    /**
+     * Schedules a rebalance timeout for the member.
+     *
+     * @param groupId               The group id.
+     * @param memberId              The member id.
+     * @param memberEpoch           The member epoch.
+     * @param rebalanceTimeoutMs    The rebalance timeout.
+     */
+    private void scheduleStreamsGroupRebalanceTimeout(
+        String groupId,
+        String memberId,
+        int memberEpoch,
+        int rebalanceTimeoutMs
+    ) {
+        String key = streamsGroupRebalanceTimeoutKey(groupId, memberId);
+        timer.schedule(key, rebalanceTimeoutMs, TimeUnit.MILLISECONDS, true, () -> {
+            try {
+                StreamsGroup group = streamsGroup(groupId);
+                StreamsGroupMember member = group.getOrMaybeCreateMember(memberId, false);
+
+                if (member.memberEpoch() == memberEpoch) {
+                    log.info("[GroupId {}] Member {} fenced from the group because " +
+                            "it failed to transition from epoch {} within {}ms.",
+                        groupId, memberId, memberEpoch, rebalanceTimeoutMs);
+
+                    return streamsGroupFenceMember(group, member, null);
+                } else {
+                    log.debug("[GroupId {}] Ignoring rebalance timeout for {} because the member " +
+                        "left the epoch {}.", groupId, memberId, memberEpoch);
+                    return new CoordinatorResult<>(Collections.emptyList());
+                }
+            } catch (GroupIdNotFoundException ex) {
+                log.debug("[GroupId {}] Could not fence {}} because the group does not exist.",
+                    groupId, memberId);
+            } catch (UnknownMemberIdException ex) {
+                log.debug("[GroupId {}] Could not fence {} because the member does not exist.",
+                    groupId, memberId);
+            }
+
+            return new CoordinatorResult<>(Collections.emptyList());
+        });
+    }
+
     /**
      * Cancels the rebalance timeout of the member.
      *
@@ -3634,6 +4564,19 @@ public class GroupMetadataManager {
         timer.cancel(consumerGroupRebalanceTimeoutKey(groupId, memberId));
     }
 
+    /**
+     * Cancels the rebalance timeout of the member.
+     *
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void cancelStreamsGroupRebalanceTimeout(
+        String groupId,
+        String memberId
+    ) {
+        timer.cancel(streamsGroupRebalanceTimeoutKey(groupId, memberId));
+    }
+
     /**
      * Schedules a join timeout for the member if there's not a join timeout.
      *
@@ -3655,6 +4598,27 @@ public class GroupMetadataManager {
         );
     }
 
+    /**
+     * Schedules a join timeout for the member if there's not a join timeout.
+     *
+     * @param groupId               The group id.
+     * @param memberId              The member id.
+     * @param rebalanceTimeoutMs    The rebalance timeout.
+     */
+    private void scheduleStreamsGroupJoinTimeoutIfAbsent(
+        String groupId,
+        String memberId,
+        int rebalanceTimeoutMs
+    ) {
+        timer.scheduleIfAbsent(
+            streamsGroupJoinKey(groupId, memberId),
+            rebalanceTimeoutMs,
+            TimeUnit.MILLISECONDS,
+            true,
+            () -> streamsGroupFenceMemberOperation(groupId, memberId, "the classic member failed to join within the rebalance timeout.")
+        );
+    }
+
     /**
      * Cancels the join timeout of the member.
      *
@@ -3668,6 +4632,19 @@ public class GroupMetadataManager {
         timer.cancel(consumerGroupJoinKey(groupId, memberId));
     }
 
+    /**
+     * Cancels the join timeout of the member.
+     *
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void cancelStreamsGroupJoinTimeout(
+        String groupId,
+        String memberId
+    ) {
+        timer.cancel(streamsGroupJoinKey(groupId, memberId));
+    }
+
     /**
      * Schedules a sync timeout for the member.
      *
@@ -3689,6 +4666,27 @@ public class GroupMetadataManager {
         );
     }
 
+    /**
+     * Schedules a sync timeout for the member.
+     *
+     * @param groupId               The group id.
+     * @param memberId              The member id.
+     * @param rebalanceTimeoutMs    The rebalance timeout.
+     */
+    private void scheduleStreamsGroupSyncTimeout(
+        String groupId,
+        String memberId,
+        int rebalanceTimeoutMs
+    ) {
+        timer.schedule(
+            streamsGroupSyncKey(groupId, memberId),
+            rebalanceTimeoutMs,
+            TimeUnit.MILLISECONDS,
+            true,
+            () -> streamsGroupFenceMemberOperation(groupId, memberId, "the member failed to sync within timeout.")
+        );
+    }
+
     /**
      * Cancels the sync timeout of the member.
      *
@@ -3702,6 +4700,19 @@ public class GroupMetadataManager {
         timer.cancel(consumerGroupSyncKey(groupId, memberId));
     }
 
+    /**
+     * Cancels the sync timeout of the member.
+     *
+     * @param groupId       The group id.
+     * @param memberId      The member id.
+     */
+    private void cancelStreamsGroupSyncTimeout(
+        String groupId,
+        String memberId
+    ) {
+        timer.cancel(streamsGroupSyncKey(groupId, memberId));
+    }
+
     /**
      * Handles a ConsumerGroupHeartbeat request.
      *
@@ -3781,37 +4792,39 @@ public class GroupMetadataManager {
     ) throws ApiException {
         throwIfStreamsHeartbeatRequestIsInvalid(request);
 
-        return new CoordinatorResult<>(
-            Collections.emptyList(),
-            new StreamsHeartbeatResponseData()
-                .setErrorCode(Errors.NONE.code())
-        );
-
-//        if (request.memberEpoch() == LEAVE_GROUP_MEMBER_EPOCH || request.memberEpoch() == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
-//            // TODO: -1 means that the member wants to leave the group.
-//            // -2 means that a static member wants to leave the group.
-//            return consumerGroupLeave(
-//                request.groupId(),
-//                request.instanceId(),
-//                request.memberId(),
-//                request.memberEpoch()
-//            );
-//        } else {
-//            // TODO: Otherwise, it is a regular heartbeat.
-//            return consumerGroupHeartbeat(
-//                request.groupId(),
-//                request.memberId(),
-//                request.memberEpoch(),
-//                request.instanceId(),
-//                request.rackId(),
-//                request.rebalanceTimeoutMs(),
-//                context.clientId(),
-//                context.clientAddress.toString(),
-//                request.subscribedTopicNames(),
-//                request.serverAssignor(),
-//                request.topicPartitions()
-//            );
-//        }
+        if (request.memberEpoch() == LEAVE_GROUP_MEMBER_EPOCH || request.memberEpoch() == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
+            // -2 means that a static member wants to leave the group.
+            return streamsGroupLeave(
+                request.groupId(),
+                request.instanceId(),
+                request.memberId(),
+                request.memberEpoch()
+            );
+        } else {
+            return streamsHeartbeat(
+                request.groupId(),
+                request.memberId(),
+                request.memberEpoch(),
+                request.instanceId(),
+                request.rackId(),
+                request.rebalanceTimeoutMs(),
+                request.topologyHash(),
+                context.clientId(),
+                context.clientAddress.toString(),
+                request.assignor(),
+                request.activeTasks(),
+                request.standbyTasks(),
+                request.warmupTasks(),
+                request.processId(),
+                request.hostInfo(),
+                request.clientTags(),
+                request.taskOffsetUpdateReason(),
+                request.taskOffset(),
+                request.userData(),
+                request.assignmentConfigs(),
+                request.shutdownApplication()
+            );
+        }
     }
 
     /**
@@ -4594,6 +5607,23 @@ public class GroupMetadataManager {
         Map<ClassicGroupState, Long> classicGroupSizeCounter = new HashMap<>();
         groups.forEach((groupId, group) -> {
             switch (group.type()) {
+                case STREAMS:
+                    StreamsGroup streamsGroup = (StreamsGroup) group;
+                    log.info("Loaded streams group {} with {} members.", groupId, streamsGroup.members().size());
+                    streamsGroup.members().forEach((memberId, member) -> {
+                        log.debug("Loaded member {} in streams group {}.", memberId, groupId);
+                        scheduleStreamsGroupSessionTimeout(groupId, memberId);
+                        if (member.state() == org.apache.kafka.coordinator.group.streams.MemberState.UNREVOKED_TASKS) {
+                            scheduleStreamsGroupRebalanceTimeout(
+                                groupId,
+                                member.memberId(),
+                                member.memberEpoch(),
+                                member.rebalanceTimeoutMs()
+                            );
+                        }
+                    });
+                    break;
+
                 case CONSUMER:
                     ConsumerGroup consumerGroup = (ConsumerGroup) group;
                     log.info("Loaded consumer group {} with {} members.", groupId, consumerGroup.members().size());
@@ -4648,6 +5678,11 @@ public class GroupMetadataManager {
     public void onUnloaded() {
         groups.values().forEach(group -> {
             switch (group.type()) {
+                case STREAMS:
+                    StreamsGroup streamsGroup = (StreamsGroup) group;
+                    log.info("[GroupId={}] Unloaded group metadata for group epoch {}.",
+                        streamsGroup.groupId(), streamsGroup.groupEpoch());
+                    break;
                 case CONSUMER:
                     ConsumerGroup consumerGroup = (ConsumerGroup) group;
                     log.info("[GroupId={}] Unloaded group metadata for group epoch {}.",
@@ -4700,6 +5735,14 @@ public class GroupMetadataManager {
         return "rebalance-timeout-" + groupId + "-" + memberId;
     }
 
+    public static String streamsGroupSessionTimeoutKey(String groupId, String memberId) {
+        return "session-timeout-" + groupId + "-" + memberId;
+    }
+
+    public static String streamsGroupRebalanceTimeoutKey(String groupId, String memberId) {
+        return "rebalance-timeout-" + groupId + "-" + memberId;
+    }
+
     /**
      * Replays GroupMetadataKey/Value to update the soft state of
      * the classic group.
@@ -6953,4 +7996,32 @@ public class GroupMetadataManager {
     static String consumerGroupSyncKey(String groupId, String memberId) {
         return "sync-" + groupId + "-" + memberId;
     }
+
+    /**
+     * Generate a streams group join key for the timer.
+     *
+     * Package private for testing.
+     *
+     * @param groupId   The group id.
+     * @param memberId  The member id.
+     *
+     * @return the sync key.
+     */
+    static String streamsGroupJoinKey(String groupId, String memberId) {
+        return "join-" + groupId + "-" + memberId;
+    }
+
+    /**
+     * Generate a streams group sync key for the timer.
+     *
+     * Package private for testing.
+     *
+     * @param groupId   The group id.
+     * @param memberId  The member id.
+     *
+     * @return the sync key.
+     */
+    static String streamsGroupSyncKey(String groupId, String memberId) {
+        return "sync-" + groupId + "-" + memberId;
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Utils.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Utils.java
index 5e32d17ae50..943a7a99a10 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Utils.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Utils.java
@@ -235,4 +235,32 @@ public class Utils {
             return apiMessageAndVersion.message();
         }
     }
+
+
+    /**
+     * @return The provided assignment as a String.
+     *
+     * Example:
+     * [subtopologyid1-0, subtopologyid1-1, subtopologyid2-0, subtopologyid2-1]
+     */
+    public static String taskAssignmentToString(
+        Map<String, Set<Integer>> assignment
+    ) {
+        StringBuilder builder = new StringBuilder("[");
+        Iterator<Map.Entry<String, Set<Integer>>> subtopologyIterator = assignment.entrySet().iterator();
+        while (subtopologyIterator.hasNext()) {
+            Map.Entry<String, Set<Integer>> entry = subtopologyIterator.next();
+            Iterator<Integer> partitionsIterator = entry.getValue().iterator();
+            while (partitionsIterator.hasNext()) {
+                builder.append(entry.getKey());
+                builder.append("-");
+                builder.append(partitionsIterator.next());
+                if (partitionsIterator.hasNext() || subtopologyIterator.hasNext()) {
+                    builder.append(", ");
+                }
+            }
+        }
+        builder.append("]");
+        return builder.toString();
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
index 23606593a6b..a71caae371f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
@@ -29,6 +29,7 @@ import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.classic.ClassicGroupState;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup.ConsumerGroupState;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState;
 import org.apache.kafka.server.metrics.KafkaYammerMetrics;
 import org.apache.kafka.timeline.SnapshotRegistry;
 
@@ -73,6 +74,8 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
     public static final String SHARE_GROUP_COUNT_METRIC_NAME = "group-count";
     public static final String CONSUMER_GROUP_COUNT_STATE_TAG = "state";
     public static final String SHARE_GROUP_COUNT_STATE_TAG = CONSUMER_GROUP_COUNT_STATE_TAG;
+    public final static String STREAMS_GROUP_COUNT_METRIC_NAME = "streams-group-count";
+    public final static String STREAMS_GROUP_COUNT_STATE_TAG = "state";
 
     public static final String OFFSET_COMMITS_SENSOR_NAME = "OffsetCommits";
     public static final String OFFSET_EXPIRED_SENSOR_NAME = "OffsetExpired";
@@ -80,6 +83,7 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
     public static final String CLASSIC_GROUP_COMPLETED_REBALANCES_SENSOR_NAME = "CompletedRebalances";
     public static final String CONSUMER_GROUP_REBALANCES_SENSOR_NAME = "ConsumerGroupRebalances";
     public static final String SHARE_GROUP_REBALANCES_SENSOR_NAME = "ShareGroupRebalances";
+    public static final String STREAMS_GROUP_REBALANCES_SENSOR_NAME = "StreamsGroupRebalances";
 
     private final MetricName classicGroupCountMetricName;
     private final MetricName consumerGroupCountMetricName;
@@ -92,6 +96,12 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
     private final MetricName shareGroupCountEmptyMetricName;
     private final MetricName shareGroupCountStableMetricName;
     private final MetricName shareGroupCountDeadMetricName;
+    private final MetricName streamsGroupCountMetricName;
+    private final MetricName streamsGroupCountEmptyMetricName;
+    private final MetricName streamsGroupCountAssigningMetricName;
+    private final MetricName streamsGroupCountReconcilingMetricName;
+    private final MetricName streamsGroupCountStableMetricName;
+    private final MetricName streamsGroupCountDeadMetricName;
 
     private final MetricsRegistry registry;
     private final Metrics metrics;
@@ -188,6 +198,47 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             "The number of share groups in dead state.",
             SHARE_GROUP_PROTOCOL_TAG, Group.GroupType.SHARE.toString(),
             SHARE_GROUP_COUNT_STATE_TAG, ShareGroup.ShareGroupState.DEAD.toString()
+
+        streamsGroupCountMetricName = metrics.metricName(
+            GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The total number of groups using the streams rebalance protocol.",
+            Collections.singletonMap(GROUP_COUNT_PROTOCOL_TAG, Group.GroupType.STREAMS.toString())
+        );
+
+        streamsGroupCountEmptyMetricName = metrics.metricName(
+            STREAMS_GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The number of streams groups in empty state.",
+            Collections.singletonMap(STREAMS_GROUP_COUNT_STATE_TAG, StreamsGroupState.EMPTY.toString())
+        );
+
+        streamsGroupCountAssigningMetricName = metrics.metricName(
+            STREAMS_GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The number of streams groups in assigning state.",
+            Collections.singletonMap(STREAMS_GROUP_COUNT_STATE_TAG, StreamsGroupState.ASSIGNING.toString())
+        );
+
+        streamsGroupCountReconcilingMetricName = metrics.metricName(
+            STREAMS_GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The number of streams groups in reconciling state.",
+            Collections.singletonMap(STREAMS_GROUP_COUNT_STATE_TAG, StreamsGroupState.RECONCILING.toString())
+        );
+
+        streamsGroupCountStableMetricName = metrics.metricName(
+            STREAMS_GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The number of streams groups in stable state.",
+            Collections.singletonMap(STREAMS_GROUP_COUNT_STATE_TAG, StreamsGroupState.STABLE.toString())
+        );
+
+        streamsGroupCountDeadMetricName = metrics.metricName(
+            STREAMS_GROUP_COUNT_METRIC_NAME,
+            METRICS_GROUP,
+            "The number of streams groups in dead state.",
+            Collections.singletonMap(STREAMS_GROUP_COUNT_STATE_TAG, StreamsGroupState.DEAD.toString())
         );
 
         registerGauges();
@@ -247,6 +298,16 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
                 METRICS_GROUP,
                 "The total number of share group rebalances",
                 SHARE_GROUP_PROTOCOL_TAG, Group.GroupType.SHARE.toString())));
+        
+        Sensor streamsGroupRebalanceSensor = metrics.sensor(STREAMS_GROUP_REBALANCES_SENSOR_NAME);
+        streamsGroupRebalanceSensor.add(new Meter(
+            metrics.metricName("streams-group-rebalance-rate",
+                METRICS_GROUP,
+                "The rate of streams group rebalances"),
+            metrics.metricName("streams-group-rebalance-count",
+                METRICS_GROUP,
+                "The total number of streams group rebalances")));
+
 
         globalSensors = Collections.unmodifiableMap(Utils.mkMap(
             Utils.mkEntry(OFFSET_COMMITS_SENSOR_NAME, offsetCommitsSensor),
@@ -254,7 +315,8 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             Utils.mkEntry(OFFSET_DELETIONS_SENSOR_NAME, offsetDeletionsSensor),
             Utils.mkEntry(CLASSIC_GROUP_COMPLETED_REBALANCES_SENSOR_NAME, classicGroupCompletedRebalancesSensor),
             Utils.mkEntry(CONSUMER_GROUP_REBALANCES_SENSOR_NAME, consumerGroupRebalanceSensor),
-            Utils.mkEntry(SHARE_GROUP_REBALANCES_SENSOR_NAME, shareGroupRebalanceSensor)
+            Utils.mkEntry(SHARE_GROUP_REBALANCES_SENSOR_NAME, shareGroupRebalanceSensor),
+            Utils.mkEntry(STREAMS_GROUP_REBALANCES_SENSOR_NAME, streamsGroupRebalanceSensor)
         ));
     }
 
@@ -278,6 +340,14 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
         return shards.values().stream().mapToLong(shard -> shard.numConsumerGroups(state)).sum();
     }
 
+    private long numStreamsGroups() {
+        return shards.values().stream().mapToLong(GroupCoordinatorMetricsShard::numStreamsGroups).sum();
+    }
+
+    private long numStreamsGroups(StreamsGroupState state) {
+        return shards.values().stream().mapToLong(shard -> shard.numStreamsGroups(state)).sum();
+    }
+    
     private long numShareGroups() {
         return shards.values().stream().mapToLong(GroupCoordinatorMetricsShard::numShareGroups).sum();
     }
@@ -309,7 +379,13 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             shareGroupCountMetricName,
             shareGroupCountEmptyMetricName,
             shareGroupCountStableMetricName,
-            shareGroupCountDeadMetricName
+            shareGroupCountDeadMetricName,
+            streamsGroupCountMetricName,
+            streamsGroupCountEmptyMetricName,
+            streamsGroupCountAssigningMetricName,
+            streamsGroupCountReconcilingMetricName,
+            streamsGroupCountStableMetricName,
+            streamsGroupCountDeadMetricName
         ).forEach(metrics::removeMetric);
 
         Arrays.asList(
@@ -318,7 +394,8 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             OFFSET_DELETIONS_SENSOR_NAME,
             CLASSIC_GROUP_COMPLETED_REBALANCES_SENSOR_NAME,
             CONSUMER_GROUP_REBALANCES_SENSOR_NAME,
-            SHARE_GROUP_REBALANCES_SENSOR_NAME
+            SHARE_GROUP_REBALANCES_SENSOR_NAME,
+            STREAMS_GROUP_REBALANCES_SENSOR_NAME
         ).forEach(metrics::removeSensor);
     }
 
@@ -461,5 +538,35 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             shareGroupCountDeadMetricName,
             (Gauge<Long>) (config, now) -> numShareGroups(ShareGroup.ShareGroupState.DEAD)
         );
+
+        metrics.addMetric(
+            streamsGroupCountMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups()
+        );
+
+        metrics.addMetric(
+            streamsGroupCountEmptyMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups(StreamsGroupState.EMPTY)
+        );
+
+        metrics.addMetric(
+            streamsGroupCountAssigningMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups(StreamsGroupState.ASSIGNING)
+        );
+
+        metrics.addMetric(
+            streamsGroupCountReconcilingMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups(StreamsGroupState.RECONCILING)
+        );
+
+        metrics.addMetric(
+            streamsGroupCountStableMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups(StreamsGroupState.STABLE)
+        );
+
+        metrics.addMetric(
+            streamsGroupCountDeadMetricName,
+            (Gauge<Long>) (config, now) -> numStreamsGroups(StreamsGroupState.DEAD)
+        );
     }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
index 219a4f0a22c..4ad6e7460f6 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetricsShard.java
@@ -23,6 +23,7 @@ import org.apache.kafka.coordinator.common.runtime.CoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.classic.ClassicGroupState;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup.ConsumerGroupState;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState;
 import org.apache.kafka.timeline.SnapshotRegistry;
 import org.apache.kafka.timeline.TimelineLong;
 
@@ -78,6 +79,11 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
      */
     private final Map<ShareGroup.ShareGroupState, TimelineGaugeCounter> shareGroupGauges;
 
+    /*
+     * Streams group size gauge counters keyed by the metric name.
+     */
+    private final Map<StreamsGroupState, TimelineGaugeCounter> streamsGroupGauges;
+
     /**
      * All sensors keyed by the sensor name. A Sensor object is shared across all metrics shards.
      */
@@ -131,6 +137,19 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
                 new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0)))
         );
 
+        this.streamsGroupGauges = Utils.mkMap(
+            Utils.mkEntry(StreamsGroupState.EMPTY,
+                new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0))),
+            Utils.mkEntry(StreamsGroupState.ASSIGNING,
+                new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0))),
+            Utils.mkEntry(StreamsGroupState.RECONCILING,
+                new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0))),
+            Utils.mkEntry(StreamsGroupState.STABLE,
+                new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0))),
+            Utils.mkEntry(StreamsGroupState.DEAD,
+                new TimelineGaugeCounter(new TimelineLong(snapshotRegistry), new AtomicLong(0)))
+        );
+
         this.globalSensors = Objects.requireNonNull(globalSensors);
         this.topicPartition = Objects.requireNonNull(topicPartition);
     }
@@ -158,6 +177,20 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
         }
     }
 
+    /**
+     * Increment the number of streams groups.
+     *
+     * @param state the streams group state.
+     */
+    public void incrementNumStreamsGroups(StreamsGroupState state) {
+        TimelineGaugeCounter gaugeCounter = streamsGroupGauges.get(state);
+        if (gaugeCounter != null) {
+            synchronized (gaugeCounter.timelineLong) {
+                gaugeCounter.timelineLong.increment();
+            }
+        }
+    }
+
     /**
      * Decrement the number of offsets.
      */
@@ -181,6 +214,20 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
         }
     }
 
+    /**
+     * Decrement the number of streams groups.
+     *
+     * @param state the streams group state.
+     */
+    public void decrementNumStreamsGroups(StreamsGroupState state) {
+        TimelineGaugeCounter gaugeCounter = streamsGroupGauges.get(state);
+        if (gaugeCounter != null) {
+            synchronized (gaugeCounter.timelineLong) {
+                gaugeCounter.timelineLong.decrement();
+            }
+        }
+    }
+
     /**
      * @return The number of offsets.
      */
@@ -233,6 +280,29 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
         return consumerGroupGauges.values().stream()
             .mapToLong(timelineGaugeCounter -> timelineGaugeCounter.atomicLong.get()).sum();
     }
+    
+    /**
+     * Obtain the number of streams groups in the specified state.
+     *
+     * @param state  the streams group state.
+     *
+     * @return   The number of streams groups in `state`.
+     */
+    public long numStreamsGroups(StreamsGroupState state) {
+        TimelineGaugeCounter gaugeCounter = streamsGroupGauges.get(state);
+        if (gaugeCounter != null) {
+            return gaugeCounter.atomicLong.get();
+        }
+        return 0L;
+    }
+
+    /**
+     * @return The total number of streams groups.
+     */
+    public long numStreamsGroups() {
+        return streamsGroupGauges.values().stream()
+            .mapToLong(timelineGaugeCounter -> timelineGaugeCounter.atomicLong.get()).sum();
+    }
 
     @Override
     public void record(String sensorName) {
@@ -265,6 +335,14 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
             gaugeCounter.atomicLong.set(value);
         });
 
+        this.streamsGroupGauges.forEach((__, gaugeCounter) -> {
+            long value;
+            synchronized (gaugeCounter.timelineLong) {
+                value = gaugeCounter.timelineLong.get(offset);
+            }
+            gaugeCounter.atomicLong.set(value);
+        });
+
         synchronized (numClassicGroupsTimelineCounter.timelineLong) {
             long value = numClassicGroupsTimelineCounter.timelineLong.get(offset);
             numClassicGroupsTimelineCounter.atomicLong.set(value);
@@ -413,4 +491,54 @@ public class GroupCoordinatorMetricsShard implements CoordinatorMetricsShard {
             }
         }
     }
+    
+    /**
+     * Called when a streams group's state has changed. Increment/decrement
+     * the counter accordingly.
+     *
+     * @param oldState The previous state. null value means that it's a new group.
+     * @param newState The next state. null value means that the group has been removed.
+     */
+    public void onStreamsGroupStateTransition(
+        StreamsGroupState oldState,
+        StreamsGroupState newState
+    ) {
+        if (newState != null) {
+            switch (newState) {
+                case EMPTY:
+                    incrementNumStreamsGroups(StreamsGroupState.EMPTY);
+                    break;
+                case ASSIGNING:
+                    incrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
+                    break;
+                case RECONCILING:
+                    incrementNumStreamsGroups(StreamsGroupState.RECONCILING);
+                    break;
+                case STABLE:
+                    incrementNumStreamsGroups(StreamsGroupState.STABLE);
+                    break;
+                case DEAD:
+                    incrementNumStreamsGroups(StreamsGroupState.DEAD);
+            }
+        }
+
+        if (oldState != null) {
+            switch (oldState) {
+                case EMPTY:
+                    decrementNumStreamsGroups(StreamsGroupState.EMPTY);
+                    break;
+                case ASSIGNING:
+                    decrementNumStreamsGroups(StreamsGroupState.ASSIGNING);
+                    break;
+                case RECONCILING:
+                    decrementNumStreamsGroups(StreamsGroupState.RECONCILING);
+                    break;
+                case STABLE:
+                    decrementNumStreamsGroups(StreamsGroupState.STABLE);
+                    break;
+                case DEAD:
+                    decrementNumStreamsGroups(StreamsGroupState.DEAD);
+            }
+        }
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index 30813ba5c13..8f0819eae45 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -53,7 +53,7 @@ public class CurrentAssignmentBuilder {
      * A function which returns the current epoch of a topic-partition or -1 if the topic-partition is not assigned. The current epoch is
      * the epoch of the current owner.
      */
-    private BiFunction<String, Integer, Integer> currentPartitionEpoch;
+    private BiFunction<String, Integer, Integer> currentTaskEpoch;
 
     /**
      * The active tasks owned by the streams. This is directly provided by the member in the StreamsHeartbeat request.
@@ -99,13 +99,13 @@ public class CurrentAssignmentBuilder {
      * Sets a BiFunction which allows to retrieve the current epoch of a partition. This is used by the state machine to determine if a
      * partition is free or still used by another member.
      *
-     * @param currentPartitionEpoch A BiFunction which gets the epoch of a topic id / tasks id pair.
+     * @param currentTaskEpoch A BiFunction which gets the epoch of a topic id / tasks id pair.
      * @return This object.
      */
-    public CurrentAssignmentBuilder withCurrentPartitionEpoch(
-        BiFunction<String, Integer, Integer> currentPartitionEpoch
+    public CurrentAssignmentBuilder withCurrentActiveTaskEpoch(
+        BiFunction<String, Integer, Integer> currentTaskEpoch
     ) {
-        this.currentPartitionEpoch = Objects.requireNonNull(currentPartitionEpoch);
+        this.currentTaskEpoch = Objects.requireNonNull(currentTaskEpoch);
         return this;
     }
 
@@ -297,7 +297,7 @@ public class CurrentAssignmentBuilder {
             Set<Integer> tasksPendingAssignment = new HashSet<>(target);
             tasksPendingAssignment.removeAll(assignedTasks);
             hasUnreleasedTasks = tasksPendingAssignment.removeIf(partitionId ->
-                currentPartitionEpoch.apply(subtopologyId, partitionId) != -1
+                currentTaskEpoch.apply(subtopologyId, partitionId) != -1
             ) || hasUnreleasedTasks;
 
             if (!assignedTasks.isEmpty()) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index d90e749e303..f83305e3e1a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -29,6 +29,8 @@ import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.image.ClusterImage;
 import org.apache.kafka.image.TopicImage;
@@ -47,6 +49,7 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import static java.util.Collections.emptyMap;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.ASSIGNING;
@@ -173,7 +176,7 @@ public class StreamsGroup implements Group {
     /**
      * The Streams topology.
      */
-    private StreamsTopology topology;
+    private TimelineObject<Optional<StreamsTopology>> topology;
 
     /**
      * The metadata refresh deadline. It consists of a timestamp in milliseconds together with the group epoch at the time of setting it.
@@ -206,7 +209,7 @@ public class StreamsGroup implements Group {
         this.currentStandbyTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
         this.currentWarmupTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
         this.metrics = Objects.requireNonNull(metrics);
-        this.topology = null; // TODO
+        this.topology = new TimelineObject<>(snapshotRegistry, Optional.empty());
     }
 
     /**
@@ -244,11 +247,11 @@ public class StreamsGroup implements Group {
     }
 
     public StreamsTopology topology() {
-        return topology;
+        return topology.get().orElse(null);
     }
 
     public void setTopology(StreamsTopology topology) {
-        this.topology = topology;
+        this.topology.set(Optional.of(topology));
     }
 
     /**
@@ -713,20 +716,20 @@ public class StreamsGroup implements Group {
     /**
      * Computes the subscription metadata based on the current subscription info.
      *
-     * @param subscribedTopicNames Map of topic names to the number of subscribers.
      * @param topicsImage          The current metadata for all available topics.
      * @param clusterImage         The current metadata for the Kafka cluster.
      * @return An immutable map of subscription metadata for each topic that the consumer group is subscribed to.
      */
     public Map<String, TopicMetadata> computeSubscriptionMetadata(
-        Map<String, Integer> subscribedTopicNames,
         TopicsImage topicsImage,
         ClusterImage clusterImage
     ) {
+        Set<String> subscribedTopicNames = topology.get().map(StreamsTopology::topicSubscription).orElse(Collections.emptySet());
+
         // Create the topic metadata for each subscribed topic.
         Map<String, TopicMetadata> newSubscriptionMetadata = new HashMap<>(subscribedTopicNames.size());
 
-        subscribedTopicNames.forEach((topicName, count) -> {
+        subscribedTopicNames.forEach(topicName -> {
             TopicImage topicImage = topicsImage.getTopic(topicName);
             if (topicImage != null) {
                 Map<Integer, Set<String>> partitionRacks = new HashMap<>();
@@ -888,10 +891,10 @@ public class StreamsGroup implements Group {
         records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochTombstoneRecord(groupId()));
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorRecordHelpers.newStreamsMemberSubscriptionTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorRecordHelpers.newStreamsGroupMemberTombstoneRecord(groupId(), memberId))
         );
 
-        records.add(CoordinatorRecordHelpers.newStreamsGroupSubscriptionMetadataTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupPartitionMetadataTombstoneRecord(groupId()));
         records.add(CoordinatorRecordHelpers.newStreamsGroupEpochTombstoneRecord(groupId()));
         records.add(CoordinatorRecordHelpers.newStreamsGroupTopologyRecordTombstone(groupId()));
     }
@@ -949,6 +952,7 @@ public class StreamsGroup implements Group {
         }
 
         state.set(newState);
+        metrics.onStreamsGroupStateTransition(previousState, newState);
     }
 
     /**
@@ -1135,7 +1139,7 @@ public class StreamsGroup implements Group {
         );
 
         records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
-        records.add(CoordinatorRecordHelpers.newStreamsGroupSubscriptionMetadataRecord(groupId(), subscriptionMetadata()));
+        records.add(CoordinatorRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), subscriptionMetadata()));
 
         members().forEach((__, streamsGroupMember) ->
             records.add(CoordinatorRecordHelpers.newStreamsCurrentAssignmentRecord(groupId(), streamsGroupMember))
@@ -1182,4 +1186,9 @@ public class StreamsGroup implements Group {
         }
         return false;
     }
+
+    public void setTopology(final StreamsGroupTopologyValue topology) {
+        this.topology.set(Optional.of(new StreamsTopology(topology.topologyHash(), topology.topology().stream().collect(Collectors.toMap(
+            Subtopology::subtopology, x -> x)))));
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index e24a4eb966e..77e038e1a3c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -170,6 +170,11 @@ public class StreamsGroupMember {
             return this;
         }
 
+        public Builder maybeUpdateTopologyHash(Optional<byte[]> topologyHash) {
+            this.topologyHash = topologyHash.orElse(this.topologyHash);
+            return this;
+        }
+
         public Builder setAssignor(String assignor) {
             this.assignor = assignor;
             return this;
@@ -180,26 +185,51 @@ public class StreamsGroupMember {
             return this;
         }
 
+        public Builder maybeUpdateProcessId(Optional<String> processId) {
+            this.processId = processId.orElse(this.processId);
+            return this;
+        }
+        
         public Builder setHostInfo(StreamsGroupMemberMetadataValue.HostInfo hostInfo) {
             this.hostInfo = hostInfo;
             return this;
         }
 
+        public Builder maybeUpdateHostInfo(Optional<StreamsGroupMemberMetadataValue.HostInfo> hostInfo) {
+            this.hostInfo = hostInfo.orElse(this.hostInfo);
+            return this;
+        }
+
         public Builder setClientTags(Map<String, String> clientTags) {
             this.clientTags = clientTags;
             return this;
         }
 
+        public Builder maybeUpdateClientTags(Optional<Map<String, String>> clientTags) {
+            this.clientTags = clientTags.orElse(this.clientTags);
+            return this;
+        }
+
         public Builder setUserData(byte[] userData) {
             this.userData = userData;
             return this;
         }
 
+        public Builder maybeUpdateUserData(Optional<byte[]> userData) {
+            this.userData = userData.orElse(this.userData);
+            return this;
+        }
+
         public Builder setAssignmentConfigs(Map<String, String> assignmentConfigs) {
             this.assignmentConfigs = assignmentConfigs;
             return this;
         }
 
+        public Builder maybeUpdateAssignmentConfigs(Optional<Map<String, String>> assignmentConfigs) {
+            this.assignmentConfigs = assignmentConfigs.orElse(this.assignmentConfigs);
+            return this;
+        }
+
         public Builder setAssignedActiveTasks(Map<String, Set<Integer>> assignedActiveTasks) {
             this.assignedActiveTasks = assignedActiveTasks;
             return this;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 0af7e375af0..9dd960b6aba 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -18,11 +18,14 @@ package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
 
 import java.util.Arrays;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Set;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 /**
  * Immutable topology metadata.
@@ -46,6 +49,13 @@ public class StreamsTopology {
         return subtopologies;
     }
 
+    public Set<String> topicSubscription() {
+        return subtopologies.values().stream()
+            .flatMap(x -> Stream.concat(x.sourceTopics().stream(), x.repartitionSourceTopics().stream().map(
+                TopicInfo::name))).collect(
+                Collectors.toSet());
+    }
+
     public static StreamsTopology fromRecord(
         StreamsGroupTopologyValue record
     ) {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index 26bc409cb7b..b60967dc1f4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -33,8 +33,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.stream.Collectors;
 
-import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord;
 
 /**
  * Build a new Target Assignment based on the provided parameters. As a result, it yields the records that must be persisted to the log and
@@ -117,11 +118,6 @@ public class TargetAssignmentBuilder {
      */
     private Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment = Collections.emptyMap();
 
-    /**
-     * Reverse lookup map representing tasks with their current member assignments.
-     */
-    private Map<String, Map<Integer, String>> invertedTargetAssignment = Collections.emptyMap();
-
     /**
      * The topics image.
      */
@@ -152,13 +148,11 @@ public class TargetAssignmentBuilder {
     public TargetAssignmentBuilder(
         String groupId,
         int groupEpoch,
-        TaskAssignor assignor,
-        StreamsTopology topology
+        TaskAssignor assignor
     ) {
         this.groupId = Objects.requireNonNull(groupId);
         this.groupEpoch = groupEpoch;
         this.assignor = Objects.requireNonNull(assignor);
-        this.topology = Objects.requireNonNull(topology);
     }
 
     /**
@@ -214,31 +208,32 @@ public class TargetAssignmentBuilder {
     }
 
     /**
-     * Adds the existing topic partition assignments.
+     * Adds the topics image.
      *
-     * @param invertedTargetAssignment The reverse lookup map of the current target assignment.
+     * @param topicsImage The topics image.
      * @return This object.
      */
-    public TargetAssignmentBuilder withInvertedTargetAssignment(
-        Map<String, Map<Integer, String>> invertedTargetAssignment
+    public TargetAssignmentBuilder withTopicsImage(
+        TopicsImage topicsImage
     ) {
-        this.invertedTargetAssignment = invertedTargetAssignment;
+        this.topicsImage = topicsImage;
         return this;
     }
 
     /**
-     * Adds the topics image.
+     * Adds the topology image.
      *
-     * @param topicsImage The topics image.
+     * @param topology The topology.
      * @return This object.
      */
-    public TargetAssignmentBuilder withTopicsImage(
-        TopicsImage topicsImage
+    public TargetAssignmentBuilder withTopology(
+        StreamsTopology topology
     ) {
-        this.topicsImage = topicsImage;
+        this.topology = topology;
         return this;
     }
 
+
     /**
      * Adds or updates a member. This is useful when the updated member is not yet materialized in memory.
      *
@@ -306,13 +301,18 @@ public class TargetAssignmentBuilder {
         });
 
         // Compute the assignment.
-        GroupAssignment newGroupAssignment = assignor.assign(
-            new GroupSpecImpl(
-                Collections.unmodifiableMap(memberSpecs),
-                new ArrayList<>(topology.subtopologies().keySet())
-            ),
-            new TopologyMetadata(subscriptionMetadata, topology)
-        );
+        GroupAssignment newGroupAssignment;
+        if (topology != null) {
+            newGroupAssignment = assignor.assign(
+                new GroupSpecImpl(
+                    Collections.unmodifiableMap(memberSpecs),
+                    new ArrayList<>(topology.subtopologies().keySet())
+                ),
+                new TopologyMetadata(subscriptionMetadata, topology)
+            );
+        } else {
+            newGroupAssignment = new GroupAssignment(memberSpecs.keySet().stream().collect(Collectors.toMap(x -> x, x -> MemberAssignment.empty())));
+        }
 
         // Compute delta from previous to new target assignment and create the
         // relevant records.
@@ -350,7 +350,7 @@ public class TargetAssignmentBuilder {
         });
 
         // Bump the target assignment epoch.
-        records.add(newTargetAssignmentEpochRecord(groupId, groupEpoch));
+        records.add(newStreamsTargetAssignmentEpochRecord(groupId, groupEpoch));
 
         return new TargetAssignmentResult(records, newTargetAssignment);
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java
index 42e5446b778..5f4b88458b0 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java
@@ -16,6 +16,7 @@
  */
 package org.apache.kafka.coordinator.group.taskassignor;
 
+import java.util.Collections;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
@@ -25,6 +26,10 @@ import java.util.Set;
  */
 public class MemberAssignment {
 
+    public static MemberAssignment empty() {
+        return new MemberAssignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap());
+    }
+
     /**
      * The target tasks assigned to this member keyed by subtopologyId.
      */
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
index 74ced92af39..2fb5608861b 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyValue.json
@@ -29,6 +29,8 @@
           "about": "String to uniquely identify the subtopology." },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
+        { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
+          "about": "The regular expressions identifying topics the topology reads from." },
         { "name": "SinkTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology writes to." },
         { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 48afadb6ce7..d450cbeecb1 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -55,11 +55,6 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData;
-import org.apache.kafka.common.message.StreamsInitializeRequestData.Subtopology;
-import org.apache.kafka.common.message.StreamsInitializeRequestData.TopicConfig;
-import org.apache.kafka.common.message.StreamsInitializeRequestData.TopicInfo;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -15857,138 +15852,143 @@ public class GroupMetadataManagerTest {
         return memberIds;
     }
 
-    @Test
-    public void testTopologyInitialization() {
-        String groupId = "fooup";
-
-        Uuid fooTopicId = Uuid.randomUuid();
-        String fooTopicName = "repartition";
-        Uuid barTopicId = Uuid.randomUuid();
-        String barTopicName = "changelog";
-
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(new MetadataImageBuilder()
-                .addTopic(fooTopicId, fooTopicName, 6)
-                .addTopic(barTopicId, barTopicName, 3)
-                .addRacks()
-                .build())
-            .build();
-
-        assertThrows(GroupIdNotFoundException.class, () ->
-            context.groupMetadataManager.consumerGroup(groupId));
-
-        final List<Subtopology> topology = Collections.singletonList(
-            new Subtopology()
-                .setSubtopology("subtopology-id")
-                .setSinkTopics(Collections.singletonList("foo"))
-                .setSourceTopics(Collections.singletonList("bar"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(
-                        new TopicInfo()
-                            .setName("repartition")
-                            .setPartitions(4)
-                            .setTopicConfigs(Collections.singletonList(
-                                new TopicConfig()
-                                    .setKey("config-name1")
-                                    .setValue("config-value1")
-                            ))
-                    )
-                )
-                .setStateChangelogTopics(
-                    Collections.singletonList(
-                        new TopicInfo()
-                            .setName("changelog")
-                            .setTopicConfigs(Collections.singletonList(
-                                new TopicConfig()
-                                    .setKey("config-name2")
-                                    .setValue("config-value2")
-                            ))
-                    )
-                )
-        );
-        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
-            context.streamsInitialize(
-                new StreamsInitializeRequestData()
-                    .setGroupId(groupId)
-                    .setTopology(topology)
-            );
-
-        assertEquals(
-            new StreamsInitializeResponseData(),
-            result.response()
-        );
-
-        List<CoordinatorRecord> expectedRecords = Arrays.asList(
-            CoordinatorRecordHelpers.newStreamsGroupTopologyRecord(
-                groupId,
-                topology
-            )
-        );
-
-        assertRecordsEquals(expectedRecords, result.records());
-    }
-
-    @Test
-    public void testTopologyInitializationMissingInternalTopics() {
-        String groupId = "fooup";
-
-        Uuid fooTopicId = Uuid.randomUuid();
-        String fooTopicName = "repartition";
-
-        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-            .withMetadataImage(new MetadataImageBuilder()
-                .addTopic(fooTopicId, fooTopicName, 6)
-                .addRacks()
-                .build())
-            .build();
-
-        assertThrows(GroupIdNotFoundException.class, () ->
-            context.groupMetadataManager.consumerGroup(groupId));
-
-        final List<Subtopology> topology = Collections.singletonList(
-            new Subtopology()
-                .setSubtopology("subtopology-id")
-                .setSinkTopics(Collections.singletonList("foo"))
-                .setSourceTopics(Collections.singletonList("bar"))
-                .setRepartitionSourceTopics(
-                    Collections.singletonList(
-                        new TopicInfo()
-                            .setName("repartition")
-                            .setPartitions(4)
-                            .setTopicConfigs(Collections.singletonList(
-                                new TopicConfig()
-                                    .setKey("config-name1")
-                                    .setValue("config-value1")
-                            ))
-                    )
-                )
-                .setStateChangelogTopics(
-                    Collections.singletonList(
-                        new TopicInfo()
-                            .setName("changelog")
-                            .setTopicConfigs(Collections.singletonList(
-                                new TopicConfig()
-                                    .setKey("config-name2")
-                                    .setValue("config-value2")
-                            ))
-                    )
-                )
-        );
-        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
-            context.streamsInitialize(
-                new StreamsInitializeRequestData()
-                    .setGroupId(groupId)
-                    .setTopology(topology)
-            );
-
-        assertEquals(
-            new StreamsInitializeResponseData()
-                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
-                .setErrorMessage("Internal topics changelog do not exist."),
-            result.response()
-        );
-
-        assertTrue(result.records().isEmpty());
-
-    }
+    // TODO: bring back topology initialization unit tests
+//    @Test
+//    public void testTopologyInitialization() {
+//        String groupId = "fooup";
+//
+//        Uuid fooTopicId = Uuid.randomUuid();
+//        String fooTopicName = "repartition";
+//        Uuid barTopicId = Uuid.randomUuid();
+//        String barTopicName = "changelog";
+//
+//        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+//            .withMetadataImage(new MetadataImageBuilder()
+//                .addTopic(fooTopicId, fooTopicName, 6)
+//                .addTopic(barTopicId, barTopicName, 3)
+//                .addRacks()
+//                .build())
+//            .build();
+//
+//        context.createStreamsGroup(groupId);
+//
+//        assertThrows(GroupIdNotFoundException.class, () ->
+//            context.groupMetadataManager.consumerGroup(groupId));
+//
+//        final List<Subtopology> topology = Collections.singletonList(
+//            new Subtopology()
+//                .setSubtopology("subtopology-id")
+//                .setSinkTopics(Collections.singletonList("foo"))
+//                .setSourceTopics(Collections.singletonList("bar"))
+//                .setRepartitionSourceTopics(
+//                    Collections.singletonList(
+//                        new TopicInfo()
+//                            .setName("repartition")
+//                            .setPartitions(4)
+//                            .setTopicConfigs(Collections.singletonList(
+//                                new TopicConfig()
+//                                    .setKey("config-name1")
+//                                    .setValue("config-value1")
+//                            ))
+//                    )
+//                )
+//                .setStateChangelogTopics(
+//                    Collections.singletonList(
+//                        new TopicInfo()
+//                            .setName("changelog")
+//                            .setTopicConfigs(Collections.singletonList(
+//                                new TopicConfig()
+//                                    .setKey("config-name2")
+//                                    .setValue("config-value2")
+//                            ))
+//                    )
+//                )
+//        );
+//        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
+//            context.streamsInitialize(
+//                new StreamsInitializeRequestData()
+//                    .setGroupId(groupId)
+//                    .setTopology(topology)
+//            );
+//
+//        assertEquals(
+//            new StreamsInitializeResponseData(),
+//            result.response()
+//        );
+//
+//        List<CoordinatorRecord> expectedRecords = Arrays.asList(
+//            CoordinatorRecordHelpers.newStreamsGroupTopologyRecord(
+//                groupId,
+//                topology
+//            )
+//        );
+//
+//        assertRecordsEquals(expectedRecords, result.records());
+//    }
+//
+//    @Test
+//    public void testTopologyInitializationMissingInternalTopics() {
+//        String groupId = "fooup";
+//
+//        Uuid fooTopicId = Uuid.randomUuid();
+//        String fooTopicName = "repartition";
+//
+//        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+//            .withMetadataImage(new MetadataImageBuilder()
+//                .addTopic(fooTopicId, fooTopicName, 6)
+//                .addRacks()
+//                .build())
+//            .build();
+//
+//        context.createStreamsGroup(groupId);
+//
+//        assertThrows(GroupIdNotFoundException.class, () ->
+//            context.groupMetadataManager.consumerGroup(groupId));
+//
+//        final List<Subtopology> topology = Collections.singletonList(
+//            new Subtopology()
+//                .setSubtopology("subtopology-id")
+//                .setSinkTopics(Collections.singletonList("foo"))
+//                .setSourceTopics(Collections.singletonList("bar"))
+//                .setRepartitionSourceTopics(
+//                    Collections.singletonList(
+//                        new TopicInfo()
+//                            .setName("repartition")
+//                            .setPartitions(4)
+//                            .setTopicConfigs(Collections.singletonList(
+//                                new TopicConfig()
+//                                    .setKey("config-name1")
+//                                    .setValue("config-value1")
+//                            ))
+//                    )
+//                )
+//                .setStateChangelogTopics(
+//                    Collections.singletonList(
+//                        new TopicInfo()
+//                            .setName("changelog")
+//                            .setTopicConfigs(Collections.singletonList(
+//                                new TopicConfig()
+//                                    .setKey("config-name2")
+//                                    .setValue("config-value2")
+//                            ))
+//                    )
+//                )
+//        );
+//        CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> result =
+//            context.streamsInitialize(
+//                new StreamsInitializeRequestData()
+//                    .setGroupId(groupId)
+//                    .setTopology(topology)
+//            );
+//
+//        assertEquals(
+//            new StreamsInitializeResponseData()
+//                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
+//                .setErrorMessage("Internal topics changelog do not exist."),
+//            result.response()
+//        );
+//
+//        assertTrue(result.records().isEmpty());
+//
+//    }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index e2e663466b3..6ad0df3aa4f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -96,6 +96,7 @@ import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.server.common.MetadataVersion;
@@ -427,6 +428,7 @@ public class GroupMetadataManagerTestContext {
         private ShareGroupPartitionAssignor shareGroupAssignor = new MockPartitionAssignor("share");
         private final List<ShareGroupBuilder> shareGroupBuilders = new ArrayList<>();
         private int shareGroupMaxSize = Integer.MAX_VALUE;
+        private List<TaskAssignor> taskAssignors = Collections.singletonList(new MockTaskAssignor("mock"));
 
         public Builder withMetadataImage(MetadataImage metadataImage) {
             this.metadataImage = metadataImage;
@@ -526,6 +528,7 @@ public class GroupMetadataManagerTestContext {
                     .withShareGroupAssignor(shareGroupAssignor)
                     .withShareGroupMaxSize(shareGroupMaxSize)
                     .withGroupConfigManager(groupConfigManager)
+                    .withStreamsGroupAssignors(taskAssignors)
                     .build(),
                 groupConfigManager,
                 classicGroupInitialRebalanceDelayMs,
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/MockTaskAssignor.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/MockTaskAssignor.java
new file mode 100644
index 00000000000..64f15cdfcee
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/MockTaskAssignor.java
@@ -0,0 +1,46 @@
+/*
+ * 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 org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
+import org.apache.kafka.coordinator.group.taskassignor.GroupSpec;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignorException;
+import org.apache.kafka.coordinator.group.taskassignor.TopologyDescriber;
+
+public class MockTaskAssignor implements TaskAssignor {
+    private final String name;
+    private GroupAssignment prepareGroupAssignment = null;
+
+    MockTaskAssignor(String name) {
+        this.name = name;
+    }
+
+    public void prepareGroupAssignment(GroupAssignment prepareGroupAssignment) {
+        this.prepareGroupAssignment = prepareGroupAssignment;
+    }
+
+    @Override
+    public String name() {
+        return name;
+    }
+
+    @Override
+    public GroupAssignment assign(GroupSpec groupSpec, TopologyDescriber topologyDescriber) throws TaskAssignorException {
+        return prepareGroupAssignment;
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetMetadataManagerTest.java
index a7e314f3f07..98aeb3268f0 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/OffsetMetadataManagerTest.java
@@ -61,6 +61,7 @@ import org.apache.kafka.coordinator.group.generated.OffsetCommitValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.taskassignor.MockAssignor;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.server.common.MetadataVersion;
@@ -142,6 +143,7 @@ public class OffsetMetadataManagerTest {
                         .withConsumerGroupAssignors(Collections.singletonList(new RangeAssignor()))
                         .withGroupCoordinatorMetricsShard(metrics)
                         .withGroupConfigManager(configManager)
+                        .withStreamsGroupAssignors(Collections.singletonList(new MockAssignor()))
                         .build();
                 }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
index e3531e11a37..c103f0995b6 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -49,7 +49,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 1, 2, 3),
                 mkTaskAssignment(subtopologyId2, 4, 5, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build();
 
         assertEquals(
@@ -83,7 +83,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .build();
 
         assertEquals(
@@ -117,7 +117,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .build();
 
         assertEquals(
@@ -154,7 +154,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 4, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build();
 
         assertEquals(
@@ -188,7 +188,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 1, 2, 3),
                 mkTaskAssignment(subtopologyId2, 4, 5, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, __) ->
+            .withCurrentActiveTaskEpoch((subtopologyId, __) ->
                 subtopologyId2.equals(subtopologyId) ? 10 : -1
             )
             .withOwnedActiveTasks(Collections.emptyList())
@@ -228,7 +228,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3),
                 mkTaskAssignment(subtopologyId2, 5, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .withOwnedActiveTasks(Arrays.asList(
                 new StreamsHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
@@ -273,7 +273,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 3),
                 mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1);
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1);
 
         assertEquals(
             member,
@@ -330,7 +330,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 3),
                 mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .withOwnedActiveTasks(Arrays.asList(
                 new StreamsHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
@@ -374,7 +374,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .withOwnedActiveTasks(Arrays.asList(
                 new StreamsHeartbeatRequestData.TaskIds()
                     .setSubtopology(subtopologyId1)
@@ -415,7 +415,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3),
                 mkTaskAssignment(subtopologyId2, 5, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build();
 
         assertEquals(
@@ -449,7 +449,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> -1)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> -1)
             .build();
 
         assertEquals(
@@ -483,7 +483,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(11, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 2, 3, 4),
                 mkTaskAssignment(subtopologyId2, 5, 6, 7))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build();
 
         assertEquals(member, updatedMember);
@@ -507,7 +507,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 3),
                 mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build();
 
         assertEquals(
@@ -549,7 +549,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new org.apache.kafka.coordinator.group.streams.Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 3),
                 mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 10)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 10)
             .build());
 
         // Then the member rejoins with no owned tasks.
@@ -557,7 +557,7 @@ public class CurrentAssignmentBuilderTest {
             .withTargetAssignment(12, new Assignment(mkAssignment(
                 mkTaskAssignment(subtopologyId1, 3),
                 mkTaskAssignment(subtopologyId2, 6))))
-            .withCurrentPartitionEpoch((subtopologyId, partitionId) -> 11)
+            .withCurrentActiveTaskEpoch((subtopologyId, partitionId) -> 11)
             .withOwnedActiveTasks(Collections.emptyList())
             .build();
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index ec82b8e99a7..03beca59411 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -40,7 +40,7 @@ import java.util.Set;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.Assertions.assertUnorderedListEquals;
-import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord;
 import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
 import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
@@ -222,12 +222,12 @@ public class TargetAssignmentBuilderTest {
 
             // Create and populate the assignment builder.
             org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder builder = new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(
-                groupId, groupEpoch, assignor, topology)
+                groupId, groupEpoch, assignor)
                 .withMembers(members)
+                .withTopology(topology)
                 .withStaticMembers(staticMembers)
                 .withSubscriptionMetadata(subscriptionMetadata)
                 .withTargetAssignment(targetAssignment)
-                .withInvertedTargetAssignment(invertedTargetAssignment)
                 .withTopicsImage(topicsImage);
 
             // Add the updated members or delete the deleted members.
@@ -306,7 +306,7 @@ public class TargetAssignmentBuilderTest {
         );
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
-        assertEquals(Collections.singletonList(newTargetAssignmentEpochRecord(
+        assertEquals(Collections.singletonList(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         )), result.records());
@@ -345,7 +345,7 @@ public class TargetAssignmentBuilderTest {
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
 
-        assertEquals(Collections.singletonList(newTargetAssignmentEpochRecord(
+        assertEquals(Collections.singletonList(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         )), result.records());
@@ -408,7 +408,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -482,7 +482,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(3));
@@ -568,7 +568,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(3));
@@ -646,7 +646,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -720,7 +720,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -796,7 +796,7 @@ public class TargetAssignmentBuilderTest {
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 1));
 
-        assertEquals(newTargetAssignmentEpochRecord(
+        assertEquals(newStreamsTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(1));
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index eb35666675e..a747f0aa2a8 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -16,23 +16,21 @@
  */
 package org.apache.kafka.streams.integration;
 
+import java.util.Locale;
+
+import kafka.api.IntegrationTestHarness;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.GroupProtocol;
 import org.apache.kafka.common.utils.Exit;
 import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.StreamsConfig.InternalConfig;
-import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
-import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
 import org.apache.kafka.streams.tests.SmokeTestClient;
 import org.apache.kafka.streams.tests.SmokeTestDriver;
-
-import org.junit.jupiter.api.AfterAll;
-import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Tag;
 import org.junit.jupiter.api.Timeout;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 
-import java.io.IOException;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Map;
@@ -45,20 +43,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 @Timeout(600)
 @Tag("integration")
-public class SmokeTestDriverIntegrationTest {
-    public static final EmbeddedKafkaCluster CLUSTER = new EmbeddedKafkaCluster(3);
-
-    @BeforeAll
-    public static void startCluster() throws IOException {
-        CLUSTER.start();
-    }
+public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
 
-    @AfterAll
-    public static void closeCluster() {
-        CLUSTER.stop();
+    @Override
+    public int brokerCount() {
+        return 3;
     }
 
-
     private static class Driver extends Thread {
         private final String bootstrapServers;
         private final int numKeys;
@@ -94,13 +85,32 @@ public class SmokeTestDriverIntegrationTest {
 
     }
 
+    @Override
+    public boolean isNewGroupCoordinatorEnabled() {
+        return true;
+    }
+
+    @Override
+    public boolean isZkMigrationTest() {
+        return false;
+    }
+
+    @Override
+    public boolean isKRaftTest() {
+        return true;
+    }
+
     // In this test, we try to keep creating new stream, and closing the old one, to maintain only 3 streams alive.
     // During the new stream added and old stream left, the stream process should still complete without issue.
     // We set 2 timeout condition to fail the test before passing the verification:
     // (1) 10 min timeout, (2) 30 tries of polling without getting any data
     @ParameterizedTest
     @CsvSource({"false, false", "true, false", "true, true"})
-    public void shouldWorkWithRebalance(final boolean stateUpdaterEnabled, final boolean processingThreadsEnabled) throws InterruptedException {
+    public void shouldWorkWithRebalance(
+        final boolean stateUpdaterEnabled,
+        final boolean processingThreadsEnabled,
+        final boolean consumerProtocolEnabled
+    ) throws InterruptedException {
         Exit.setExitProcedure((statusCode, message) -> {
             throw new AssertionError("Test called exit(). code:" + statusCode + " message:" + message);
         });
@@ -110,9 +120,40 @@ public class SmokeTestDriverIntegrationTest {
         int numClientsCreated = 0;
         final ArrayList<SmokeTestClient> clients = new ArrayList<>();
 
-        IntegrationTestUtils.cleanStateBeforeTest(CLUSTER, SmokeTestDriver.topics());
+        for (final String topic: SmokeTestDriver.topics()) {
+            deleteTopic(topic, listenerName());
+        }
 
-        final String bootstrapServers = CLUSTER.bootstrapServers();
+        for (final String topic: new String[]{
+            "SmokeTest-KSTREAM-REDUCE-STATE-STORE-0000000020-changelog",
+            "SmokeTest-minStoreName-changelog",
+            "SmokeTest-cntByCnt-repartition",
+            "SmokeTest-KTABLE-SUPPRESS-STATE-STORE-0000000011-changelog",
+            "SmokeTest-sum-STATE-STORE-0000000050-changelog",
+            "SmokeTest-uwin-cnt-changelog",
+            "SmokeTest-maxStoreName-changelog",
+            "SmokeTest-cntStoreName-changelog",
+            "SmokeTest-KTABLE-SUPPRESS-STATE-STORE-0000000027-changelog",
+            "SmokeTest-win-sum-changelog",
+            "SmokeTest-uwin-max-changelog",
+            "SmokeTest-uwin-min-changelog",
+            "SmokeTest-cntByCnt-changelog",
+            "data",
+            "echo",
+            "max",
+            "min", "min-suppressed", "min-raw",
+            "dif",
+            "sum",
+            "sws-raw", "sws-suppressed",
+            "cnt",
+            "avg",
+            "tagg",
+            "fk"
+        }) {
+            createTopic(topic, 3, 1, new Properties(), listenerName(), new Properties());
+        }
+
+        final String bootstrapServers = bootstrapServers(listenerName());
         final Driver driver = new Driver(bootstrapServers, 10, 1000);
         driver.start();
         System.out.println("started driver");
@@ -124,6 +165,9 @@ public class SmokeTestDriverIntegrationTest {
         props.put(InternalConfig.PROCESSING_THREADS_ENABLED, processingThreadsEnabled);
         // decrease the session timeout so that we can trigger the rebalance soon after old client left closed
         props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10000);
+        if (consumerProtocolEnabled) {
+            props.put(StreamsConfig.consumerPrefix(ConsumerConfig.GROUP_PROTOCOL_CONFIG), GroupProtocol.CONSUMER.name().toLowerCase(Locale.getDefault()));
+        }
 
         // cycle out Streams instances as long as the test is running.
         while (driver.isAlive()) {
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java
index f361d3dc320..3631ea1bd1f 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskManager.java
@@ -1848,7 +1848,11 @@ public class TaskManager {
      */
     public void updateLags() {
         for (final Task t: tasks.activeTasks()) {
-            t.updateLags();
+            try {
+                t.updateLags();
+            } catch (final Throwable e) {
+                // noop
+            }
         }
     }
 
diff --git a/streams/src/test/resources/log4j.properties b/streams/src/test/resources/log4j.properties
index 104b46df20f..197c8c74210 100644
--- a/streams/src/test/resources/log4j.properties
+++ b/streams/src/test/resources/log4j.properties
@@ -27,6 +27,7 @@ log4j.logger.org.apache.kafka.clients=ERROR
 log4j.logger.org.apache.kafka.clients.consumer=INFO
 log4j.logger.org.apache.kafka.clients.producer=INFO
 log4j.logger.org.apache.kafka.streams=INFO
+log4j.logger.org.apache.kafka.coordinator.group=INFO
 
 # printing out the configs takes up a huge amount of the allotted characters,
 # and provides little value as we can always figure out the test configs without the logs


(kafka) 42/42: Remove unused import

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 744679541e13f3ef49f9aac8b1eb95fac5ad6310
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Thu Nov 28 17:56:14 2024 +0100

    Remove unused import
---
 .../java/org/apache/kafka/streams/processor/internals/StreamThread.java  | 1 -
 1 file changed, 1 deletion(-)

diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index 7f45577dca8..e5208bdea97 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -24,7 +24,6 @@ import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.InvalidOffsetException;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
-import org.apache.kafka.clients.consumer.OffsetResetStrategy;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
 import org.apache.kafka.common.KafkaException;


(kafka) 13/42: Add streams group member

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 9b4480292741a47fc4a2e5c9f639a634918303c7
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Fri Jun 7 15:34:07 2024 +0200

    Add streams group member
    
    See https://github.com/lucasbru/kafka/pull/19
---
 .../org/apache/kafka/coordinator/group/Group.java  |    1 +
 .../group/GroupCoordinatorRecordHelpers.java       |  162 +++
 .../coordinator/group/streams/StreamsGroup.java    | 1104 ++++++++++++++++++++
 .../group/streams/StreamsGroupMember.java          |  704 +++++++++++++
 .../group/streams/SubscribedTopicMetadata.java     |   98 ++
 .../StreamsGroupCurrentMemberAssignmentValue.json  |    2 +-
 .../group/streams/StreamsGroupMemberTest.java      |  298 ++++++
 .../group/streams/StreamsGroupTest.java            |  730 +++++++++++++
 8 files changed, 3098 insertions(+), 1 deletion(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Group.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Group.java
index b5d63499751..79c1b72237b 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Group.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/Group.java
@@ -37,6 +37,7 @@ public interface Group {
         CONSUMER("consumer"),
         CLASSIC("classic"),
         SHARE("share"),
+        STREAMS("streams"),
         UNKNOWN("unknown");
 
         private final String name;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index 98cf7f937e8..ea657361480 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -52,12 +52,23 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.modern.TopicMetadata;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember;
 import org.apache.kafka.coordinator.group.modern.consumer.ResolvedRegularExpression;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
 import org.apache.kafka.server.common.MetadataVersion;
 
@@ -112,6 +123,35 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    public static CoordinatorRecord newStreamsGroupMemberRecord(
+        String groupId,
+        StreamsGroupMember member
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMemberMetadataKey()
+                    .setGroupId(groupId)
+                    .setMemberId(member.memberId()),
+                (short) 11
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupMemberMetadataValue()
+                    .setRackId(member.rackId())
+                    .setInstanceId(member.instanceId())
+                    .setClientId(member.clientId())
+                    .setClientHost(member.clientHost())
+                    .setRebalanceTimeoutMs(member.rebalanceTimeoutMs())
+                    .setTopologyHash(member.topologyHash())
+                    .setProcessId(member.processId())
+                    .setHostInfo(member.hostInfo())
+                    .setClientTags(member.clientTags())
+                    .setUserData(member.userData())
+                    .setAssignmentConfigs(member.assignmentConfigs()),
+               (short) 0
+            )
+        );
+    }
+
     /**
      * Creates a ConsumerGroupMemberMetadata tombstone.
      *
@@ -211,6 +251,24 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    public static CoordinatorRecord newStreamsGroupEpochRecord(
+        String groupId,
+        int newGroupEpoch
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataKey()
+                    .setGroupId(groupId),
+                (short) 9
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupMetadataValue()
+                    .setEpoch(newGroupEpoch),
+                (short) 0
+            )
+        );
+    }
+
     /**
      * Creates a ConsumerGroupMetadata tombstone.
      *
@@ -269,6 +327,55 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    public static CoordinatorRecord newTargetAssignmentRecord(
+        String groupId,
+        String memberId,
+        Map<String, Set<Integer>> activeTasks,
+        Map<String, Set<Integer>> standbyTasks,
+        Map<String, Set<Integer>> warmupTasks
+    ) {
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> activeTaskIds = new ArrayList<>(activeTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : activeTasks.entrySet()) {
+            activeTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> standbyTaskIds = new ArrayList<>(standbyTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : standbyTasks.entrySet()) {
+            standbyTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> warmupTaskIds = new ArrayList<>(warmupTasks.size());
+        for (Map.Entry<String, Set<Integer>> entry : warmupTasks.entrySet()) {
+            warmupTaskIds.add(
+                new StreamsGroupTargetAssignmentMemberValue.TaskIds()
+                    .setSubtopology(entry.getKey())
+                    .setPartitions(new ArrayList<>(entry.getValue()))
+            );
+        }
+
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMemberKey()
+                    .setGroupId(groupId)
+                    .setMemberId(memberId),
+                (short) 13
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMemberValue()
+                    .setActiveTasks(activeTaskIds)
+                    .setStandbyTasks(standbyTaskIds)
+                    .setWarmupTasks(warmupTaskIds),
+                (short) 0
+            )
+        );
+    }
+
     /**
      * Creates a ConsumerGroupTargetAssignmentMember tombstone.
      *
@@ -316,6 +423,24 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    public static CoordinatorRecord newStreamsTargetAssignmentEpochRecord(
+        String groupId,
+        int assignmentEpoch
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMetadataKey()
+                    .setGroupId(groupId),
+                (short) 12
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupTargetAssignmentMetadataValue()
+                    .setAssignmentEpoch(assignmentEpoch),
+                (short) 0
+            )
+        );
+    }
+
     /**
      * Creates a ConsumerGroupTargetAssignmentMetadata tombstone.
      *
@@ -365,6 +490,31 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
+    public static CoordinatorRecord newCurrentAssignmentRecord(
+        String groupId,
+        StreamsGroupMember member
+    ) {
+        return new CoordinatorRecord(
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentKey()
+                    .setGroupId(groupId)
+                    .setMemberId(member.memberId()),
+                (short) 14
+            ),
+            new ApiMessageAndVersion(
+                new StreamsGroupCurrentMemberAssignmentValue()
+                    .setMemberEpoch(member.memberEpoch())
+                    .setPreviousMemberEpoch(member.previousMemberEpoch())
+                    .setState(member.state().value())
+                    .setActiveTasks(toTaskIds(member.assignedActiveTasks()))
+                    .setStandbyTasks(toTaskIds(member.assignedStandbyTasks()))
+                    .setWarmupTasks(toTaskIds(member.assignedWarmupTasks()))
+                    .setActiveTasksPendingRevocation(toTaskIds(member.activeTasksPendingRevocation())),
+                (short) 0
+            )
+        );
+    }
+
     /**
      * Creates a ConsumerGroupCurrentMemberAssignment tombstone.
      *
@@ -943,6 +1093,18 @@ public class GroupCoordinatorRecordHelpers {
         return topics;
     }
 
+    private static List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> toTaskIds(
+        Map<String, Set<Integer>> tasks
+    ) {
+        List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> taskIds = new ArrayList<>(tasks.size());
+        tasks.forEach((subtopologyId, partitions) ->
+            taskIds.add(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId)
+                .setPartitions(new ArrayList<>(partitions)))
+        );
+        return taskIds;
+    }
+
     /**
      * Creates a StreamsTopology record.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
new file mode 100644
index 00000000000..d28e9218994
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -0,0 +1,1104 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.clients.consumer.internals.ConsumerProtocol;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.ApiException;
+import org.apache.kafka.common.errors.StaleMemberEpochException;
+import org.apache.kafka.common.errors.UnknownMemberIdException;
+import org.apache.kafka.common.message.ListGroupsResponseData;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.group.CoordinatorRecordHelpers;
+import org.apache.kafka.coordinator.group.Group;
+import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
+import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
+import org.apache.kafka.coordinator.group.assignor.SubscriptionType;
+import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.image.ClusterImage;
+import org.apache.kafka.image.TopicImage;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineInteger;
+import org.apache.kafka.timeline.TimelineObject;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.kafka.coordinator.group.assignor.SubscriptionType.HETEROGENEOUS;
+import static org.apache.kafka.coordinator.group.assignor.SubscriptionType.HOMOGENEOUS;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.ASSIGNING;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.EMPTY;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.RECONCILING;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.STABLE;
+
+/**
+ * A Streams Group. All the metadata in this class are backed by
+ * records in the __consumer_offsets partitions.
+ */
+public class StreamsGroup implements Group {
+
+    public enum StreamsGroupState {
+        EMPTY("Empty"),
+        ASSIGNING("Assigning"),
+        RECONCILING("Reconciling"),
+        STABLE("Stable"),
+        DEAD("Dead");
+
+        private final String name;
+
+        private final String lowerCaseName;
+
+        StreamsGroupState(String name) {
+            this.name = name;
+            this.lowerCaseName = name.toLowerCase(Locale.ROOT);
+        }
+
+        @Override
+        public String toString() {
+            return name;
+        }
+
+        public String toLowerCaseString() {
+            return lowerCaseName;
+        }
+    }
+
+    public static class DeadlineAndEpoch {
+        static final DeadlineAndEpoch EMPTY = new DeadlineAndEpoch(0L, 0);
+
+        public final long deadlineMs;
+        public final int epoch;
+
+        DeadlineAndEpoch(long deadlineMs, int epoch) {
+            this.deadlineMs = deadlineMs;
+            this.epoch = epoch;
+        }
+    }
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The group id.
+     */
+    private final String groupId;
+
+    /**
+     * The group state.
+     */
+    private final TimelineObject<StreamsGroupState> state;
+
+    /**
+     * The group epoch. The epoch is incremented whenever the subscriptions
+     * are updated and it will trigger the computation of a new assignment
+     * for the group.
+     */
+    private final TimelineInteger groupEpoch;
+
+    /**
+     * The group members.
+     */
+    private final TimelineHashMap<String, StreamsGroupMember> members;
+
+    /**
+     * The static group members.
+     */
+    private final TimelineHashMap<String, String> staticMembers;
+
+    /**
+     * The number of members supporting each assignor name.
+     */
+    private final TimelineHashMap<String, Integer> assignors;
+
+    /**
+     * The target assignment epoch. An assignment epoch smaller than the group epoch
+     * means that a new assignment is required. The assignment epoch is updated when
+     * a new assignment is installed.
+     */
+    private final TimelineInteger targetAssignmentEpoch;
+
+    /**
+     * The target assignment per member id.
+     */
+    private final TimelineHashMap<String, Assignment> targetAssignment;
+
+    /**
+     * Reverse lookup map representing tasks with
+     * their current member assignments.
+     */
+    private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetActiveTasksAssignment;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetStandbyTasksAssignment;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetWarmupTasksAssignment;
+
+    /**
+     * The current partition epoch maps each topic-partitions to their current epoch where
+     * the epoch is the epoch of their owners. When a member revokes a partition, it removes
+     * its epochs from this map. When a member gets a partition, it adds its epochs to this map.
+     */
+    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentActiveTasksEpoch;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentStandbyTasksEpoch;
+    private final TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentWarmupTasksEpoch;
+
+    /**
+     * The coordinator metrics.
+     */
+    private final GroupCoordinatorMetricsShard metrics;
+
+    /**
+     * The metadata refresh deadline. It consists of a timestamp in milliseconds together with
+     * the group epoch at the time of setting it. The metadata refresh time is considered as a
+     * soft state (read that it is not stored in a timeline data structure). It is like this
+     * because it is not persisted to the log. The group epoch is here to ensure that the
+     * metadata refresh deadline is invalidated if the group epoch does not correspond to
+     * the current group epoch. This can happen if the metadata refresh deadline is updated
+     * after having refreshed the metadata but the write operation failed. In this case, the
+     * time is not automatically rolled back.
+     */
+    private DeadlineAndEpoch metadataRefreshDeadline = DeadlineAndEpoch.EMPTY;
+
+    public StreamsGroup(
+        SnapshotRegistry snapshotRegistry,
+        String groupId,
+        GroupCoordinatorMetricsShard metrics
+    ) {
+        this.snapshotRegistry = Objects.requireNonNull(snapshotRegistry);
+        this.groupId = Objects.requireNonNull(groupId);
+        this.state = new TimelineObject<>(snapshotRegistry, EMPTY);
+        this.groupEpoch = new TimelineInteger(snapshotRegistry);
+        this.members = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.staticMembers = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.assignors = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.targetAssignmentEpoch = new TimelineInteger(snapshotRegistry);
+        this.targetAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.invertedTargetActiveTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.invertedTargetStandbyTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.invertedTargetWarmupTasksAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentActiveTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentStandbyTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentWarmupTasksEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.metrics = Objects.requireNonNull(metrics);
+    }
+
+    /**
+     * @return The group type (Streams).
+     */
+    @Override
+    public GroupType type() {
+        return GroupType.STREAMS;
+    }
+
+    /**
+     * @return The current state as a String.
+     */
+    @Override
+    public String stateAsString() {
+        return state.get().toString();
+    }
+
+    /**
+     * @return The current state as a String with given committedOffset.
+     */
+    public String stateAsString(long committedOffset) {
+        return state.get(committedOffset).toString();
+    }
+
+    /**
+     * @return the group formatted as a list group response based on the committed offset.
+     */
+    public ListGroupsResponseData.ListedGroup asListedGroup(long committedOffset) {
+        return new ListGroupsResponseData.ListedGroup()
+            .setGroupId(groupId)
+            .setProtocolType(ConsumerProtocol.PROTOCOL_TYPE)
+            .setGroupState(state.get(committedOffset).toString())
+            .setGroupType(type().toString());
+    }
+
+    /**
+     * @return The group id.
+     */
+    @Override
+    public String groupId() {
+        return groupId;
+    }
+
+    /**
+     * @return The current state.
+     */
+    public StreamsGroupState state() {
+        return state.get();
+    }
+
+    /**
+     * @return The current state based on committed offset.
+     */
+    public StreamsGroupState state(long committedOffset) {
+        return state.get(committedOffset);
+    }
+
+    /**
+     * @return The group epoch.
+     */
+    public int groupEpoch() {
+        return groupEpoch.get();
+    }
+
+    /**
+     * Sets the group epoch.
+     *
+     * @param groupEpoch The new group epoch.
+     */
+    public void setGroupEpoch(int groupEpoch) {
+        this.groupEpoch.set(groupEpoch);
+        maybeUpdateGroupState();
+    }
+
+    /**
+     * @return The target assignment epoch.
+     */
+    public int assignmentEpoch() {
+        return targetAssignmentEpoch.get();
+    }
+
+    /**
+     * Sets the assignment epoch.
+     *
+     * @param targetAssignmentEpoch The new assignment epoch.
+     */
+    public void setTargetAssignmentEpoch(int targetAssignmentEpoch) {
+        this.targetAssignmentEpoch.set(targetAssignmentEpoch);
+        maybeUpdateGroupState();
+    }
+
+    /**
+     * Get member id of a static member that matches the given group
+     * instance id.
+     *
+     * @param groupInstanceId The group instance id.
+     *
+     * @return The member id corresponding to the given instance id or null if it does not exist
+     */
+    public String staticMemberId(String groupInstanceId) {
+        return staticMembers.get(groupInstanceId);
+    }
+
+    /**
+     * Gets or creates a new member but without adding it to the group. Adding a member
+     * is done via the {@link StreamsGroup#updateMember(StreamsGroupMember)} method.
+     *
+     * @param memberId          The member id.
+     * @param createIfNotExists Booleans indicating whether the member must be
+     *                          created if it does not exist.
+     *
+     * @return A StreamsGroupMember.
+     */
+    public StreamsGroupMember getOrMaybeCreateMember(
+        String memberId,
+        boolean createIfNotExists
+    ) {
+        StreamsGroupMember member = members.get(memberId);
+        if (member != null) return member;
+
+        if (!createIfNotExists) {
+            throw new UnknownMemberIdException(
+                String.format("Member %s is not a member of group %s.", memberId, groupId)
+            );
+        }
+
+        return new StreamsGroupMember.Builder(memberId).build();
+    }
+
+    /**
+     * Gets a static member.
+     *
+     * @param instanceId The group instance id.
+     *
+     * @return The member corresponding to the given instance id or null if it does not exist
+     */
+    public StreamsGroupMember staticMember(String instanceId) {
+        String existingMemberId = staticMemberId(instanceId);
+        return existingMemberId == null ? null : getOrMaybeCreateMember(existingMemberId, false);
+    }
+
+    /**
+     * Adds or updates the member.
+     *
+     * @param newMember The new member state.
+     */
+    public void updateMember(StreamsGroupMember newMember) {
+        if (newMember == null) {
+            throw new IllegalArgumentException("newMember cannot be null.");
+        }
+        StreamsGroupMember oldMember = members.put(newMember.memberId(), newMember);
+        maybeUpdateTaskEpoch(oldMember, newMember);
+        updateStaticMember(newMember);
+        maybeUpdateGroupState();
+        maybeUpdateAssignors(oldMember, newMember);
+    }
+
+    /**
+     * Updates the member id stored against the instance id if the member is a static member.
+     *
+     * @param newMember The new member state.
+     */
+    private void updateStaticMember(StreamsGroupMember newMember) {
+        if (newMember.instanceId() != null) {
+            staticMembers.put(newMember.instanceId(), newMember.memberId());
+        }
+    }
+
+    /**
+     * Remove the member from the group.
+     *
+     * @param memberId The member id to remove.
+     */
+    public void removeMember(String memberId) {
+        StreamsGroupMember oldMember = members.remove(memberId);
+        maybeRemoveTaskEpoch(oldMember);
+        removeStaticMember(oldMember);
+        maybeUpdateGroupState();
+    }
+
+    /**
+     * Remove the static member mapping if the removed member is static.
+     *
+     * @param oldMember The member to remove.
+     */
+    private void removeStaticMember(StreamsGroupMember oldMember) {
+        if (oldMember.instanceId() != null) {
+            staticMembers.remove(oldMember.instanceId());
+        }
+    }
+
+    /**
+     * Returns true if the member exists.
+     *
+     * @param memberId The member id.
+     *
+     * @return A boolean indicating whether the member exists or not.
+     */
+    public boolean hasMember(String memberId) {
+        return members.containsKey(memberId);
+    }
+
+    /**
+     * @return The number of members.
+     */
+    public int numMembers() {
+        return members.size();
+    }
+
+    /**
+     * @return An immutable Map containing all the members keyed by their id.
+     */
+    public Map<String, StreamsGroupMember> members() {
+        return Collections.unmodifiableMap(members);
+    }
+
+    /**
+     * @return An immutable Map containing all the static members keyed by instance id.
+     */
+    public Map<String, String> staticMembers() {
+        return Collections.unmodifiableMap(staticMembers);
+    }
+
+    /**
+     * Returns the target assignment of the member.
+     *
+     * @return The StreamsGroupMemberAssignment or an EMPTY one if it does not
+     *         exist.
+     */
+    public Assignment targetAssignment(String memberId) {
+        return targetAssignment.getOrDefault(memberId, Assignment.EMPTY);
+    }
+
+    /**
+     * @return An immutable map containing all the topic partitions
+     *         with their current member assignments.
+     */
+    public Map<String, Map<Integer, String>> invertedTargetActiveTasksAssignment() {
+        return Collections.unmodifiableMap(invertedTargetActiveTasksAssignment);
+    }
+
+    public Map<String, Map<Integer, String>> invertedTargetStandbyTasksAssignment() {
+        return Collections.unmodifiableMap(invertedTargetStandbyTasksAssignment);
+    }
+
+    public Map<String, Map<Integer, String>> invertedTargetWarmupTasksAssignment() {
+        return Collections.unmodifiableMap(invertedTargetWarmupTasksAssignment);
+    }
+
+    /**
+     * Updates the server assignors count.
+     *
+     * @param oldMember The old member.
+     * @param newMember The new member.
+     */
+    private void maybeUpdateAssignors(
+        StreamsGroupMember oldMember,
+        StreamsGroupMember newMember
+    ) {
+        maybeUpdateAssignors(assignors, oldMember, newMember);
+    }
+
+    private static void maybeUpdateAssignors(
+        Map<String, Integer> serverAssignorCount,
+        StreamsGroupMember oldMember,
+        StreamsGroupMember newMember
+    ) {
+        if (oldMember != null) {
+            oldMember.assignor().ifPresent(name ->
+                serverAssignorCount.compute(name, StreamsGroup::decValue)
+            );
+        }
+        if (newMember != null) {
+            newMember.assignor().ifPresent(name ->
+                serverAssignorCount.compute(name, StreamsGroup::incValue)
+            );
+        }
+    }
+
+    /**
+     * Updates the target assignment of a member.
+     *
+     * @param memberId              The member id.
+     * @param newTargetAssignment   The new target assignment.
+     */
+    public void updateTargetAssignment(String memberId, Assignment newTargetAssignment) {
+        updateInvertedTargetActiveTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, new Assignment(emptyMap(), emptyMap(), emptyMap())),
+            newTargetAssignment
+        );
+        updateInvertedTargetStandbyTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, new Assignment(emptyMap(), emptyMap(), emptyMap())),
+            newTargetAssignment
+        );
+        updateInvertedTargetWarmupTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, new Assignment(emptyMap(), emptyMap(), emptyMap())),
+            newTargetAssignment
+        );
+        targetAssignment.put(memberId, newTargetAssignment);
+    }
+
+
+    private void updateInvertedTargetActiveTasksAssignment(
+        String memberId,
+        Assignment oldTargetAssignment,
+        Assignment newTargetAssignment
+    ) {
+        updateInvertedTargetAssignment(
+            memberId,
+            oldTargetAssignment,
+            newTargetAssignment,
+            invertedTargetActiveTasksAssignment
+        );
+    }
+
+    private void updateInvertedTargetStandbyTasksAssignment(
+        String memberId,
+        Assignment oldTargetAssignment,
+        Assignment newTargetAssignment
+    ) {
+        updateInvertedTargetAssignment(
+            memberId,
+            oldTargetAssignment,
+            newTargetAssignment,
+            invertedTargetStandbyTasksAssignment
+        );
+    }
+
+    private void updateInvertedTargetWarmupTasksAssignment(
+        String memberId,
+        Assignment oldTargetAssignment,
+        Assignment newTargetAssignment
+    ) {
+        updateInvertedTargetAssignment(
+            memberId,
+            oldTargetAssignment,
+            newTargetAssignment,
+            invertedTargetWarmupTasksAssignment
+        );
+    }
+
+    /**
+     * Updates the reverse lookup map of the target assignment.
+     *
+     * @param memberId              The member Id.
+     * @param oldTargetAssignment   The old target assignment.
+     * @param newTargetAssignment   The new target assignment.
+     */
+    private void updateInvertedTargetAssignment(
+        String memberId,
+        Assignment oldTargetAssignment,
+        Assignment newTargetAssignment,
+        TimelineHashMap<String, TimelineHashMap<Integer, String>> invertedTargetAssignment
+    ) {
+        // Combine keys from both old and new assignments.
+        Set<String> allSubtopologyIds = new HashSet<>();
+        allSubtopologyIds.addAll(oldTargetAssignment.activeTasks().keySet());
+        allSubtopologyIds.addAll(newTargetAssignment.activeTasks().keySet());
+
+        for (String subtopologyId : allSubtopologyIds) {
+            Set<Integer> oldPartitions = oldTargetAssignment.activeTasks().getOrDefault(subtopologyId, Collections.emptySet());
+            Set<Integer> newPartitions = newTargetAssignment.activeTasks().getOrDefault(subtopologyId, Collections.emptySet());
+
+            TimelineHashMap<Integer, String> taskPartitionAssignment = invertedTargetAssignment.computeIfAbsent(
+                subtopologyId, k -> new TimelineHashMap<>(snapshotRegistry, Math.max(oldPartitions.size(), newPartitions.size()))
+            );
+
+            // Remove partitions that aren't present in the new assignment only if the partition is currently
+            // still assigned to the member in question.
+            // If p0 was moved from A to B, and the target assignment map was updated for B first, we don't want to
+            // remove the key p0 from the inverted map and undo the action when A eventually tries to update its assignment.
+            for (Integer partition : oldPartitions) {
+                if (!newPartitions.contains(partition) && memberId.equals(taskPartitionAssignment.get(partition))) {
+                    taskPartitionAssignment.remove(partition);
+                }
+            }
+
+            // Add partitions that are in the new assignment but not in the old assignment.
+            for (Integer partition : newPartitions) {
+                if (!oldPartitions.contains(partition)) {
+                    taskPartitionAssignment.put(partition, memberId);
+                }
+            }
+
+            if (taskPartitionAssignment.isEmpty()) {
+                invertedTargetAssignment.remove(subtopologyId);
+            } else {
+                invertedTargetAssignment.put(subtopologyId, taskPartitionAssignment);
+            }
+        }
+    }
+
+    /**
+     * Removes the target assignment of a member.
+     *
+     * @param memberId The member id.
+     */
+    public void removeTargetAssignment(String memberId) {
+        updateInvertedTargetActiveTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, Assignment.EMPTY),
+            Assignment.EMPTY
+        );
+        updateInvertedTargetStandbyTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, Assignment.EMPTY),
+            Assignment.EMPTY
+        );
+        updateInvertedTargetWarmupTasksAssignment(
+            memberId,
+            targetAssignment.getOrDefault(memberId, Assignment.EMPTY),
+            Assignment.EMPTY
+        );
+        targetAssignment.remove(memberId);
+    }
+
+    /**
+     * @return An immutable Map containing all the target assignment keyed by member id.
+     */
+    public Map<String, Assignment> targetAssignment() {
+        return Collections.unmodifiableMap(targetAssignment);
+    }
+
+    /**
+     * Returns the current epoch of a partition or -1 if the partition
+     * does not have one.
+     *
+     * @param topicId       The topic id.
+     * @param partitionId   The partition id.
+     *
+     * @return The epoch or -1.
+     */
+    public int currentActiveTaskEpoch(
+        String topicId, int partitionId
+    ) {
+        Map<Integer, Integer> partitions = currentActiveTasksEpoch.get(topicId);
+        if (partitions == null) {
+            return -1;
+        } else {
+            return partitions.getOrDefault(partitionId, -1);
+        }
+    }
+
+    /**
+     * Updates the metadata refresh deadline.
+     *
+     * @param deadlineMs The deadline in milliseconds.
+     * @param groupEpoch The associated group epoch.
+     */
+    public void setMetadataRefreshDeadline(
+        long deadlineMs,
+        int groupEpoch
+    ) {
+        this.metadataRefreshDeadline = new DeadlineAndEpoch(deadlineMs, groupEpoch);
+    }
+
+    /**
+     * Requests a metadata refresh.
+     */
+    public void requestMetadataRefresh() {
+        this.metadataRefreshDeadline = DeadlineAndEpoch.EMPTY;
+    }
+
+    /**
+     * Checks if a metadata refresh is required. A refresh is required in two cases:
+     * 1) The deadline is smaller or equal to the current time;
+     * 2) The group epoch associated with the deadline is larger than
+     *    the current group epoch. This means that the operations which updated
+     *    the deadline failed.
+     *
+     * @param currentTimeMs The current time in milliseconds.
+     * @return A boolean indicating whether a refresh is required or not.
+     */
+    public boolean hasMetadataExpired(long currentTimeMs) {
+        return currentTimeMs >= metadataRefreshDeadline.deadlineMs || groupEpoch() < metadataRefreshDeadline.epoch;
+    }
+
+    /**
+     * @return The metadata refresh deadline.
+     */
+    public DeadlineAndEpoch metadataRefreshDeadline() {
+        return metadataRefreshDeadline;
+    }
+
+    /**
+     * Validates the OffsetCommit request.
+     *
+     * @param memberId          The member id.
+     * @param groupInstanceId   The group instance id.
+     * @param memberEpoch       The member epoch.
+     * @param isTransactional   Whether the offset commit is transactional or not. It has no
+     *                          impact when a consumer group is used.
+     */
+    @Override
+    public void validateOffsetCommit(
+        String memberId,
+        String groupInstanceId,
+        int memberEpoch,
+        boolean isTransactional
+    ) throws UnknownMemberIdException, StaleMemberEpochException {
+        // When the member epoch is -1, the request comes from either the admin client
+        // or a consumer which does not use the group management facility. In this case,
+        // the request can commit offsets if the group is empty.
+        if (memberEpoch < 0 && members().isEmpty()) return;
+
+        final StreamsGroupMember member = getOrMaybeCreateMember(memberId, false);
+        validateMemberEpoch(memberEpoch, member.memberEpoch());
+    }
+
+    /**
+     * Validates the OffsetFetch request.
+     *
+     * @param memberId              The member id for consumer groups.
+     * @param memberEpoch           The member epoch for consumer groups.
+     * @param lastCommittedOffset   The last committed offsets in the timeline.
+     */
+    @Override
+    public void validateOffsetFetch(
+        String memberId,
+        int memberEpoch,
+        long lastCommittedOffset
+    ) throws UnknownMemberIdException, StaleMemberEpochException {
+        // When the member id is null and the member epoch is -1, the request either comes
+        // from the admin client or from a client which does not provide them. In this case,
+        // the fetch request is accepted.
+        if (memberId == null && memberEpoch < 0) return;
+
+        final StreamsGroupMember member = members.get(memberId, lastCommittedOffset);
+        if (member == null) {
+            throw new UnknownMemberIdException(String.format("Member %s is not a member of group %s.",
+                memberId, groupId));
+        }
+        validateMemberEpoch(memberEpoch, member.memberEpoch());
+    }
+
+    /**
+     * Validates the OffsetDelete request.
+     */
+    @Override
+    public void validateOffsetDelete() {}
+
+    /**
+     * Validates the DeleteGroups request.
+     */
+    @Override
+    public void validateDeleteGroup() throws ApiException {
+        if (state() != StreamsGroupState.EMPTY) {
+            throw Errors.NON_EMPTY_GROUP.exception();
+        }
+    }
+
+    @Override
+    public boolean isSubscribedToTopic(String topic) {
+        return false;
+    }
+
+    /**
+     * Populates the list of records with tombstone(s) for deleting the group.
+     *
+     * @param records The list of records.
+     */
+    @Override
+    public void createGroupTombstoneRecords(List<CoordinatorRecord> records) {
+        members().forEach((memberId, member) ->
+            records.add(CoordinatorRecordHelpers.newCurrentAssignmentTombstoneRecord(groupId(), memberId))
+        );
+
+        members().forEach((memberId, member) ->
+            records.add(CoordinatorRecordHelpers.newTargetAssignmentTombstoneRecord(groupId(), memberId))
+        );
+        records.add(CoordinatorRecordHelpers.newTargetAssignmentEpochTombstoneRecord(groupId()));
+
+        members().forEach((memberId, member) ->
+            records.add(CoordinatorRecordHelpers.newMemberSubscriptionTombstoneRecord(groupId(), memberId))
+        );
+
+        records.add(CoordinatorRecordHelpers.newGroupSubscriptionMetadataTombstoneRecord(groupId()));
+        records.add(CoordinatorRecordHelpers.newGroupEpochTombstoneRecord(groupId()));
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return state() == StreamsGroupState.EMPTY;
+    }
+
+    /**
+     * See {@link org.apache.kafka.coordinator.group.OffsetExpirationCondition}
+     *
+     * @return The offset expiration condition for the group or Empty if no such condition exists.
+     */
+    @Override
+    public Optional<OffsetExpirationCondition> offsetExpirationCondition() {
+        return Optional.of(new OffsetExpirationConditionImpl(offsetAndMetadata -> offsetAndMetadata.commitTimestampMs));
+    }
+
+    @Override
+    public boolean isInStates(Set<String> statesFilter, long committedOffset) {
+        return statesFilter.contains(state.get(committedOffset).toLowerCaseString());
+    }
+
+    /**
+     * Throws a StaleMemberEpochException if the received member epoch does not match
+     * the expected member epoch.
+     */
+    private void validateMemberEpoch(
+        int receivedMemberEpoch,
+        int expectedMemberEpoch
+    ) throws StaleMemberEpochException {
+        if (receivedMemberEpoch != expectedMemberEpoch) {
+            throw new StaleMemberEpochException(String.format("The received member epoch %d does not match "
+                + "the expected member epoch %d.", receivedMemberEpoch, expectedMemberEpoch));
+        }
+    }
+
+    /**
+     * Updates the current state of the group.
+     */
+    private void maybeUpdateGroupState() {
+        StreamsGroupState previousState = state.get();
+        StreamsGroupState newState = STABLE;
+        if (members.isEmpty()) {
+            newState = EMPTY;
+        } else if (groupEpoch.get() > targetAssignmentEpoch.get()) {
+            newState = ASSIGNING;
+        } else {
+            for (StreamsGroupMember member : members.values()) {
+                if (!member.isReconciledTo(targetAssignmentEpoch.get())) {
+                    newState = RECONCILING;
+                    break;
+                }
+            }
+        }
+
+        state.set(newState);
+    }
+
+    /**
+     * Compute the subscription type of the consumer group.
+     *
+     * @param subscribedTopicNames      A map of topic names to the count of members subscribed to each topic.
+     *
+     * @return {@link org.apache.kafka.coordinator.group.assignor.SubscriptionType#HOMOGENEOUS} if all members are subscribed to exactly the same topics;
+     *         otherwise, {@link org.apache.kafka.coordinator.group.assignor.SubscriptionType#HETEROGENEOUS}.
+     */
+    public static SubscriptionType subscriptionType(
+        Map<String, Integer> subscribedTopicNames,
+        int numberOfMembers
+    ) {
+        if (subscribedTopicNames.isEmpty()) {
+            return HOMOGENEOUS;
+        }
+
+        for (int subscriberCount : subscribedTopicNames.values()) {
+            if (subscriberCount != numberOfMembers) {
+                return HETEROGENEOUS;
+            }
+        }
+        return HOMOGENEOUS;
+    }
+
+    /**
+     * Updates the tasks epochs based on the old and the new member.
+     *
+     * @param oldMember The old member.
+     * @param newMember The new member.
+     */
+    private void maybeUpdateTaskEpoch(
+        StreamsGroupMember oldMember,
+        StreamsGroupMember newMember
+    ) {
+        maybeRemoveTaskEpoch(oldMember);
+        addTaskEpochs(
+            newMember.assignedActiveTasks(),
+            newMember.assignedStandbyTasks(),
+            newMember.assignedWarmupTasks(),
+            newMember.memberEpoch()
+        );
+        addTaskEpochs(
+            newMember.activeTasksPendingRevocation(),
+            emptyMap(),
+            emptyMap(),
+            newMember.memberEpoch()
+        );
+    }
+
+    /**
+     * Removes the task epochs for the provided member.
+     *
+     * @param oldMember The old member.
+     */
+    private void maybeRemoveTaskEpoch(
+        StreamsGroupMember oldMember
+    ) {
+        if (oldMember != null) {
+            removeActiveTaskEpochs(oldMember.assignedActiveTasks(), oldMember.memberEpoch());
+            removeStandbyTaskEpochs(oldMember.assignedStandbyTasks(), oldMember.memberEpoch());
+            removeWarmupTaskEpochs(oldMember.assignedWarmupTasks(), oldMember.memberEpoch());
+            removeActiveTaskEpochs(oldMember.activeTasksPendingRevocation(), oldMember.memberEpoch());
+        }
+    }
+
+    void removeActiveTaskEpochs(
+        Map<String, Set<Integer>> assignment,
+        int expectedEpoch
+    ) {
+        removeTaskEpochs(assignment, currentActiveTasksEpoch, expectedEpoch);
+    }
+
+    void removeStandbyTaskEpochs(
+        Map<String, Set<Integer>> assignment,
+        int expectedEpoch
+    ) {
+        removeTaskEpochs(assignment, currentStandbyTasksEpoch, expectedEpoch);
+    }
+
+    void removeWarmupTaskEpochs(
+        Map<String, Set<Integer>> assignment,
+        int expectedEpoch
+    ) {
+        removeTaskEpochs(assignment, currentWarmupTasksEpoch, expectedEpoch);
+    }
+
+    /**
+     * Removes the task epochs based on the provided assignment.
+     *
+     * @param assignment    The assignment.
+     * @param expectedEpoch The expected epoch.
+     * @throws IllegalStateException if the epoch does not match the expected one.
+     * package-private for testing.
+     */
+    private void removeTaskEpochs(
+        Map<String, Set<Integer>> assignment,
+        TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentTasksEpoch,
+        int expectedEpoch
+    ) {
+        assignment.forEach((subtopologyId, assignedPartitions) -> {
+            currentTasksEpoch.compute(subtopologyId, (__, partitionsOrNull) -> {
+                if (partitionsOrNull != null) {
+                    assignedPartitions.forEach(partitionId -> {
+                        Integer prevValue = partitionsOrNull.remove(partitionId);
+                        if (prevValue != expectedEpoch) {
+                            throw new IllegalStateException(
+                                String.format("Cannot remove the epoch %d from task %s_%s because the partition is " +
+                                    "still owned at a different epoch %d", expectedEpoch, subtopologyId, partitionId, prevValue));
+                        }
+                    });
+                    if (partitionsOrNull.isEmpty()) {
+                        return null;
+                    } else {
+                        return partitionsOrNull;
+                    }
+                } else {
+                    throw new IllegalStateException(
+                        String.format("Cannot remove the epoch %d from %s because it does not have any epoch",
+                            expectedEpoch, subtopologyId));
+                }
+            });
+        });
+    }
+
+    /**
+     * Adds the partitions epoch based on the provided assignment.
+     *
+     * @param activeTasks   The assigned active tasks.
+     * @param standbyTasks  The assigned standby tasks.
+     * @param warmupTasks   The assigned warmup tasks.
+     * @param epoch         The new epoch.
+     * @throws IllegalStateException if the partition already has an epoch assigned.
+     * package-private for testing.
+     */
+    void addTaskEpochs(
+        Map<String, Set<Integer>> activeTasks,
+        Map<String, Set<Integer>> standbyTasks,
+        Map<String, Set<Integer>> warmupTasks,
+        int epoch
+    ) {
+        addTaskEpochs(activeTasks, epoch, currentActiveTasksEpoch);
+        addTaskEpochs(standbyTasks, epoch, currentStandbyTasksEpoch);
+        addTaskEpochs(warmupTasks, epoch, currentWarmupTasksEpoch);
+    }
+
+    void addTaskEpochs(
+        Map<String, Set<Integer>> tasks,
+        int epoch,
+        TimelineHashMap<String, TimelineHashMap<Integer, Integer>> currentTasksEpoch
+    ) {
+        tasks.forEach((subtopologyId, assignedTaskPartitions) -> {
+            currentTasksEpoch.compute(subtopologyId, (__, partitionsOrNull) -> {
+                if (partitionsOrNull == null) {
+                    partitionsOrNull = new TimelineHashMap<>(snapshotRegistry, assignedTaskPartitions.size());
+                }
+                for (Integer partitionId : assignedTaskPartitions) {
+                    Integer prevValue = partitionsOrNull.put(partitionId, epoch);
+                    if (prevValue != null) {
+                        throw new IllegalStateException(
+                            String.format("Cannot set the epoch of %s-%s to %d because the partition is " +
+                                "still owned at epoch %d", subtopologyId, partitionId, epoch, prevValue));
+                    }
+                }
+                return partitionsOrNull;
+            });
+        });
+    }
+
+    /**
+     * Decrements value by 1; returns null when reaching zero. This helper is
+     * meant to be used with Map#compute.
+     */
+    private static Integer decValue(String key, Integer value) {
+        if (value == null) return null;
+        return value == 1 ? null : value - 1;
+    }
+
+    /**
+     * Increments value by 1; This helper is meant to be used with Map#compute.
+     */
+    private static Integer incValue(String key, Integer value) {
+        return value == null ? 1 : value + 1;
+    }
+
+    /**
+     * Populate the record list with the records needed to create the given Streams group.
+     *
+     * @param records The list to which the new records are added.
+     */
+    public void createStreamsGroupRecords(
+        List<CoordinatorRecord> records
+    ) {
+        members().forEach((__, streamsGroupMember) ->
+            records.add(CoordinatorRecordHelpers.newStreamsGroupMemberRecord(groupId(), streamsGroupMember))
+        );
+
+        records.add(CoordinatorRecordHelpers.newStreamsGroupEpochRecord(groupId(), groupEpoch()));
+
+        members().forEach((streamsGroupMemberId, streamsGroupMember) ->
+            records.add(CoordinatorRecordHelpers.newTargetAssignmentRecord(
+                groupId(),
+                streamsGroupMemberId,
+                targetAssignment(streamsGroupMemberId).activeTasks(),
+                targetAssignment(streamsGroupMemberId).standbyTasks(),
+                targetAssignment(streamsGroupMemberId).warmupTasks()
+            ))
+        );
+
+        records.add(CoordinatorRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
+
+        members().forEach((__, streamsGroupMember) ->
+            records.add(CoordinatorRecordHelpers.newCurrentAssignmentRecord(groupId(), streamsGroupMember))
+        );
+    }
+
+    /**
+     * @return The map of topic id and partition set converted from the list of TopicPartition.
+     */
+    private static Map<Uuid, Set<Integer>> topicPartitionMapFromList(
+        List<TopicPartition> partitions,
+        TopicsImage topicsImage
+    ) {
+        Map<Uuid, Set<Integer>> topicPartitionMap = new HashMap<>();
+        partitions.forEach(topicPartition -> {
+            TopicImage topicImage = topicsImage.getTopic(topicPartition.topic());
+            if (topicImage != null) {
+                topicPartitionMap
+                    .computeIfAbsent(topicImage.id(), __ -> new HashSet<>())
+                    .add(topicPartition.partition());
+            }
+        });
+        return topicPartitionMap;
+    }
+
+    /**
+     * Checks whether the member has any unreleased tasks.
+     *
+     * @param member The member to check.
+     * @return A boolean indicating whether the member has partitions in the target
+     *         assignment that hasn't been revoked by other members.
+     */
+    public boolean waitingOnUnreleasedActiveTasks(StreamsGroupMember member) {
+        if (member.state() == MemberState.UNRELEASED_TASKS) {
+            for (Map.Entry<String, Set<Integer>> entry : targetAssignment().get(member.memberId()).activeTasks().entrySet()) {
+                String subtopologyId = entry.getKey();
+                Set<Integer> assignedActiveTasks = member.assignedActiveTasks().getOrDefault(subtopologyId, Collections.emptySet());
+
+                for (int partition : entry.getValue()) {
+                    if (!assignedActiveTasks.contains(partition) && currentActiveTaskEpoch(subtopologyId, partition) != -1) {
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
new file mode 100644
index 00000000000..0379a58bb2c
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -0,0 +1,704 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.message.ConsumerGroupDescribeResponseData;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.image.TopicImage;
+import org.apache.kafka.image.TopicsImage;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * StreamsGroupMember contains all the information related to a member
+ * within a Streams group. This class is immutable and is fully backed
+ * by records stored in the __consumer_offsets topic.
+ */
+public class StreamsGroupMember {
+
+    /**
+     * A builder that facilitates the creation of a new member or the update of
+     * an existing one.
+     *
+     * Please refer to the javadoc of {{@link StreamsGroupMember}} for the
+     * definition of the fields.
+     */
+    public static class Builder {
+        private final String memberId;
+        private int memberEpoch = 0;
+        private int previousMemberEpoch = -1;
+        private MemberState state = MemberState.STABLE;
+        private String instanceId = null;
+        private String rackId = null;
+        private int rebalanceTimeoutMs = -1;
+        private String clientId = "";
+        private String clientHost = "";
+        private byte[] topologyHash;
+        private String assignor;
+        private String processId;
+        private StreamsGroupMemberMetadataValue.HostInfo hostInfo;
+        private List<StreamsGroupMemberMetadataValue.KeyValue> clientTags;
+        private byte[] userData;
+        private List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs;
+        private Map<String, Set<Integer>> assignedActiveTasks = Collections.emptyMap();
+        private Map<String, Set<Integer>> assignedStandbyTasks = Collections.emptyMap();
+        private Map<String, Set<Integer>> assignedWarmupTasks = Collections.emptyMap();
+        private Map<String, Set<Integer>> activeTasksPendingRevocation = Collections.emptyMap();
+
+        public Builder(String memberId) {
+            this.memberId = Objects.requireNonNull(memberId);
+        }
+
+        public Builder(StreamsGroupMember member) {
+            Objects.requireNonNull(member);
+
+            this.memberId = member.memberId;
+            this.memberEpoch = member.memberEpoch;
+            this.previousMemberEpoch = member.previousMemberEpoch;
+            this.instanceId = member.instanceId;
+            this.rackId = member.rackId;
+            this.rebalanceTimeoutMs = member.rebalanceTimeoutMs;
+            this.clientId = member.clientId;
+            this.clientHost = member.clientHost;
+            this.topologyHash = member.topologyHash;
+            this.assignor = member.assignor;
+            this.processId = member.processId;
+            this.hostInfo = member.hostInfo;
+            this.clientTags = member.clientTags;
+            this.userData = member.userData;
+            this.assignmentConfigs = member.assignmentConfigs;
+            this.state = member.state;
+            this.assignedActiveTasks = member.assignedActiveTasks;
+            this.assignedStandbyTasks = member.assignedStandbyTasks;
+            this.assignedWarmupTasks = member.assignedWarmupTasks;
+            this.activeTasksPendingRevocation = member.activeTasksPendingRevocation;
+        }
+
+        public Builder updateMemberEpoch(int memberEpoch) {
+            int currentMemberEpoch = this.memberEpoch;
+            this.memberEpoch = memberEpoch;
+            this.previousMemberEpoch = currentMemberEpoch;
+            return this;
+        }
+
+        public Builder setMemberEpoch(int memberEpoch) {
+            this.memberEpoch = memberEpoch;
+            return this;
+        }
+
+        public Builder setPreviousMemberEpoch(int previousMemberEpoch) {
+            this.previousMemberEpoch = previousMemberEpoch;
+            return this;
+        }
+
+        public Builder setInstanceId(String instanceId) {
+            this.instanceId = instanceId;
+            return this;
+        }
+
+        public Builder maybeUpdateInstanceId(Optional<String> instanceId) {
+            this.instanceId = instanceId.orElse(this.instanceId);
+            return this;
+        }
+
+        public Builder setRackId(String rackId) {
+            this.rackId = rackId;
+            return this;
+        }
+
+        public Builder maybeUpdateRackId(Optional<String> rackId) {
+            this.rackId = rackId.orElse(this.rackId);
+            return this;
+        }
+
+        public Builder setRebalanceTimeoutMs(int rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+            return this;
+        }
+
+        public Builder maybeUpdateRebalanceTimeoutMs(OptionalInt rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs.orElse(this.rebalanceTimeoutMs);
+            return this;
+        }
+
+        public StreamsGroupMember.Builder maybeUpdateAssignor(Optional<String> assignor) {
+            this.assignor = assignor.orElse(this.assignor);
+            return this;
+        }
+
+        public Builder setClientId(String clientId) {
+            this.clientId = clientId;
+            return this;
+        }
+
+        public Builder setClientHost(String clientHost) {
+            this.clientHost = clientHost;
+            return this;
+        }
+
+        public Builder setState(MemberState state) {
+            this.state = state;
+            return this;
+        }
+
+        public Builder setTopologyHash(byte[] topologyHash) {
+            this.topologyHash = topologyHash;
+            return this;
+        }
+
+        public Builder setAssignor(String assignor) {
+            this.assignor = assignor;
+            return this;
+        }
+
+        public Builder setProcessId(String processId) {
+            this.processId = processId;
+            return this;
+        }
+
+        public Builder setHostInfo(StreamsGroupMemberMetadataValue.HostInfo hostInfo) {
+            this.hostInfo = hostInfo;
+            return this;
+        }
+
+        public Builder setClientTags(List<StreamsGroupMemberMetadataValue.KeyValue> clientTags) {
+            this.clientTags = clientTags;
+            return this;
+        }
+
+        public Builder setUserData(byte[] userData) {
+            this.userData = userData;
+            return this;
+        }
+
+        public Builder setAssignmentConfigs(List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs) {
+            this.assignmentConfigs = assignmentConfigs;
+            return this;
+        }
+
+        public Builder setAssignedActiveTasks(Map<String, Set<Integer>> assignedActiveTasks) {
+            this.assignedActiveTasks = assignedActiveTasks;
+            return this;
+        }
+
+        public Builder setAssignedStandbyTasks(Map<String, Set<Integer>> assignedStandbyTasks) {
+            this.assignedStandbyTasks = assignedStandbyTasks;
+            return this;
+        }
+
+        public Builder setAssignedWarmupTasks(Map<String, Set<Integer>> assignedWarmupTasks) {
+            this.assignedWarmupTasks = assignedWarmupTasks;
+            return this;
+        }
+
+        public Builder setActiveTasksPendingRevocation(Map<String, Set<Integer>> activeTasksPendingRevocation) {
+            this.activeTasksPendingRevocation = activeTasksPendingRevocation;
+            return this;
+        }
+
+        public Builder updateWith(StreamsGroupMemberMetadataValue record) {
+            setInstanceId(record.instanceId());
+            setRackId(record.rackId());
+            setClientId(record.clientId());
+            setClientHost(record.clientHost());
+            setRebalanceTimeoutMs(record.rebalanceTimeoutMs());
+            setTopologyHash(record.topologyHash());
+            setAssignor(record.assignor());
+            setProcessId(record.processId());
+            setHostInfo(record.hostInfo());
+            setClientTags(record.clientTags());
+            setUserData(record.userData());
+            setAssignmentConfigs(record.assignmentConfigs());
+            return this;
+        }
+
+        public Builder updateWith(StreamsGroupCurrentMemberAssignmentValue record) {
+            setMemberEpoch(record.memberEpoch());
+            setPreviousMemberEpoch(record.previousMemberEpoch());
+            setState(MemberState.fromValue(record.state()));
+            setAssignedActiveTasks(assignmentFromTaskIds(record.activeTasks()));
+            setAssignedStandbyTasks(assignmentFromTaskIds(record.standbyTasks()));
+            setAssignedWarmupTasks(assignmentFromTaskIds(record.warmupTasks()));
+            setActiveTasksPendingRevocation(assignmentFromTaskIds(record.activeTasksPendingRevocation()));
+            return this;
+        }
+
+        private Map<String, Set<Integer>> assignmentFromTaskIds(
+            List<StreamsGroupCurrentMemberAssignmentValue.TaskIds> topicPartitionsList
+        ) {
+            return topicPartitionsList.stream().collect(Collectors.toMap(
+                StreamsGroupCurrentMemberAssignmentValue.TaskIds::subtopology,
+                taskIds -> Collections.unmodifiableSet(new HashSet<>(taskIds.partitions()))));
+        }
+
+        public StreamsGroupMember build() {
+            return new StreamsGroupMember(
+                memberId,
+                memberEpoch,
+                previousMemberEpoch,
+                instanceId,
+                rackId,
+                rebalanceTimeoutMs,
+                clientId,
+                clientHost,
+                topologyHash,
+                assignor,
+                processId,
+                hostInfo,
+                clientTags,
+                userData,
+                assignmentConfigs,
+                state,
+                assignedActiveTasks,
+                assignedStandbyTasks,
+                assignedWarmupTasks,
+                activeTasksPendingRevocation
+            );
+        }
+    }
+
+    /**
+     * The member id.
+     */
+    private final String memberId;
+
+    /**
+     * The current member epoch.
+     */
+    private final int memberEpoch;
+
+    /**
+     * The previous member epoch.
+     */
+    private final int previousMemberEpoch;
+
+    /**
+     * The member state.
+     */
+    private final MemberState state;
+
+    /**
+     * The instance id provided by the member.
+     */
+    private final String instanceId;
+
+    /**
+     * The rack id provided by the member.
+     */
+    private final String rackId;
+
+    /**
+     * The rebalance timeout provided by the member.
+     */
+    private final int rebalanceTimeoutMs;
+
+    /**
+     * The client id reported by the member.
+     */
+    private final String clientId;
+
+    /**
+     * The host reported by the member.
+     */
+    private final String clientHost;
+
+    /**
+     * The topology hash
+     */
+    private byte[] topologyHash;
+
+    /**
+     * The assignor
+     */
+    private String assignor;
+
+    /**
+     * The process ID
+     */
+    private String processId;
+
+    /**
+     * The host info
+     */
+    private StreamsGroupMemberMetadataValue.HostInfo hostInfo;
+
+    /**
+     * The client tags
+     */
+    private  List<StreamsGroupMemberMetadataValue.KeyValue> clientTags;
+
+    /**
+     * The user data
+     */
+    private byte[] userData;
+
+    /**
+     * The assignment configs
+     */
+    private  List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs;
+
+    /**
+     * Active tasks assigned to this member.
+     */
+    private final Map<String, Set<Integer>> assignedActiveTasks;
+
+    /**
+     * Standby tasks assigned to this member.
+     */
+    private final Map<String, Set<Integer>> assignedStandbyTasks;
+
+    /**
+     * Warmup tasks assigned to this member.
+     */
+    private final Map<String, Set<Integer>> assignedWarmupTasks;
+
+    /**
+     * Active tasks being revoked by this member.
+     */
+    private final Map<String, Set<Integer>> activeTasksPendingRevocation;
+
+    private StreamsGroupMember(
+        String memberId,
+        int memberEpoch,
+        int previousMemberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        byte[] topologyHash,
+        String assignor,
+        String processId,
+        StreamsGroupMemberMetadataValue.HostInfo hostInfo,
+        List<StreamsGroupMemberMetadataValue.KeyValue> clientTags,
+        byte[] userData,
+        List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs,
+        MemberState state,
+        Map<String, Set<Integer>> assignedActiveTasks,
+        Map<String, Set<Integer>> assignedStandbyTasks,
+        Map<String, Set<Integer>> assignedWarmupTasks,
+        Map<String, Set<Integer>> activeTasksPendingRevocation
+    ) {
+        this.memberId = memberId;
+        this.memberEpoch = memberEpoch;
+        this.previousMemberEpoch = previousMemberEpoch;
+        this.state = state;
+        this.instanceId = instanceId;
+        this.rackId = rackId;
+        this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+        this.clientId = clientId;
+        this.clientHost = clientHost;
+        this.topologyHash = topologyHash;
+        this.assignor = assignor;
+        this.processId = processId;
+        this.hostInfo = hostInfo;
+        this.clientTags = clientTags;
+        this.userData = userData;
+        this.assignmentConfigs = assignmentConfigs;
+        this.assignedActiveTasks = assignedActiveTasks;
+        this.assignedStandbyTasks = assignedStandbyTasks;
+        this.assignedWarmupTasks = assignedWarmupTasks;
+        this.activeTasksPendingRevocation = activeTasksPendingRevocation;
+    }
+
+    /**
+     * @return The member id.
+     */
+    public String memberId() {
+        return memberId;
+    }
+
+    /**
+     * @return The current member epoch.
+     */
+    public int memberEpoch() {
+        return memberEpoch;
+    }
+
+    /**
+     * @return The previous member epoch.
+     */
+    public int previousMemberEpoch() {
+        return previousMemberEpoch;
+    }
+
+    /**
+     * @return The instance id.
+     */
+    public String instanceId() {
+        return instanceId;
+    }
+
+    /**
+     * @return The rack id.
+     */
+    public String rackId() {
+        return rackId;
+    }
+
+    /**
+     * @return The rebalance timeout in millis.
+     */
+    public int rebalanceTimeoutMs() {
+        return rebalanceTimeoutMs;
+    }
+
+    /**
+     * @return The client id.
+     */
+    public String clientId() {
+        return clientId;
+    }
+
+    /**
+     * @return The client host.
+     */
+    public String clientHost() {
+        return clientHost;
+    }
+
+    /**
+     * @return The process ID
+     */
+    public byte[] topologyHash() {
+        return topologyHash;
+    }
+
+    /**
+     * @return The assignor
+     */
+    public Optional<String> assignor() {
+        return Optional.ofNullable(assignor);
+    }
+
+    /**
+     * @return The process ID
+     */
+    public String processId() {
+        return processId;
+    }
+
+    /**
+     * @return The host info
+     */
+    public StreamsGroupMemberMetadataValue.HostInfo hostInfo() {
+        return hostInfo;
+    }
+
+    /**
+     * @return The client tags
+     */
+    public List<StreamsGroupMemberMetadataValue.KeyValue> clientTags() {
+        return clientTags;
+    }
+
+    public byte[] userData() {
+        return userData;
+    }
+
+    /**
+     * @return The assignment configs
+     */
+    public List<StreamsGroupMemberMetadataValue.KeyValue> assignmentConfigs() {
+        return assignmentConfigs;
+    }
+
+    /**
+     * @return The current state.
+     */
+    public MemberState state() {
+        return state;
+    }
+
+    /**
+     * @return True if the member is in the Stable state and at the desired epoch.
+     */
+    public boolean isReconciledTo(int targetAssignmentEpoch) {
+        return state == MemberState.STABLE && memberEpoch == targetAssignmentEpoch;
+    }
+
+    /**
+     * @return The set of assigned active tasks.
+     */
+    public Map<String, Set<Integer>> assignedActiveTasks() {
+        return assignedActiveTasks;
+    }
+
+    /**
+     * @return The set of assigned standby tasks.
+     */
+    public Map<String, Set<Integer>> assignedStandbyTasks() {
+        return assignedStandbyTasks;
+    }
+
+    /**
+     * @return The set of assigned warm-up tasks.
+     */
+    public Map<String, Set<Integer>> assignedWarmupTasks() {
+        return assignedWarmupTasks;
+    }
+
+    /**
+     * @return The set of active tasks awaiting revocation from the member.
+     */
+    public Map<String, Set<Integer>> activeTasksPendingRevocation() {
+        return activeTasksPendingRevocation;
+    }
+
+    private static List<ConsumerGroupDescribeResponseData.TopicPartitions> topicPartitionsFromMap(
+        Map<Uuid, Set<Integer>> partitions,
+        TopicsImage topicsImage
+    ) {
+        List<ConsumerGroupDescribeResponseData.TopicPartitions> topicPartitions = new ArrayList<>();
+        partitions.forEach((topicId, partitionSet) -> {
+            String topicName = lookupTopicNameById(topicId, topicsImage);
+            if (topicName != null) {
+                topicPartitions.add(new ConsumerGroupDescribeResponseData.TopicPartitions()
+                    .setTopicId(topicId)
+                    .setTopicName(topicName)
+                    .setPartitions(new ArrayList<>(partitionSet)));
+            }
+        });
+        return topicPartitions;
+    }
+
+    private static String lookupTopicNameById(
+        Uuid topicId,
+        TopicsImage topicsImage
+    ) {
+        TopicImage topicImage = topicsImage.getTopic(topicId);
+        if (topicImage != null) {
+            return topicImage.name();
+        } else {
+            return null;
+        }
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        StreamsGroupMember that = (StreamsGroupMember) o;
+        return memberEpoch == that.memberEpoch
+            && previousMemberEpoch == that.previousMemberEpoch
+            && rebalanceTimeoutMs == that.rebalanceTimeoutMs
+            && Objects.equals(memberId, that.memberId)
+            && state == that.state
+            && Objects.equals(instanceId, that.instanceId)
+            && Objects.equals(rackId, that.rackId)
+            && Objects.equals(clientId, that.clientId)
+            && Objects.equals(clientHost, that.clientHost)
+            && Objects.deepEquals(topologyHash, that.topologyHash)
+            && Objects.equals(assignor, that.assignor)
+            && Objects.equals(processId, that.processId)
+            && Objects.equals(hostInfo, that.hostInfo)
+            && Objects.equals(clientTags, that.clientTags)
+            && Objects.deepEquals(userData, that.userData)
+            && Objects.equals(assignmentConfigs, that.assignmentConfigs)
+            && Objects.equals(assignedActiveTasks, that.assignedActiveTasks)
+            && Objects.equals(assignedStandbyTasks, that.assignedStandbyTasks)
+            && Objects.equals(assignedWarmupTasks, that.assignedWarmupTasks)
+            && Objects.equals(activeTasksPendingRevocation, that.activeTasksPendingRevocation);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = memberId != null ? memberId.hashCode() : 0;
+        result = 31 * result + memberEpoch;
+        result = 31 * result + previousMemberEpoch;
+        result = 31 * result + Objects.hashCode(state);
+        result = 31 * result + Objects.hashCode(instanceId);
+        result = 31 * result + Objects.hashCode(rackId);
+        result = 31 * result + rebalanceTimeoutMs;
+        result = 31 * result + Objects.hashCode(clientId);
+        result = 31 * result + Objects.hashCode(clientHost);
+        result = 31 * result + Arrays.hashCode(topologyHash);
+        result = 31 * result + Objects.hashCode(assignor);
+        result = 31 * result + Objects.hashCode(processId);
+        result = 31 * result + Objects.hashCode(hostInfo);
+        result = 31 * result + Objects.hashCode(clientTags);
+        result = 31 * result + Arrays.hashCode(userData);
+        result = 31 * result + Objects.hashCode(assignmentConfigs);
+        result = 31 * result + Objects.hashCode(assignedActiveTasks);
+        result = 31 * result + Objects.hashCode(assignedStandbyTasks);
+        result = 31 * result + Objects.hashCode(assignedWarmupTasks);
+        result = 31 * result + Objects.hashCode(activeTasksPendingRevocation);
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "StreamsGroupMember(" +
+            "memberId='" + memberId + '\'' +
+            ", memberEpoch=" + memberEpoch +
+            ", previousMemberEpoch=" + previousMemberEpoch +
+            ", state='" + state + '\'' +
+            ", instanceId='" + instanceId + '\'' +
+            ", rackId='" + rackId + '\'' +
+            ", rebalanceTimeoutMs=" + rebalanceTimeoutMs +
+            ", clientId='" + clientId + '\'' +
+            ", clientHost='" + clientHost + '\'' +
+            ", assignedActiveTasks=" + assignedActiveTasks +
+            ", assignedStandbyTasks=" + assignedStandbyTasks +
+            ", assignedWarmupTasks=" + assignedWarmupTasks +
+            ", activeTasksPendingRevocation=" + activeTasksPendingRevocation +
+            ')';
+    }
+
+    /**
+     * @return True if the two provided members have different assigned active tasks.
+     */
+    public static boolean hasAssignedActiveTasksChanged(
+        StreamsGroupMember member1,
+        StreamsGroupMember member2
+    ) {
+        return !member1.assignedActiveTasks().equals(member2.assignedActiveTasks());
+    }
+
+    /**
+     * @return True if the two provided members have different assigned active tasks.
+     */
+    public static boolean hasAssignedStandbyTasksChanged(
+        StreamsGroupMember member1,
+        StreamsGroupMember member2
+    ) {
+        return !member1.assignedStandbyTasks().equals(member2.assignedStandbyTasks());
+    }
+
+    /**
+     * @return True if the two provided members have different assigned active tasks.
+     */
+    public static boolean hasAssignedWarmupTasksChanged(
+        StreamsGroupMember member1,
+        StreamsGroupMember member2
+    ) {
+        return !member1.assignedWarmupTasks().equals(member2.assignedWarmupTasks());
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java
new file mode 100644
index 00000000000..fb9b1133637
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/SubscribedTopicMetadata.java
@@ -0,0 +1,98 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.assignor.SubscribedTopicDescriber;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * The subscribed topic metadata class is used by the {@link org.apache.kafka.coordinator.group.assignor.PartitionAssignor} to obtain
+ * topic and partition metadata for the topics that the consumer group is subscribed to.
+ */
+public class SubscribedTopicMetadata implements SubscribedTopicDescriber {
+    /**
+     * The topic Ids mapped to their corresponding {@link org.apache.kafka.coordinator.group.consumer.TopicMetadata}
+     * object, which contains topic and partition metadata.
+     */
+    private final Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata;
+
+    public SubscribedTopicMetadata(Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata) {
+        this.topicMetadata = Objects.requireNonNull(topicMetadata);
+    }
+
+    /**
+     * Map of topic Ids to topic metadata.
+     *
+     * @return The map of topic Ids to topic metadata.
+     */
+    public Map<Uuid, org.apache.kafka.coordinator.group.consumer.TopicMetadata> topicMetadata() {
+        return this.topicMetadata;
+    }
+
+    /**
+     * The number of partitions for the given topic Id.
+     *
+     * @param topicId   Uuid corresponding to the topic.
+     * @return The number of partitions corresponding to the given topic Id,
+     *         or -1 if the topic Id does not exist.
+     */
+    @Override
+    public int numPartitions(Uuid topicId) {
+        org.apache.kafka.coordinator.group.consumer.TopicMetadata topic = this.topicMetadata.get(topicId);
+        return topic == null ? -1 : topic.numPartitions();
+    }
+
+    /**
+     * Returns all the available racks associated with the replicas of the given partition.
+     *
+     * @param topicId       Uuid corresponding to the partition's topic.
+     * @param partition     Partition Id within the topic.
+     * @return The set of racks corresponding to the replicas of the topics partition.
+     *         If the topic Id does not exist or no partition rack information is available, an empty set is returned.
+     */
+    @Override
+    public Set<String> racksForPartition(Uuid topicId, int partition) {
+        TopicMetadata topic = this.topicMetadata.get(topicId);
+        return topic == null ? Collections.emptySet() : topic.partitionRacks().getOrDefault(partition, Collections.emptySet());
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        SubscribedTopicMetadata that = (SubscribedTopicMetadata) o;
+        return topicMetadata.equals(that.topicMetadata);
+    }
+
+    @Override
+    public int hashCode() {
+        return topicMetadata.hashCode();
+    }
+
+    @Override
+    public String toString() {
+        return "SubscribedTopicMetadata(" +
+            "topicMetadata=" + topicMetadata +
+            ')';
+    }
+}
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
index 0cbe1ba1e4e..aaaccf7d865 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -32,7 +32,7 @@
       "about": "Currently assigned standby tasks for this streams client." },
     { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned warming up tasks for this streams client." },
-    { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskId",
+    { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskIds",
       "about": "The active tasks that must be revoked by this member." }
   ],
   "commonStructs": [
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
new file mode 100644
index 00000000000..5041aa9cf07
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -0,0 +1,298 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Optional;
+import java.util.OptionalInt;
+
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class StreamsGroupMemberTest {
+
+    @Test
+    public void testNewMember() {
+        String subtopologyId1 = "subtopology-1";
+        String subtopologyId2 = "subtopology-2";
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(5000)
+            .setClientId("client-id")
+            .setClientHost("hostname")
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .build();
+
+        assertEquals("member-id", member.memberId());
+        assertEquals(10, member.memberEpoch());
+        assertEquals(9, member.previousMemberEpoch());
+        assertEquals("instance-id", member.instanceId());
+        assertEquals("rack-id", member.rackId());
+        assertEquals("client-id", member.clientId());
+        assertEquals("hostname", member.clientHost());
+        assertTrue(Arrays.equals("topology-hash".getBytes(), member.topologyHash()));
+        assertEquals("assignor", member.assignor().get());
+        assertEquals("process-id", member.processId());
+        assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
+        assertEquals(
+            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")),
+            member.clientTags()
+        );
+        assertTrue(Arrays.equals("user-data".getBytes(), member.userData()));
+        assertEquals(
+            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")),
+            member.assignmentConfigs()
+        );
+        assertEquals(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)),
+            member.assignedActiveTasks()
+        );
+        assertEquals(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)),
+            member.assignedStandbyTasks()
+        );
+        assertEquals(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)),
+            member.assignedWarmupTasks()
+        );
+        assertEquals(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)),
+            member.activeTasksPendingRevocation()
+        );
+    }
+
+    @Test
+    public void testEquals() {
+        String subtopologyId1 = "subtopology-1";
+        String subtopologyId2 = "subtopology-2";
+
+        StreamsGroupMember member1 = new StreamsGroupMember.Builder("member-id")
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(5000)
+            .setClientId("client-id")
+            .setClientHost("hostname")
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .build();
+
+        StreamsGroupMember member2 = new StreamsGroupMember.Builder("member-id")
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(5000)
+            .setClientId("client-id")
+            .setClientHost("hostname")
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .build();
+
+        StreamsGroupMember member3 = new StreamsGroupMember.Builder("member3-id")
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(5000)
+            .setClientId("client-id")
+            .setClientHost("hostname")
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .build();
+
+        assertEquals(member1, member2);
+        assertNotEquals(member1, member3);
+    }
+
+    @Test
+    public void testUpdateMember() {
+        String subtopologyId1 = "subtopology-1";
+        String subtopologyId2 = "subtopology-2";
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(5000)
+            .setClientId("client-id")
+            .setClientHost("hostname")
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")))
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)))
+            .setAssignedStandbyTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)))
+            .setAssignedWarmupTasks(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 3, 2, 1)))
+            .build();
+
+        // This is a no-op.
+        StreamsGroupMember updatedMember = new StreamsGroupMember.Builder(member)
+            .maybeUpdateRackId(Optional.empty())
+            .maybeUpdateInstanceId(Optional.empty())
+            .maybeUpdateRebalanceTimeoutMs(OptionalInt.empty())
+            .maybeUpdateAssignor(Optional.empty())
+            .build();
+
+        assertEquals(member, updatedMember);
+
+        updatedMember = new StreamsGroupMember.Builder(member)
+            .maybeUpdateRackId(Optional.of("new-rack-id"))
+            .maybeUpdateInstanceId(Optional.of("new-instance-id"))
+            .maybeUpdateRebalanceTimeoutMs(OptionalInt.of(6000))
+            .maybeUpdateAssignor(Optional.of("new-assignor"))
+            .build();
+
+        assertEquals("new-instance-id", updatedMember.instanceId());
+        assertEquals("new-rack-id", updatedMember.rackId());
+        assertEquals(6000, updatedMember.rebalanceTimeoutMs());
+        assertEquals("new-assignor", updatedMember.assignor());
+    }
+
+    @Test
+    public void testUpdateWithStreamsGroupMemberMetadataValue() {
+        StreamsGroupMemberMetadataValue record = new StreamsGroupMemberMetadataValue()
+            .setClientId("client-id")
+            .setClientHost("host-id")
+            .setInstanceId("instance-id")
+            .setRackId("rack-id")
+            .setRebalanceTimeoutMs(1000)
+            .setTopologyHash("topology-hash".getBytes())
+            .setAssignor("assignor")
+            .setProcessId("process-id")
+            .setHostInfo(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090))
+            .setClientTags(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")))
+            .setUserData("user-data".getBytes())
+            .setAssignmentConfigs(Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")));
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
+            .updateWith(record)
+            .build();
+
+        assertEquals("instance-id", member.instanceId());
+        assertEquals("rack-id", member.rackId());
+        assertEquals("client-id", member.clientId());
+        assertEquals("host-id", member.clientHost());
+        assertEquals(1000, member.rebalanceTimeoutMs());
+        assertTrue(Arrays.equals("topology-hash".getBytes(), member.topologyHash()));
+        assertEquals("assignor", member.assignor().get());
+        assertEquals("process-id", member.processId());
+        assertEquals(new StreamsGroupMemberMetadataValue.HostInfo().setHost("host").setPort(9090), member.hostInfo());
+        assertEquals(
+            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("client").setValue("tag")),
+            member.clientTags()
+        );
+        assertTrue(Arrays.equals("user-data".getBytes(), member.userData()));
+        assertEquals(
+            Arrays.asList(new StreamsGroupMemberMetadataValue.KeyValue().setKey("assignment").setValue("config")),
+            member.assignmentConfigs()
+        );
+    }
+
+    @Test
+    public void testUpdateWithConsumerGroupCurrentMemberAssignmentValue() {
+        String subtopologyId1 = "subtopology-1";
+        String subtopologyId2 = "subtopology-2";
+
+        StreamsGroupCurrentMemberAssignmentValue record = new StreamsGroupCurrentMemberAssignmentValue()
+            .setMemberEpoch(10)
+            .setPreviousMemberEpoch(9)
+            .setState((byte) 1)
+            .setActiveTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId1)
+                .setPartitions(Arrays.asList(1, 2, 3)))
+            )
+            .setStandbyTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId2)
+                .setPartitions(Arrays.asList(6, 5, 4)))
+            )
+            .setWarmupTasks(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId1)
+                .setPartitions(Arrays.asList(7, 8, 9)))
+            )
+            .setActiveTasksPendingRevocation(Arrays.asList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subtopologyId2)
+                .setPartitions(Arrays.asList(2, 3, 1)))
+            );
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
+            .updateWith(record)
+            .build();
+
+        assertEquals(10, member.memberEpoch());
+        assertEquals(9, member.previousMemberEpoch());
+        assertEquals(MemberState.STABLE, member.state());
+        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 1, 2, 3)), member.assignedActiveTasks());
+        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 6, 5, 4)), member.assignedStandbyTasks());
+        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)), member.assignedWarmupTasks());
+        assertEquals(mkStreamsAssignment(mkTaskAssignment(subtopologyId2, 2, 3, 1)), member.activeTasksPendingRevocation());
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
new file mode 100644
index 00000000000..d2f2f4fd22d
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -0,0 +1,730 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.GroupNotEmptyException;
+import org.apache.kafka.common.errors.StaleMemberEpochException;
+import org.apache.kafka.common.errors.UnknownMemberIdException;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.coordinator.group.OffsetAndMetadata;
+import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
+import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
+import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.OptionalLong;
+
+import static java.util.Collections.emptyMap;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
+import static org.apache.kafka.server.immutable.ImmutableSet.singleton;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+public class StreamsGroupTest {
+
+    private StreamsGroup createStreamsGroup(String groupId) {
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        return new StreamsGroup(
+            snapshotRegistry,
+            groupId,
+            mock(GroupCoordinatorMetricsShard.class)
+        );
+    }
+
+    @Test
+    public void testGetOrCreateMember() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        // Create a member.
+        member = streamsGroup.getOrMaybeCreateMember("member-id", true);
+        assertEquals("member-id", member.memberId());
+
+        // Add member to the group.
+        streamsGroup.updateMember(member);
+
+        // Get that member back.
+        member = streamsGroup.getOrMaybeCreateMember("member-id", false);
+        assertEquals("member-id", member.memberId());
+
+        assertThrows(UnknownMemberIdException.class, () ->
+            streamsGroup.getOrMaybeCreateMember("does-not-exist", false));
+    }
+
+    @Test
+    public void testUpdateMember() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        member = streamsGroup.getOrMaybeCreateMember("member", true);
+
+        member = new StreamsGroupMember.Builder(member)
+            .setAssignor("client")
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(member, streamsGroup.getOrMaybeCreateMember("member", false));
+    }
+
+    @Test
+    public void testNoStaticMember() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        // Create a new member which is not static
+        streamsGroup.getOrMaybeCreateMember("member", true);
+        assertNull(streamsGroup.staticMember("instance-id"));
+    }
+
+    @Test
+    public void testGetStaticMemberByInstanceId() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        member = streamsGroup.getOrMaybeCreateMember("member", true);
+
+        member = new StreamsGroupMember.Builder(member)
+            .setInstanceId("instance")
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(member, streamsGroup.staticMember("instance"));
+        assertEquals(member, streamsGroup.getOrMaybeCreateMember("member", false));
+        assertEquals(member.memberId(), streamsGroup.staticMemberId("instance"));
+    }
+
+    @Test
+    public void testRemoveMember() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        StreamsGroupMember member = streamsGroup.getOrMaybeCreateMember("member", true);
+        streamsGroup.updateMember(member);
+        assertTrue(streamsGroup.hasMember("member"));
+
+        streamsGroup.removeMember("member");
+        assertFalse(streamsGroup.hasMember("member"));
+
+    }
+
+    @Test
+    public void testRemoveStaticMember() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        StreamsGroupMember member = new StreamsGroupMember.Builder("member")
+            .setInstanceId("instance")
+            .build();
+
+        streamsGroup.updateMember(member);
+        assertTrue(streamsGroup.hasMember("member"));
+
+        streamsGroup.removeMember("member");
+        assertFalse(streamsGroup.hasMember("member"));
+        assertNull(streamsGroup.staticMember("instance"));
+        assertNull(streamsGroup.staticMemberId("instance"));
+    }
+
+    @Test
+    public void testUpdatingMemberUpdatesPartitionEpoch() {
+        String fooSubtopology = "foo-sub";
+        String barSubtopology = "bar-sub";
+        String zarSubtopology = "zar-sub";
+
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        member = new StreamsGroupMember.Builder("member")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(mkStreamsAssignment(
+                mkTaskAssignment(fooSubtopology, 1, 2, 3)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(barSubtopology, 4, 5, 6)))
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 1));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 2));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 3));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 4));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 5));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 6));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 7));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 8));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 9));
+
+        member = new StreamsGroupMember.Builder(member)
+            .setMemberEpoch(11)
+            .setAssignedActiveTasks(mkStreamsAssignment(
+                mkTaskAssignment(barSubtopology, 1, 2, 3)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(zarSubtopology, 4, 5, 6)))
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 1));
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 2));
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(barSubtopology, 3));
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 4));
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 5));
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 6));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 7));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 8));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 9));
+    }
+
+    @Test
+    public void testUpdatingMemberUpdatesPartitionEpochWhenPartitionIsReassignedBeforeBeingRevoked() {
+        String fooSubtopologyId = "foo-sub";
+
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        member = new StreamsGroupMember.Builder("member")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(emptyMap())
+            .setAssignedStandbyTasks(emptyMap())
+            .setAssignedWarmupTasks(emptyMap())
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(fooSubtopologyId, 1)))
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopologyId, 1));
+
+        member = new StreamsGroupMember.Builder(member)
+            .setMemberEpoch(11)
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedStandbyTasks(emptyMap())
+            .setAssignedWarmupTasks(emptyMap())
+            .setActiveTasksPendingRevocation(emptyMap())
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(11, streamsGroup.currentActiveTaskEpoch(fooSubtopologyId, 1));
+    }
+
+    @Test
+    public void testUpdatingMemberUpdatesPartitionEpochWhenPartitionIsNotReleased() {
+        String fooSubtopologyId = "foo-sub";
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedStandbyTasks(emptyMap())
+            .setAssignedWarmupTasks(emptyMap())
+            .build();
+
+        streamsGroup.updateMember(m1);
+
+        StreamsGroupMember m2 = new StreamsGroupMember.Builder("m2")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .setAssignedStandbyTasks(emptyMap())
+            .setAssignedWarmupTasks(emptyMap())
+            .build();
+
+        // m2 should not be able to acquire foo-1 because the partition is
+        // still owned by another member.
+        assertThrows(IllegalStateException.class, () -> streamsGroup.updateMember(m2));
+    }
+
+    @Test
+    public void testRemoveTaskEpochs() {
+        String fooSubtopologyId = "foo-sub";
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        // Removing should fail because there is no epoch set.
+        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
+            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            10
+        ));
+
+        StreamsGroupMember m1 = new StreamsGroupMember.Builder("m1")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)))
+            .build();
+
+        streamsGroup.updateMember(m1);
+
+        // Removing should fail because the expected epoch is incorrect.
+        assertThrows(IllegalStateException.class, () -> streamsGroup.removeActiveTaskEpochs(
+            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            11
+        ));
+    }
+
+    @Test
+    public void testAddPartitionEpochs() {
+        String fooSubtopologyId = "foo-sub";
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        streamsGroup.addTaskEpochs(
+            mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+            emptyMap(),
+            emptyMap(),
+            10
+        );
+
+        // Changing the epoch should fail because the owner of the partition
+        // should remove it first.
+        assertThrows(IllegalStateException.class, () -> streamsGroup.addTaskEpochs(
+                mkStreamsAssignment(mkTaskAssignment(fooSubtopologyId, 1)),
+                emptyMap(),
+                emptyMap(),
+                11
+        ));
+    }
+
+    @Test
+    public void testDeletingMemberRemovesPartitionEpoch() {
+        String fooSubtopology = "foo-sub";
+        String barSubtopology = "bar-sub";
+        String zarSubtopology = "zar-sub";
+
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        StreamsGroupMember member;
+
+        member = new StreamsGroupMember.Builder("member")
+            .setMemberEpoch(10)
+            .setAssignedActiveTasks(mkStreamsAssignment(
+                mkTaskAssignment(fooSubtopology, 1, 2, 3)))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(barSubtopology, 4, 5, 6)))
+            .build();
+
+        streamsGroup.updateMember(member);
+
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 1));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 2));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 3));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 4));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 5));
+        assertEquals(10, streamsGroup.currentActiveTaskEpoch(barSubtopology, 6));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 7));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 8));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 9));
+
+        streamsGroup.removeMember(member.memberId());
+
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 1));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 2));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(barSubtopology, 3));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 4));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 5));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(zarSubtopology, 6));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 7));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 8));
+        assertEquals(-1, streamsGroup.currentActiveTaskEpoch(fooSubtopology, 9));
+    }
+
+    @Test
+    public void testWaitingOnUnreleasedTask() {
+        String fooSubtopology = "foo-sub";
+        String barSubtopology = "bar-sub";
+        String zarSubtopology = "zar-sub";
+        String memberId1 = "m1";
+        String memberId2 = "m2";
+
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        streamsGroup.updateTargetAssignment(memberId1,
+            new Assignment(
+                mkStreamsAssignment(
+                    mkTaskAssignment(fooSubtopology, 1, 2, 3),
+                    mkTaskAssignment(zarSubtopology, 7, 8, 9)
+                ),
+                emptyMap(),
+                emptyMap())
+        );
+
+        StreamsGroupMember member1 = new StreamsGroupMember.Builder(memberId1)
+            .setMemberEpoch(10)
+            .setState(MemberState.UNRELEASED_TASKS)
+            .setAssignedActiveTasks(mkStreamsAssignment(
+                mkTaskAssignment(fooSubtopology, 1, 2, 3)
+            ))
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(barSubtopology, 4, 5, 6)
+            ))
+            .build();
+        streamsGroup.updateMember(member1);
+
+        assertFalse(streamsGroup.waitingOnUnreleasedActiveTasks(member1));
+
+        StreamsGroupMember member2 = new StreamsGroupMember.Builder(memberId2)
+            .setMemberEpoch(10)
+            .setActiveTasksPendingRevocation(mkStreamsAssignment(
+                mkTaskAssignment(zarSubtopology, 7)))
+            .build();
+        streamsGroup.updateMember(member2);
+
+        assertTrue(streamsGroup.waitingOnUnreleasedActiveTasks(member1));
+    }
+
+    @Test
+    public void testGroupState() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+
+        StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
+            .setState(MemberState.STABLE)
+            .setMemberEpoch(1)
+            .setPreviousMemberEpoch(0)
+            .build();
+
+        streamsGroup.updateMember(member1);
+        streamsGroup.setGroupEpoch(1);
+
+        assertEquals(MemberState.STABLE, member1.state());
+        assertEquals(StreamsGroup.StreamsGroupState.ASSIGNING, streamsGroup.state());
+
+        StreamsGroupMember member2 = new StreamsGroupMember.Builder("member2")
+            .setState(MemberState.STABLE)
+            .setMemberEpoch(1)
+            .setPreviousMemberEpoch(0)
+            .build();
+
+        streamsGroup.updateMember(member2);
+        streamsGroup.setGroupEpoch(2);
+
+        assertEquals(MemberState.STABLE, member2.state());
+        assertEquals(StreamsGroup.StreamsGroupState.ASSIGNING, streamsGroup.state());
+
+        streamsGroup.setTargetAssignmentEpoch(2);
+
+        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, streamsGroup.state());
+
+        member1 = new StreamsGroupMember.Builder(member1)
+            .setState(MemberState.STABLE)
+            .setMemberEpoch(2)
+            .setPreviousMemberEpoch(1)
+            .build();
+
+        streamsGroup.updateMember(member1);
+
+        assertEquals(MemberState.STABLE, member1.state());
+        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, streamsGroup.state());
+
+        // Member 2 is not stable so the group stays in reconciling state.
+        member2 = new StreamsGroupMember.Builder(member2)
+            .setState(MemberState.UNREVOKED_TASKS)
+            .setMemberEpoch(2)
+            .setPreviousMemberEpoch(1)
+            .build();
+
+        streamsGroup.updateMember(member2);
+
+        assertEquals(MemberState.UNREVOKED_TASKS, member2.state());
+        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, streamsGroup.state());
+
+        member2 = new StreamsGroupMember.Builder(member2)
+            .setState(MemberState.STABLE)
+            .setMemberEpoch(2)
+            .setPreviousMemberEpoch(1)
+            .build();
+
+        streamsGroup.updateMember(member2);
+
+        assertEquals(MemberState.STABLE, member2.state());
+        assertEquals(StreamsGroup.StreamsGroupState.STABLE, streamsGroup.state());
+
+        streamsGroup.removeMember("member1");
+        streamsGroup.removeMember("member2");
+
+        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+    }
+
+    @Test
+    public void testUpdateInvertedAssignment() {
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        GroupCoordinatorMetricsShard metricsShard = mock(GroupCoordinatorMetricsShard.class);
+        StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, "test-group", metricsShard);
+        String subtopologyId = "foo-sub";
+        String memberId1 = "member1";
+        String memberId2 = "member2";
+
+        // Initial assignment for member1
+        Assignment initialAssignment = new Assignment(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 0)),
+            emptyMap(),
+            emptyMap()
+        );
+        streamsGroup.updateTargetAssignment(memberId1, initialAssignment);
+
+        // Verify that partition 0 is assigned to member1.
+        assertEquals(
+            mkMap(
+                mkEntry(subtopologyId, mkMap(mkEntry(0, memberId1)))
+            ),
+            streamsGroup.invertedTargetActiveTasksAssignment()
+        );
+
+        // New assignment for member1
+        Assignment newAssignment = new Assignment(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 1)),
+            emptyMap(),
+            emptyMap()
+        );
+        streamsGroup.updateTargetAssignment(memberId1, newAssignment);
+
+        // Verify that partition 0 is no longer assigned and partition 1 is assigned to member1
+        assertEquals(
+            mkMap(
+                mkEntry(subtopologyId, mkMap(mkEntry(1, memberId1)))
+            ),
+            streamsGroup.invertedTargetActiveTasksAssignment()
+        );
+
+        // New assignment for member2 to add partition 1
+        Assignment newAssignment2 = new Assignment(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 1)),
+            emptyMap(),
+            emptyMap()
+        );
+        streamsGroup.updateTargetAssignment(memberId2, newAssignment);
+
+        // Verify that partition 1 is assigned to member2
+        assertEquals(
+            mkMap(
+                mkEntry(subtopologyId, mkMap(mkEntry(1, memberId2)))
+            ),
+            streamsGroup.invertedTargetActiveTasksAssignment()
+        );
+
+        // New assignment for member1 to revoke partition 1 and assign partition 0
+        Assignment newAssignment1 = new Assignment(
+            mkStreamsAssignment(mkTaskAssignment(subtopologyId, 0)),
+            emptyMap(),
+            emptyMap()
+        );
+        streamsGroup.updateTargetAssignment(memberId1, newAssignment1);
+
+        // Verify that partition 1 is still assigned to member2 and partition 0 is assigned to member1
+        assertEquals(
+            mkMap(
+                mkEntry(subtopologyId, mkMap(
+                    mkEntry(0, memberId1),
+                    mkEntry(1, memberId2)
+                ))
+            ),
+            streamsGroup.invertedTargetActiveTasksAssignment()
+        );
+
+        // Test remove target assignment for member1
+        streamsGroup.removeTargetAssignment(memberId1);
+
+        // Verify that partition 0 is no longer assigned and partition 1 is still assigned to member2
+        assertEquals(
+            mkMap(
+                mkEntry(subtopologyId, mkMap(mkEntry(1, memberId2)))
+            ),
+            streamsGroup.invertedTargetActiveTasksAssignment()
+        );
+    }
+
+    @Test
+    public void testMetadataRefreshDeadline() {
+        MockTime time = new MockTime();
+        StreamsGroup group = createStreamsGroup("group-foo");
+
+        // Group epoch starts at 0.
+        assertEquals(0, group.groupEpoch());
+
+        // The refresh time deadline should be empty when the group is created or loaded.
+        assertTrue(group.hasMetadataExpired(time.milliseconds()));
+        assertEquals(0L, group.metadataRefreshDeadline().deadlineMs);
+        assertEquals(0, group.metadataRefreshDeadline().epoch);
+
+        // Set the refresh deadline. The metadata remains valid because the deadline
+        // has not past and the group epoch is correct.
+        group.setMetadataRefreshDeadline(time.milliseconds() + 1000, group.groupEpoch());
+        assertFalse(group.hasMetadataExpired(time.milliseconds()));
+        assertEquals(time.milliseconds() + 1000, group.metadataRefreshDeadline().deadlineMs);
+        assertEquals(group.groupEpoch(), group.metadataRefreshDeadline().epoch);
+
+        // Advance past the deadline. The metadata should have expired.
+        time.sleep(1001L);
+        assertTrue(group.hasMetadataExpired(time.milliseconds()));
+
+        // Set the refresh time deadline with a higher group epoch. The metadata is considered
+        // as expired because the group epoch attached to the deadline is higher than the
+        // current group epoch.
+        group.setMetadataRefreshDeadline(time.milliseconds() + 1000, group.groupEpoch() + 1);
+        assertTrue(group.hasMetadataExpired(time.milliseconds()));
+        assertEquals(time.milliseconds() + 1000, group.metadataRefreshDeadline().deadlineMs);
+        assertEquals(group.groupEpoch() + 1, group.metadataRefreshDeadline().epoch);
+
+        // Advance the group epoch.
+        group.setGroupEpoch(group.groupEpoch() + 1);
+
+        // Set the refresh deadline. The metadata remains valid because the deadline
+        // has not past and the group epoch is correct.
+        group.setMetadataRefreshDeadline(time.milliseconds() + 1000, group.groupEpoch());
+        assertFalse(group.hasMetadataExpired(time.milliseconds()));
+        assertEquals(time.milliseconds() + 1000, group.metadataRefreshDeadline().deadlineMs);
+        assertEquals(group.groupEpoch(), group.metadataRefreshDeadline().epoch);
+
+        // Request metadata refresh. The metadata expires immediately.
+        group.requestMetadataRefresh();
+        assertTrue(group.hasMetadataExpired(time.milliseconds()));
+        assertEquals(0L, group.metadataRefreshDeadline().deadlineMs);
+        assertEquals(0, group.metadataRefreshDeadline().epoch);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = {false, true})
+    public void testValidateOffsetCommit(boolean isTransactional) {
+        StreamsGroup group = createStreamsGroup("group-foo");
+
+        // Simulate a call from the admin client without member id and member epoch.
+        // This should pass only if the group is empty.
+        group.validateOffsetCommit("", "", -1, isTransactional);
+
+        // The member does not exist.
+        assertThrows(UnknownMemberIdException.class, () ->
+            group.validateOffsetCommit("member-id", null, 0, isTransactional));
+
+        // Create a member.
+        group.updateMember(new StreamsGroupMember.Builder("member-id").build());
+
+        // A call from the admin client should fail as the group is not empty.
+        assertThrows(UnknownMemberIdException.class, () ->
+            group.validateOffsetCommit("", "", -1, isTransactional));
+
+        // The member epoch is stale.
+        assertThrows(StaleMemberEpochException.class, () ->
+            group.validateOffsetCommit("member-id", "", 10, isTransactional));
+
+        // This should succeed.
+        group.validateOffsetCommit("member-id", "", 0, isTransactional);
+    }
+
+    @Test
+    public void testValidateOffsetFetch() {
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        StreamsGroup group = new StreamsGroup(
+            snapshotRegistry,
+            "group-foo",
+            mock(GroupCoordinatorMetricsShard.class)
+        );
+
+        // Simulate a call from the admin client without member id and member epoch.
+        group.validateOffsetFetch(null, -1, Long.MAX_VALUE);
+
+        // The member does not exist.
+        assertThrows(UnknownMemberIdException.class, () ->
+            group.validateOffsetFetch("member-id", 0, Long.MAX_VALUE));
+
+        // Create a member.
+        snapshotRegistry.getOrCreateSnapshot(0);
+        group.updateMember(new StreamsGroupMember.Builder("member-id").build());
+
+        // The member does not exist at last committed offset 0.
+        assertThrows(UnknownMemberIdException.class, () ->
+            group.validateOffsetFetch("member-id", 0, 0));
+
+        // The member exists but the epoch is stale when the last committed offset is not considered.
+        assertThrows(StaleMemberEpochException.class, () ->
+            group.validateOffsetFetch("member-id", 10, Long.MAX_VALUE));
+
+        // This should succeed.
+        group.validateOffsetFetch("member-id", 0, Long.MAX_VALUE);
+    }
+
+    @Test
+    public void testValidateDeleteGroup() {
+        StreamsGroup streamsGroup = createStreamsGroup("foo");
+
+        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+        assertDoesNotThrow(streamsGroup::validateDeleteGroup);
+
+        StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
+            .setMemberEpoch(1)
+            .setPreviousMemberEpoch(0)
+            .build();
+        streamsGroup.updateMember(member1);
+
+        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, streamsGroup.state());
+        assertThrows(GroupNotEmptyException.class, streamsGroup::validateDeleteGroup);
+
+        streamsGroup.setGroupEpoch(1);
+
+        assertEquals(StreamsGroup.StreamsGroupState.ASSIGNING, streamsGroup.state());
+        assertThrows(GroupNotEmptyException.class, streamsGroup::validateDeleteGroup);
+
+        streamsGroup.setTargetAssignmentEpoch(1);
+
+        assertEquals(StreamsGroup.StreamsGroupState.STABLE, streamsGroup.state());
+        assertThrows(GroupNotEmptyException.class, streamsGroup::validateDeleteGroup);
+    }
+
+    @Test
+    public void testOffsetExpirationCondition() {
+        long currentTimestamp = 30000L;
+        long commitTimestamp = 20000L;
+        long offsetsRetentionMs = 10000L;
+        OffsetAndMetadata offsetAndMetadata = new OffsetAndMetadata(15000L, OptionalInt.empty(), "", commitTimestamp, OptionalLong.empty());
+        StreamsGroup group = new StreamsGroup(new SnapshotRegistry(new LogContext()), "group-id", mock(GroupCoordinatorMetricsShard.class));
+
+        Optional<OffsetExpirationCondition> offsetExpirationCondition = group.offsetExpirationCondition();
+        assertTrue(offsetExpirationCondition.isPresent());
+
+        OffsetExpirationConditionImpl condition = (OffsetExpirationConditionImpl) offsetExpirationCondition.get();
+        assertEquals(commitTimestamp, condition.baseTimestamp().apply(offsetAndMetadata));
+        assertTrue(condition.isOffsetExpired(offsetAndMetadata, currentTimestamp, offsetsRetentionMs));
+    }
+
+    @Test
+    public void testIsInStatesCaseInsensitive() {
+        SnapshotRegistry snapshotRegistry = new SnapshotRegistry(new LogContext());
+        GroupCoordinatorMetricsShard metricsShard = new GroupCoordinatorMetricsShard(
+            snapshotRegistry,
+            emptyMap(),
+            new TopicPartition("__consumer_offsets", 0)
+        );
+        StreamsGroup group = new StreamsGroup(snapshotRegistry, "group-foo", metricsShard);
+        snapshotRegistry.getOrCreateSnapshot(0);
+        assertTrue(group.isInStates(singleton("empty"), 0));
+        assertFalse(group.isInStates(singleton("Empty"), 0));
+
+        group.updateMember(new StreamsGroupMember.Builder("member1")
+            .build());
+        snapshotRegistry.getOrCreateSnapshot(1);
+        assertTrue(group.isInStates(singleton("empty"), 0));
+        assertTrue(group.isInStates(singleton("stable"), 1));
+        assertFalse(group.isInStates(singleton("empty"), 1));
+    }
+}
\ No newline at end of file


(kafka) 23/42: StickyTaskAssignor

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit eeea1ca92059bf14fdeecfb168091efa3a605168
Author: Alieh Saeedi <10...@users.noreply.github.com>
AuthorDate: Fri Aug 30 09:55:34 2024 +0200

    StickyTaskAssignor
    
    Implement the `StickyTaskAssignor` for KIP-1071.
---
 .../coordinator/group/GroupCoordinatorShard.java   |    3 +-
 .../group/streams/TargetAssignmentBuilder.java     |    3 +-
 .../group/streams/TopologyMetadata.java            |    6 +
 .../coordinator/group/taskassignor/GroupSpec.java  |    2 +
 .../group/taskassignor/GroupSpecImpl.java          |   14 +-
 .../group/taskassignor/ProcessState.java           |  144 +++
 .../group/taskassignor/StickyTaskAssignor.java     |  437 +++++++
 .../coordinator/group/taskassignor/TaskId.java     |    4 +
 .../group/taskassignor/TopologyDescriber.java      |    2 +
 .../group/streams/TargetAssignmentBuilderTest.java |    2 +-
 .../group/taskassignor/GroupSpecImplTest.java      |    3 +-
 .../group/taskassignor/MockAssignorTest.java       |   37 +-
 .../group/taskassignor/StickyTaskAssignorTest.java | 1201 ++++++++++++++++++++
 13 files changed, 1844 insertions(+), 14 deletions(-)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index dff55c9b684..cb2833f7029 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -108,6 +108,7 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.coordinator.group.taskassignor.MockAssignor;
+import org.apache.kafka.coordinator.group.taskassignor.StickyTaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -256,7 +257,7 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 .withShareGroupSessionTimeout(config.shareGroupSessionTimeoutMs())
                 .withShareGroupHeartbeatInterval(config.shareGroupHeartbeatIntervalMs())
                // TODO: Do we need separate configs for streams groups?
-                .withStreamsGroupAssignors(Collections.singletonList(new MockAssignor()))
+                .withStreamsGroupAssignors(Collections.singletonList(new StickyTaskAssignor()))
                 .withStreamsGroupMaxSize(config.consumerGroupMaxSize())
                 .withStreamsGroupSessionTimeout(config.consumerGroupSessionTimeoutMs())
                 .withStreamsGroupHeartbeatInterval(config.consumerGroupHeartbeatIntervalMs())
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index 51e07c3418c..a09919e2157 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -284,7 +284,8 @@ public class TargetAssignmentBuilder {
             newGroupAssignment = assignor.assign(
                 new GroupSpecImpl(
                     Collections.unmodifiableMap(memberSpecs),
-                    new ArrayList<>(topology.subtopologies().keySet())
+                    new ArrayList<>(topology.subtopologies().keySet()),
+                    new HashMap<>()
                 ),
                 new TopologyMetadata(subscriptionMetadata, topology)
             );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java
index ebc0f239f7d..c2b253f001c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopologyMetadata.java
@@ -57,6 +57,12 @@ public class TopologyMetadata implements TopologyDescriber {
         return topology;
     }
 
+    @Override
+    public boolean isStateful(String subtopologyId) {
+        //TODO
+        return false;
+    }
+
     /**
      * The number of partitions for the given subtopology ID.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java
index cb9c5f3e398..46b279416f5 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java
@@ -34,4 +34,6 @@ public interface GroupSpec {
      */
     List<String> subtopologies();
 
+    Map<String, String> assignmentConfigs();
+
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java
index e08acaa468e..539ce9203db 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java
@@ -35,14 +35,18 @@ public class GroupSpecImpl implements GroupSpec {
      */
     private final List<String> subtopologies;
 
+    private final Map<String, String> assignmentConfigs;
+
     public GroupSpecImpl(
         Map<String, AssignmentMemberSpec> members,
-        List<String> subtopologies
+        List<String> subtopologies,
+        Map<String, String> assignmentConfigs
     ) {
         Objects.requireNonNull(members);
         Objects.requireNonNull(subtopologies);
         this.members = members;
         this.subtopologies = subtopologies;
+        this.assignmentConfigs = assignmentConfigs;
     }
 
     /**
@@ -58,6 +62,11 @@ public class GroupSpecImpl implements GroupSpec {
         return subtopologies;
     }
 
+    @Override
+    public Map<String, String> assignmentConfigs() {
+        return assignmentConfigs;
+    }
+
     @Override
     public boolean equals(final Object o) {
         if (this == o) {
@@ -68,7 +77,8 @@ public class GroupSpecImpl implements GroupSpec {
         }
         final GroupSpecImpl groupSpec = (GroupSpecImpl) o;
         return Objects.equals(members, groupSpec.members)
-            && Objects.equals(subtopologies, groupSpec.subtopologies);
+            && Objects.equals(subtopologies, groupSpec.subtopologies)
+            && Objects.equals(assignmentConfigs, groupSpec.assignmentConfigs);
     }
 
     @Override
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/ProcessState.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/ProcessState.java
new file mode 100644
index 00000000000..a0c494200f6
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/ProcessState.java
@@ -0,0 +1,144 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static java.util.Collections.unmodifiableSet;
+import static org.apache.kafka.common.utils.Utils.union;
+
+public class ProcessState {
+    private final String processId;
+    // number of members
+    private int capacity;
+    private double load;
+    private final Map<String, Integer> memberToTaskCounts;
+    private final Map<String, Set<TaskId>> assignedActiveTasks;
+    private final Map<String, Set<TaskId>> assignedStandbyTasks;
+
+
+    ProcessState(final String processId) {
+        this.processId = processId;
+        this.capacity = 0;
+        this.load = Double.MAX_VALUE;
+        this.assignedActiveTasks = new HashMap<>();
+        this.assignedStandbyTasks = new HashMap<>();
+        this.memberToTaskCounts = new HashMap<>();
+    }
+
+
+    public String processId() {
+        return processId;
+    }
+
+    public int capacity() {
+        return capacity;
+    }
+
+    public int totalTaskCount() {
+        return assignedStandbyTasks().size() + assignedActiveTasks().size();
+    }
+
+    public double load() {
+        return load;
+    }
+
+    public Map<String, Integer> memberToTaskCounts() {
+        return memberToTaskCounts;
+    }
+
+    public Set<TaskId> assignedActiveTasks() {
+        return assignedActiveTasks.values().stream()
+                .flatMap(Set::stream)
+                .collect(Collectors.toSet());
+    }
+
+    public Map<String, Set<TaskId>> assignedActiveTasksByMember() {
+        return assignedActiveTasks;
+    }
+
+    public Set<TaskId> assignedStandbyTasks() {
+        return assignedStandbyTasks.values().stream()
+                .flatMap(Set::stream)
+                .collect(Collectors.toSet());
+    }
+
+    public Map<String, Set<TaskId>> assignedStandbyTasksByMember() {
+        return assignedStandbyTasks;
+    }
+
+    public void addTask(final String memberId, final TaskId taskId, final boolean isActive) {
+        if (isActive) {
+            assignedActiveTasks.putIfAbsent(memberId, new HashSet<>());
+            assignedActiveTasks.get(memberId).add(taskId);
+        } else {
+            assignedStandbyTasks.putIfAbsent(memberId, new HashSet<>());
+            assignedStandbyTasks.get(memberId).add(taskId);
+        }
+        memberToTaskCounts.put(memberId, memberToTaskCounts.get(memberId) + 1);
+        computeLoad();
+    }
+
+    private void incrementCapacity() {
+        capacity++;
+        computeLoad();
+    }
+    public void computeLoad() {
+        if (capacity <= 0) {
+            this.load = -1;
+        } else {
+            this.load = (double) totalTaskCount() / capacity;
+        }
+    }
+
+    public void addMember(final String member) {
+        this.memberToTaskCounts.put(member, 0);
+        incrementCapacity();
+    }
+
+    public boolean hasCapacity() {
+        return totalTaskCount() < capacity;
+    }
+
+    public int compareTo(final ProcessState other) {
+        int loadCompare = Double.compare(this.load, other.load());
+        if (loadCompare == 0) {
+            return Integer.compare(other.capacity, this.capacity);
+        }
+        return loadCompare;
+    }
+
+    public boolean hasTask(final TaskId taskId) {
+        return assignedActiveTasks().contains(taskId) || assignedStandbyTasks().contains(taskId);    }
+
+
+    Set<TaskId> assignedTasks() {
+        final Set<TaskId> assignedActiveTaskIds = assignedActiveTasks();
+        final Set<TaskId> assignedStandbyTaskIds = assignedStandbyTasks();
+        return unmodifiableSet(
+                union(
+                        () -> new HashSet<>(assignedActiveTaskIds.size() + assignedStandbyTaskIds.size()),
+                        assignedActiveTaskIds,
+                        assignedStandbyTaskIds
+                )
+        );
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignor.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignor.java
new file mode 100644
index 00000000000..db67eb373d9
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignor.java
@@ -0,0 +1,437 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class StickyTaskAssignor implements TaskAssignor {
+
+    public static final String STICKY_ASSIGNOR_NAME = "sticky";
+    private static final Logger log = LoggerFactory.getLogger(StickyTaskAssignor.class);
+
+    // helper data structures:
+    private TaskPairs taskPairs;
+    Map<TaskId, Member> activeTaskToPrevMember;
+    Map<TaskId, Set<Member>> standbyTaskToPrevMember;
+    Map<String, ProcessState> processIdToState;
+
+    int allTasks;
+    int totalCapacity;
+    int tasksPerMember;
+
+    @Override
+    public String name() {
+        return STICKY_ASSIGNOR_NAME;
+    }
+
+    @Override
+    public GroupAssignment assign(final GroupSpec groupSpec, final TopologyDescriber topologyDescriber) throws TaskAssignorException {
+
+        initialize(groupSpec, topologyDescriber);
+
+        //active
+        Set<TaskId> activeTasks = toTaskIds(groupSpec, topologyDescriber, true);
+        assignActive(activeTasks);
+
+        //standby
+        final int numStandbyReplicas =
+                groupSpec.assignmentConfigs().isEmpty() ? 0
+                        : Integer.parseInt(groupSpec.assignmentConfigs().get("numStandbyReplicas"));
+        if (numStandbyReplicas > 0) {
+            Set<TaskId> statefulTasks = toTaskIds(groupSpec, topologyDescriber, false);
+            assignStandby(statefulTasks, numStandbyReplicas);
+        }
+
+        return buildGroupAssignment(groupSpec.members().keySet());
+    }
+
+    private Set<TaskId> toTaskIds(final GroupSpec groupSpec, final TopologyDescriber topologyDescriber, final boolean isActive) {
+        Set<TaskId> ret = new HashSet<>();
+        for (String subtopology : groupSpec.subtopologies()) {
+            if (isActive || topologyDescriber.isStateful(subtopology)) {
+                int numberOfPartitions = topologyDescriber.numPartitions(subtopology);
+                for (int i = 0; i < numberOfPartitions; i++) {
+                    ret.add(new TaskId(subtopology, i));
+                }
+            }
+        }
+        return ret;
+    }
+
+    private void initialize(final GroupSpec groupSpec, final TopologyDescriber topologyDescriber) {
+
+        allTasks = 0;
+        for (String subtopology : groupSpec.subtopologies()) {
+            int numberOfPartitions = topologyDescriber.numPartitions(subtopology);
+            allTasks += numberOfPartitions;
+        }
+        totalCapacity = groupSpec.members().size();
+        tasksPerMember = computeTasksPerMember(allTasks, totalCapacity);
+
+        taskPairs = new TaskPairs(allTasks * (allTasks - 1) / 2);
+
+        processIdToState = new HashMap<>();
+        activeTaskToPrevMember = new HashMap<>();
+        standbyTaskToPrevMember = new HashMap<>();
+        for (Map.Entry<String, AssignmentMemberSpec> memberEntry : groupSpec.members().entrySet()) {
+            final String memberId = memberEntry.getKey();
+            final String processId = memberEntry.getValue().processId();
+            final Member member = new Member(processId, memberId);
+            final AssignmentMemberSpec memberSpec = memberEntry.getValue();
+
+            processIdToState.putIfAbsent(processId, new ProcessState(processId));
+            processIdToState.get(processId).addMember(memberId);
+
+            // prev active tasks
+            for (Map.Entry<String, Set<Integer>> entry : memberSpec.activeTasks().entrySet()) {
+                Set<Integer> partitionNoSet = entry.getValue();
+                for (int partitionNo : partitionNoSet) {
+                    activeTaskToPrevMember.put(new TaskId(entry.getKey(), partitionNo), member);
+                }
+            }
+
+            // prev standby tasks
+            for (Map.Entry<String, Set<Integer>> entry : memberSpec.standbyTasks().entrySet()) {
+                Set<Integer> partitionNoSet = entry.getValue();
+                for (int partitionNo : partitionNoSet) {
+                    TaskId taskId = new TaskId(entry.getKey(), partitionNo);
+                    standbyTaskToPrevMember.putIfAbsent(taskId, new HashSet<>());
+                    standbyTaskToPrevMember.get(taskId).add(member);
+                }
+            }
+        }
+    }
+
+    private GroupAssignment buildGroupAssignment(final Set<String> members) {
+        final Map<String, MemberAssignment> memberAssignments = new HashMap<>();
+        final Map<String, Set<TaskId>> activeTasksAssignments = activeTasksAssignments();
+        final Map<String, Set<TaskId>> standbyTasksAssignments = standbyTasksAssignments();
+
+        for (String memberId : members) {
+            Map<String, Set<Integer>> activeTasks = new HashMap<>();
+            if (activeTasksAssignments.containsKey(memberId)) {
+                activeTasks = toCompactedTaskIds(activeTasksAssignments.get(memberId));
+            }
+            Map<String, Set<Integer>> standByTasks = new HashMap<>();
+
+            if (standbyTasksAssignments.containsKey(memberId)) {
+                standByTasks = toCompactedTaskIds(standbyTasksAssignments.get(memberId));
+            }
+            memberAssignments.put(memberId, new MemberAssignment(activeTasks, standByTasks, new HashMap<>()));
+        }
+
+        return new GroupAssignment(memberAssignments);
+    }
+
+    private Map<String, Set<TaskId>> standbyTasksAssignments() {
+        return processIdToState.entrySet().stream()
+                .flatMap(entry -> entry.getValue().assignedStandbyTasksByMember().entrySet().stream())
+                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (set1, set2) -> {
+                    set1.addAll(set2);
+                    return set1;
+                }));
+    }
+
+    private Map<String, Set<TaskId>> activeTasksAssignments() {
+        return processIdToState.entrySet().stream()
+                .flatMap(entry -> entry.getValue().assignedActiveTasksByMember().entrySet().stream())
+                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (set1, set2) -> {
+                    set1.addAll(set2);
+                    return set1;
+                }));
+    }
+
+    private Map<String, Set<Integer>> toCompactedTaskIds(final Set<TaskId> taskIds) {
+        Map<String, Set<Integer>> ret = new HashMap<>();
+        for (TaskId taskId : taskIds) {
+            ret.putIfAbsent(taskId.subtopologyId(), new HashSet<>());
+            ret.get(taskId.subtopologyId()).add(taskId.partition());
+        }
+        return ret;
+    }
+
+    private void assignActive(final Set<TaskId> activeTasks) {
+
+        // 1. re-assigning existing active tasks to clients that previously had the same active tasks
+        for (Iterator<TaskId> it = activeTasks.iterator(); it.hasNext();) {
+            final TaskId task = it.next();
+            final Member prevMember = activeTaskToPrevMember.get(task);
+            if (prevMember != null && (hasUnfulfilledQuota(prevMember))) {
+                processIdToState.get(prevMember.processId).addTask(prevMember.memberId, task, true);
+                updateHelpers(prevMember, task, true);
+                it.remove();
+            }
+        }
+
+        // 2. re-assigning tasks to clients that previously have seen the same task (as standby task)
+        for (Iterator<TaskId> it = activeTasks.iterator(); it.hasNext();) {
+            final TaskId task = it.next();
+            final Set<Member> prevMembers = standbyTaskToPrevMember.get(task);
+            if (prevMembers != null && !prevMembers.isEmpty()) {
+                final Member prevMember = findMemberWithLeastLoad(prevMembers, task, true);
+                if (prevMember != null && hasUnfulfilledQuota(prevMember)) {
+                    processIdToState.get(prevMember.processId).addTask(prevMember.memberId, task, true);
+                    updateHelpers(prevMember, task, true);
+                    it.remove();
+                }
+            }
+        }
+
+        // 3. assign any remaining unassigned tasks
+        for (Iterator<TaskId> it = activeTasks.iterator(); it.hasNext();) {
+            final TaskId task = it.next();
+            final Member member = findMemberWithLeastLoad(task);
+            if (member != null) {
+                processIdToState.get(member.processId).addTask(member.memberId, task, true);
+                it.remove();
+                updateHelpers(member, task, true);
+            }
+        }
+    }
+
+    private void maybeUpdateTasksPerMember(final int activeTasksNo) {
+        if (activeTasksNo == tasksPerMember) {
+            totalCapacity--;
+            allTasks -= activeTasksNo;
+            tasksPerMember = computeTasksPerMember(allTasks, totalCapacity);
+        }
+    }
+
+    private Member findMemberWithLeastLoad(final Set<Member> members, TaskId taskId, final boolean returnSameMember) {
+        Set<Member> rightPairs = members.stream()
+                .filter(member  -> taskPairs.hasNewPair(taskId, processIdToState.get(member.processId).assignedTasks()))
+                .collect(Collectors.toSet());
+        if (rightPairs.isEmpty()) {
+            rightPairs = members;
+        }
+        Optional<ProcessState> processWithLeastLoad = rightPairs.stream()
+                .map(member  -> processIdToState.get(member.processId))
+                .min(Comparator.comparingDouble(ProcessState::load));
+
+        assert processWithLeastLoad.isPresent();
+        // if the same exact former member is needed
+        if (returnSameMember) {
+            return standbyTaskToPrevMember.get(taskId).stream()
+                    .filter(standby -> standby.processId.equals(processWithLeastLoad.get().processId()))
+                    .findFirst()
+                    .orElseGet(() -> memberWithLeastLoad(processWithLeastLoad.get()));
+        }
+        return memberWithLeastLoad(processWithLeastLoad.get());
+    }
+
+    private Member findMemberWithLeastLoad(final TaskId taskId) {
+        Set<Member> allMembers = processIdToState.entrySet().stream()
+                .flatMap(entry -> entry.getValue().memberToTaskCounts().keySet().stream()
+                        .map(memberId -> new Member(entry.getKey(), memberId)))
+                .collect(Collectors.toSet());
+        return findMemberWithLeastLoad(allMembers, taskId, false);
+    }
+
+    private Member findMemberWithLeastLoad(final TaskId taskId, final Set<String> processes) {
+        Set<Member> allMembers = processes.stream()
+                .flatMap(processId -> processIdToState.get(processId).memberToTaskCounts().keySet().stream()
+                        .map(memberId -> new Member(processId, memberId)))
+                .collect(Collectors.toSet());
+        return findMemberWithLeastLoad(allMembers, taskId, false);
+    }
+
+    private Member memberWithLeastLoad(final ProcessState processWithLeastLoad) {
+        Optional<String> memberWithLeastLoad = processWithLeastLoad.memberToTaskCounts().entrySet().stream()
+                .min(Map.Entry.comparingByValue())
+                .map(Map.Entry::getKey);
+        return memberWithLeastLoad.map(memberId -> new Member(processWithLeastLoad.processId(), memberId)).orElse(null);
+    }
+
+    private boolean hasUnfulfilledQuota(final Member member) {
+        return processIdToState.get(member.processId).memberToTaskCounts().get(member.memberId) < tasksPerMember;
+    }
+
+    private void assignStandby(final Set<TaskId> standbyTasks, final int numStandbyReplicas) {
+        for (TaskId task : standbyTasks) {
+            for (int i = 0; i < numStandbyReplicas; i++) {
+                final Set<String> availableProcesses = findAllowedProcesses(task);
+                if (availableProcesses.isEmpty()) {
+                    log.warn("Unable to assign " + (numStandbyReplicas - i) +
+                            " of " + numStandbyReplicas + " standby tasks for task [" + task + "]. " +
+                            "There is not enough available capacity. You should " +
+                            "increase the number of threads and/or application instances " +
+                            "to maintain the requested number of standby replicas.");
+                    break;
+                }
+                Member standby = null;
+
+                // prev active task
+                Member prevMember = activeTaskToPrevMember.get(task);
+                if (prevMember != null && availableProcesses.contains(prevMember.processId) && isLoadBalanced(prevMember.processId)
+                        && taskPairs.hasNewPair(task, processIdToState.get(prevMember.processId).assignedTasks())) {
+                    standby = prevMember;
+                }
+
+                // prev standby tasks
+                if (standby == null) {
+                    final Set<Member> prevMembers = standbyTaskToPrevMember.get(task);
+                    if (prevMembers != null && !prevMembers.isEmpty()) {
+                        prevMembers.removeIf(member  -> !availableProcesses.contains(member.processId));
+                        prevMember = findMemberWithLeastLoad(prevMembers, task, true);
+                        if (prevMember != null && isLoadBalanced(prevMember.processId)) {
+                            standby = prevMember;
+                        }
+                    }
+                }
+
+                // others
+                if (standby == null) {
+                    standby = findMemberWithLeastLoad(task, availableProcesses);
+                }
+                processIdToState.get(standby.processId).addTask(standby.memberId, task, false);
+                updateHelpers(standby, task, false);
+            }
+
+        }
+    }
+
+    private boolean isLoadBalanced(final String processId) {
+        final ProcessState process = processIdToState.get(processId);
+        return process.hasCapacity() || isLeastLoadedProcess(process.load());
+    }
+
+    private boolean isLeastLoadedProcess(final double load) {
+        return processIdToState.values().stream()
+                .allMatch(process -> process.load() >= load);
+    }
+
+    private Set<String> findAllowedProcesses(final TaskId taskId) {
+        return processIdToState.values().stream()
+                .filter(process -> !process.hasTask(taskId))
+                .map(ProcessState::processId)
+                .collect(Collectors.toSet());
+    }
+
+    private void updateHelpers(final Member member, final TaskId taskId, final boolean isActive) {
+        // add all pair combinations: update taskPairs
+        taskPairs.addPairs(taskId, processIdToState.get(member.processId).assignedTasks());
+
+        if (isActive) {
+            // update task per process
+            maybeUpdateTasksPerMember(processIdToState.get(member.processId).assignedActiveTasks().size());
+        }
+    }
+
+    private static int computeTasksPerMember(final int numberOfTasks, final int numberOfMembers) {
+        if (numberOfMembers == 0) {
+            return 0;
+        }
+        int tasksPerMember = numberOfTasks / numberOfMembers;
+        if (numberOfTasks % numberOfMembers > 0) {
+            tasksPerMember++;
+        }
+        return tasksPerMember;
+    }
+
+    private static class TaskPairs {
+        private final Set<Pair> pairs;
+        private final int maxPairs;
+
+        TaskPairs(final int maxPairs) {
+            this.maxPairs = maxPairs;
+            this.pairs = new HashSet<>(maxPairs);
+        }
+
+        boolean hasNewPair(final TaskId task1,
+                           final Set<TaskId> taskIds) {
+            if (pairs.size() == maxPairs) {
+                return false;
+            }
+            if (taskIds.size() == 0) {
+                return true;
+            }
+            for (final TaskId taskId : taskIds) {
+                if (!pairs.contains(pair(task1, taskId))) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        void addPairs(final TaskId taskId, final Set<TaskId> assigned) {
+            for (final TaskId id : assigned) {
+                if (!id.equals(taskId))
+                    pairs.add(pair(id, taskId));
+            }
+        }
+
+        Pair pair(final TaskId task1, final TaskId task2) {
+            if (task1.compareTo(task2) < 0) {
+                return new Pair(task1, task2);
+            }
+            return new Pair(task2, task1);
+        }
+
+
+        private static class Pair {
+            private final TaskId task1;
+            private final TaskId task2;
+
+            Pair(final TaskId task1, final TaskId task2) {
+                this.task1 = task1;
+                this.task2 = task2;
+            }
+
+            @Override
+            public boolean equals(final Object o) {
+                if (this == o) {
+                    return true;
+                }
+                if (o == null || getClass() != o.getClass()) {
+                    return false;
+                }
+                final Pair pair = (Pair) o;
+                return Objects.equals(task1, pair.task1) &&
+                        Objects.equals(task2, pair.task2);
+            }
+
+            @Override
+            public int hashCode() {
+                return Objects.hash(task1, task2);
+            }
+        }
+    }
+
+    static class Member {
+        private final String processId;
+        private final String memberId;
+
+        public Member(final String processId, final String memberId) {
+            this.processId = processId;
+            this.memberId = memberId;
+        }
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
index 3b828a60413..885858f700d 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
@@ -63,4 +63,8 @@ public final class TaskId {
             ", partition=" + partition +
             '}';
     }
+
+    public int compareTo(final TaskId other) {
+        return this.hashCode() - other.hashCode();
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java
index f2a28e2cc10..8b3d5bdec26 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java
@@ -34,4 +34,6 @@ public interface TopologyDescriber {
      */
     int numPartitions(String subtopologyId);
 
+    boolean isStateful(String subtopologyId);
+
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index d97832eb969..c6b135eeebf 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -211,7 +211,7 @@ public class TargetAssignmentBuilderTest {
             Map<String, Map<Integer, String>> invertedTargetAssignment = TaskAssignmentTestUtil.invertedTargetAssignment(memberSpecs);
 
             // Prepare the expected assignment spec.
-            GroupSpecImpl groupSpec = new GroupSpecImpl(memberSpecs, new ArrayList<>(topology.subtopologies().keySet()));
+            GroupSpecImpl groupSpec = new GroupSpecImpl(memberSpecs, new ArrayList<>(topology.subtopologies().keySet()), new HashMap<>());
 
             // We use `any` here to always return an assignment but use `verify` later on
             // to ensure that the input was correct.
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
index 6e34368a155..bad6b8e1c1c 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
@@ -55,7 +55,8 @@ public class GroupSpecImplTest {
 
         groupSpec = new GroupSpecImpl(
             members,
-            subtopologies
+            subtopologies,
+            new HashMap<>()
         );
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
index 457bbdb524d..a63b2e7c7ca 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
@@ -43,9 +44,10 @@ public class MockAssignorTest {
         final GroupAssignment result = assignor.assign(
             new GroupSpecImpl(
                 Collections.emptyMap(),
-                Collections.emptyList()
+                Collections.emptyList(),
+                new HashMap<>()
             ),
-            x -> 5
+            new TopologyDescriberImpl(5)
         );
 
         assertEquals(0, result.members().size());
@@ -69,9 +71,10 @@ public class MockAssignorTest {
         final GroupAssignment result = assignor.assign(
             new GroupSpecImpl(
                 Collections.singletonMap("test_member", memberSpec),
-                Collections.singletonList("test-subtopology")
+                Collections.singletonList("test-subtopology"),
+                new HashMap<>()
             ),
-            x -> 4
+            new TopologyDescriberImpl(4)
         );
 
         assertEquals(1, result.members().size());
@@ -111,9 +114,10 @@ public class MockAssignorTest {
         final GroupAssignment result = assignor.assign(
             new GroupSpecImpl(
                 mkMap(mkEntry("test_member1", memberSpec1), mkEntry("test_member2", memberSpec2)),
-                Arrays.asList("test-subtopology1", "test-subtopology2")
+                Arrays.asList("test-subtopology1", "test-subtopology2"),
+                new HashMap<>()
             ),
-            x -> 4
+            new TopologyDescriberImpl(4)
         );
 
         final Map<String, Set<Integer>> expected1 = mkMap(
@@ -167,9 +171,10 @@ public class MockAssignorTest {
         final GroupAssignment result = assignor.assign(
             new GroupSpecImpl(
                 mkMap(mkEntry("test_member1", memberSpec1), mkEntry("test_member2", memberSpec2)),
-                Arrays.asList("test-subtopology1", "test-subtopology2")
+                Arrays.asList("test-subtopology1", "test-subtopology2"),
+                new HashMap<>()
             ),
-            x -> 4
+            new TopologyDescriberImpl(4)
         );
 
         assertEquals(2, result.members().size());
@@ -187,4 +192,20 @@ public class MockAssignorTest {
         ), testMember2.activeTasks());
     }
 
+    static class TopologyDescriberImpl implements TopologyDescriber {
+        final int numPartitions;
+
+        TopologyDescriberImpl(int numPartitions) {
+            this.numPartitions = numPartitions;
+        }
+        @Override
+        public int numPartitions(String subtopologyId) {
+            return numPartitions;
+        }
+        @Override
+        public boolean isStateful(String subtopologyId) {
+            return false;
+        }
+    }
+
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java
new file mode 100644
index 00000000000..6455fb5cd68
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java
@@ -0,0 +1,1201 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static java.util.Arrays.asList;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class StickyTaskAssignorTest {
+    private final StickyTaskAssignor assignor = new StickyTaskAssignor();
+
+
+    @Test
+    public void shouldAssignOneActiveTaskToEachProcessWhenTaskCountSameAsProcessCount() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(
+                        mkMap(mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3)),
+                        Collections.singletonList("test-subtopology"),
+                        new HashMap<>()
+                ),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(3, result.members().size());
+        Set<Integer> actualActiveTasks = new HashSet<>();
+        for (int i = 0; i < 3; i++) {
+            final MemberAssignment testMember = result.members().get("member" + (i + 1));
+            assertNotNull(testMember);
+            assertEquals(1, testMember.activeTasks().size());
+            actualActiveTasks.addAll(testMember.activeTasks().get("test-subtopology"));
+        }
+        assertEquals(mkSet(0, 1, 2), actualActiveTasks);
+    }
+
+    @Test
+    public void shouldAssignTopicGroupIdEvenlyAcrossClientsWithNoStandByTasks() {
+
+        final AssignmentMemberSpec memberSpec11 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec12 = createAssignmentMemberSpec("process1");
+
+        final AssignmentMemberSpec memberSpec21 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec22 = createAssignmentMemberSpec("process2");
+
+        final AssignmentMemberSpec memberSpec31 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec32 = createAssignmentMemberSpec("process3");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(mkEntry("member1_1", memberSpec11), mkEntry("member1_2", memberSpec12),
+                mkEntry("member2_1", memberSpec21), mkEntry("member2_2", memberSpec22),
+                mkEntry("member3_1", memberSpec31), mkEntry("member3_2", memberSpec32));
+
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Arrays.asList("test-subtopology1", "test-subtopology2"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(1, getAllActiveTaskCount(result, "member1_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member1_2"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2_2"));
+        assertEquals(1, getAllActiveTaskCount(result, "member3_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member3_2"));
+
+        assertEquals(mkMap(mkEntry("test-subtopology1", mkSet(0, 1, 2)), mkEntry("test-subtopology2", mkSet(0, 1, 2))),
+                mergeAllActiveTasks(result, "member1_1", "member1_2", "member2_1", "member2_2", "member3_1", "member3_2"));
+    }
+
+    @Test
+    public void shouldAssignTopicGroupIdEvenlyAcrossClientsWithStandByTasks() {
+        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology1", mkSet(0, 1, 2)), mkEntry("test-subtopology2", mkSet(0, 1, 2)));
+        final AssignmentMemberSpec memberSpec11 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec12 = createAssignmentMemberSpec("process1");
+
+        final AssignmentMemberSpec memberSpec21 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec22 = createAssignmentMemberSpec("process2");
+
+        final AssignmentMemberSpec memberSpec31 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec32 = createAssignmentMemberSpec("process3");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(mkEntry("member1_1", memberSpec11), mkEntry("member1_2", memberSpec12),
+                mkEntry("member2_1", memberSpec21), mkEntry("member2_2", memberSpec22),
+                mkEntry("member3_1", memberSpec31), mkEntry("member3_2", memberSpec32));
+
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Arrays.asList("test-subtopology1", "test-subtopology2"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(3, true)
+        );
+
+        // active tasks
+        assertEquals(1, getAllActiveTaskCount(result, "member1_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member1_2"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2_2"));
+        assertEquals(1, getAllActiveTaskCount(result, "member3_1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member3_2"));
+        assertEquals(tasks,
+                mergeAllActiveTasks(result, "member1_1", "member1_2", "member2_1", "member2_2", "member3_1", "member3_2"));
+    }
+
+    @Test
+    public void shouldNotMigrateActiveTaskToOtherProcess() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
+        AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        Map<String, AssignmentMemberSpec> members = mkMap(mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertTrue(testMember1.activeTasks().get("test-subtopology").contains(0));
+
+        MemberAssignment testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertTrue(testMember2.activeTasks().get("test-subtopology").contains(1));
+
+
+        assertEquals(3,
+                testMember1.activeTasks().get("test-subtopology").size() + testMember2.activeTasks().get("test-subtopology").size());
+
+
+        // flip the previous active tasks assignment around.
+        memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
+        members = mkMap(mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertTrue(testMember2.activeTasks().get("test-subtopology").contains(1));
+
+        MemberAssignment testMember3 = result.members().get("member3");
+        assertNotNull(testMember3);
+        assertTrue(testMember3.activeTasks().get("test-subtopology").contains(2));
+
+
+        assertEquals(3,
+                testMember2.activeTasks().get("test-subtopology").size() + testMember3.activeTasks().get("test-subtopology").size());
+    }
+
+    @Test
+    public void shouldMigrateActiveTasksToNewProcessWithoutChangingAllAssignments() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertTrue(testMember1.activeTasks().get("test-subtopology").contains(0) || testMember1.activeTasks().get("test-subtopology").contains(2));
+
+        MemberAssignment testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertTrue(testMember2.activeTasks().get("test-subtopology").contains(1));
+
+        MemberAssignment testMember3 = result.members().get("member3");
+        assertNotNull(testMember3);
+        assertTrue(testMember3.activeTasks().get("test-subtopology").contains(2) || testMember3.activeTasks().get("test-subtopology").contains(0));
+
+
+        assertEquals(3,
+                testMember1.activeTasks().get("test-subtopology").size() +
+                        testMember2.activeTasks().get("test-subtopology").size() +
+                        testMember3.activeTasks().get("test-subtopology").size());
+    }
+
+    @Test
+    public void shouldAssignBasedOnCapacity() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+
+        final AssignmentMemberSpec memberSpec21 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec22 = createAssignmentMemberSpec("process2");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2_1", memberSpec21), mkEntry("member2_2", memberSpec22));
+
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertEquals(1, testMember1.activeTasks().get("test-subtopology").size());
+
+        MemberAssignment testMember21 = result.members().get("member2_1");
+        assertNotNull(testMember21);
+        assertEquals(1, testMember21.activeTasks().get("test-subtopology").size());
+
+        MemberAssignment testMember22 = result.members().get("member2_2");
+        assertNotNull(testMember22);
+        assertEquals(1, testMember22.activeTasks().get("test-subtopology").size());
+    }
+
+    @Test
+    public void shouldAssignTasksEvenlyWithUnequalTopicGroupSizes() {
+        final Map<String, Set<Integer>> activeTasks = mkMap(
+                mkEntry("test-subtopology1", mkSet(0, 1, 2, 3, 4, 5)),
+                mkEntry("test-subtopology2", mkSet(0)));
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", activeTasks, Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Arrays.asList("test-subtopology1", "test-subtopology2"), new HashMap<>()),
+                new TopologyDescriberImpl2()
+        );
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        final Set<Integer> member1Topology1 = testMember1.activeTasks().get("test-subtopology1");
+        final Set<Integer> member1Topology2 = testMember1.activeTasks().getOrDefault("test-subtopology2", new HashSet<>());
+        assertEquals(4, member1Topology1.size() + member1Topology2.size());
+
+        MemberAssignment testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        final Set<Integer> member2Topology1 = testMember2.activeTasks().get("test-subtopology1");
+        final Set<Integer> member2Topology2 = testMember2.activeTasks().getOrDefault("test-subtopology2", new HashSet<>());
+        assertEquals(3, member2Topology1.size() + member2Topology2.size());
+
+
+        assertEquals(activeTasks, mkMap(
+                mkEntry("test-subtopology1", Stream.concat(member1Topology1.stream(), member2Topology1.stream()).collect(Collectors.toSet())),
+                mkEntry("test-subtopology2", Stream.concat(member1Topology2.stream(), member2Topology2.stream()).collect(Collectors.toSet()))));
+    }
+
+    @Test
+    public void shouldKeepActiveTaskStickinessWhenMoreClientThanActiveTasks() {
+        AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
+        AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
+        AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+        AssignmentMemberSpec memberSpec5 = createAssignmentMemberSpec("process5");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2),
+                mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4), mkEntry("member5", memberSpec5));
+
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertEquals(1, testMember1.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(0), testMember1.activeTasks().get("test-subtopology"));
+
+
+        MemberAssignment testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertEquals(1, testMember2.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(2), testMember2.activeTasks().get("test-subtopology"));
+
+
+        MemberAssignment testMember3 = result.members().get("member3");
+        assertNotNull(testMember3);
+        assertEquals(1, testMember3.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(1), testMember3.activeTasks().get("test-subtopology"));
+
+        MemberAssignment testMember4 = result.members().get("member4");
+        assertNotNull(testMember4);
+        assertNull(testMember4.activeTasks().get("test-subtopology"));
+
+        MemberAssignment testMember5 = result.members().get("member5");
+        assertNotNull(testMember5);
+        assertNull(testMember5.activeTasks().get("test-subtopology"));
+
+
+        // change up the assignment and make sure it is still sticky
+        memberSpec1 = createAssignmentMemberSpec("process1");
+        memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
+        memberSpec3 = createAssignmentMemberSpec("process3");
+        memberSpec4 = createAssignmentMemberSpec("process4", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
+        memberSpec5 = createAssignmentMemberSpec("process5", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+
+
+        members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2),
+                mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4), mkEntry("member5", memberSpec5));
+        result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertNull(testMember1.activeTasks().get("test-subtopology"));
+
+
+        testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertEquals(1, testMember2.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(0), testMember2.activeTasks().get("test-subtopology"));
+
+
+        testMember3 = result.members().get("member3");
+        assertNotNull(testMember3);
+        assertNull(testMember3.activeTasks().get("test-subtopology"));
+
+        testMember4 = result.members().get("member4");
+        assertNotNull(testMember4);
+        assertEquals(1, testMember4.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(2), testMember4.activeTasks().get("test-subtopology"));
+
+        testMember5 = result.members().get("member5");
+        assertNotNull(testMember5);
+        assertEquals(1, testMember5.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(1), testMember5.activeTasks().get("test-subtopology"));
+    }
+
+    @Test
+    public void shouldAssignTasksToClientWithPreviousStandbyTasks() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", Collections.singleton(2))));
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", Collections.singleton(1))));
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", Collections.singleton(0))));
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertEquals(1, testMember1.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(2), testMember1.activeTasks().get("test-subtopology"));
+
+
+        MemberAssignment testMember2 = result.members().get("member2");
+        assertNotNull(testMember2);
+        assertEquals(1, testMember2.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(1), testMember2.activeTasks().get("test-subtopology"));
+
+
+        MemberAssignment testMember3 = result.members().get("member3");
+        assertNotNull(testMember3);
+        assertEquals(1, testMember3.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(0), testMember3.activeTasks().get("test-subtopology"));
+    }
+
+    @Test
+    public void shouldAssignBasedOnCapacityWhenMultipleClientHaveStandbyTasks() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
+                mkMap(mkEntry("test-subtopology", Collections.singleton(0))),
+                        mkMap(mkEntry("test-subtopology", Collections.singleton(1))));
+        final AssignmentMemberSpec memberSpec21 = createAssignmentMemberSpec("process2",
+                mkMap(mkEntry("test-subtopology", Collections.singleton(2))),
+                mkMap(mkEntry("test-subtopology", Collections.singleton(1))));
+        final AssignmentMemberSpec memberSpec22 = createAssignmentMemberSpec("process2",
+                Collections.emptyMap(), Collections.emptyMap());
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1),
+                mkEntry("member2_1", memberSpec21), mkEntry("member2_2", memberSpec22));
+
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+
+        MemberAssignment testMember1 = result.members().get("member1");
+        assertNotNull(testMember1);
+        assertEquals(1, testMember1.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(0), testMember1.activeTasks().get("test-subtopology"));
+
+        MemberAssignment testMember21 = result.members().get("member2_1");
+        assertNotNull(testMember21);
+        assertEquals(1, testMember21.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(2), testMember21.activeTasks().get("test-subtopology"));
+
+        MemberAssignment testMember22 = result.members().get("member2_2");
+        assertNotNull(testMember22);
+        assertEquals(1, testMember22.activeTasks().get("test-subtopology").size());
+        assertEquals(Collections.singleton(1), testMember22.activeTasks().get("test-subtopology"));
+    }
+
+    @Test
+    public void shouldAssignStandbyTasksToDifferentClientThanCorrespondingActiveTaskIsAssignedTo() {
+        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3)));
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4", mkMap(mkEntry("test-subtopology", Collections.singleton(3))), Collections.emptyMap());
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2),
+                mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4));
+
+
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(4, true)
+        );
+
+
+        final List<Integer> member1TaskIds = getAllStandbyTaskIds(result, "member1");
+        assertFalse(member1TaskIds.contains(0));
+        assertTrue(member1TaskIds.size() <= 2);
+
+        final List<Integer> member2TaskIds = getAllStandbyTaskIds(result, "member2");
+        assertFalse(member2TaskIds.contains(1));
+        assertTrue(member2TaskIds.size() <= 2);
+
+        final List<Integer> member3TaskIds = getAllStandbyTaskIds(result, "member3");
+        assertFalse(member3TaskIds.contains(2));
+        assertTrue(member3TaskIds.size() <= 2);
+
+        final List<Integer> member4TaskIds = getAllStandbyTaskIds(result, "member4");
+        assertFalse(member4TaskIds.contains(3));
+        assertTrue(member4TaskIds.size() <= 2);
+
+
+        int nonEmptyStandbyTaskCount = 0;
+        nonEmptyStandbyTaskCount += member1TaskIds.size() == 0 ? 0 : 1;
+        nonEmptyStandbyTaskCount += member2TaskIds.size() == 0 ? 0 : 1;
+        nonEmptyStandbyTaskCount += member3TaskIds.size() == 0 ? 0 : 1;
+        nonEmptyStandbyTaskCount += member4TaskIds.size() == 0 ? 0 : 1;
+
+        assertTrue(nonEmptyStandbyTaskCount >= 3);
+        assertEquals(tasks, mergeAllStandbyTasks(result));
+
+    }
+
+    @Test
+    public void shouldAssignMultipleReplicasOfStandbyTask() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2),
+                mkEntry("member3", memberSpec3));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "2"))),
+                new TopologyDescriberImpl(3, true)
+        );
+
+
+        assertEquals(mkSet(1, 2), new HashSet<>(getAllStandbyTaskIds(result, "member1")));
+        assertEquals(mkSet(0, 2), new HashSet<>(getAllStandbyTaskIds(result, "member2")));
+        assertEquals(mkSet(0, 1), new HashSet<>(getAllStandbyTaskIds(result, "member3")));
+    }
+
+    @Test
+    public void shouldNotAssignStandbyTaskReplicasWhenNoClientAvailableWithoutHavingTheTaskAssigned() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(1, true)
+        );
+        assertTrue(getAllStandbyTasks(result, "member1").isEmpty());
+    }
+
+    @Test
+    public void shouldAssignActiveAndStandbyTasks() {
+
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1),
+                mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(3, true)
+        );
+
+
+
+        assertEquals(mkSet(0, 1, 2), new HashSet<>(getAllActiveTaskIds(result)));
+        assertEquals(mkSet(0, 1, 2), new HashSet<>(getAllStandbyTaskIds(result)));
+    }
+
+    @Test
+    public void shouldAssignAtLeastOneTaskToEachClientIfPossible() {
+        final AssignmentMemberSpec memberSpec11 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec12 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec13 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1_1", memberSpec11), mkEntry("member1_2", memberSpec12), mkEntry("member1_3", memberSpec13),
+                mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(1, getAllActiveTaskIds(result, "member1_1", "member1_2", "member1_3").size());
+        assertEquals(1, getAllActiveTaskIds(result, "member2").size());
+        assertEquals(1, getAllActiveTaskIds(result, "member3").size());
+    }
+
+    @Test
+    public void shouldAssignEachActiveTaskToOneClientWhenMoreClientsThanTasks() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+        final AssignmentMemberSpec memberSpec5 = createAssignmentMemberSpec("process5");
+        final AssignmentMemberSpec memberSpec6 = createAssignmentMemberSpec("process6");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3),
+                mkEntry("member4", memberSpec4), mkEntry("member5", memberSpec5), mkEntry("member6", memberSpec6));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(3, getAllActiveTaskIds(result, "member1", "member2", "member3", "member4", "member5", "member6").size());
+        assertEquals(mkSet(0, 1, 2), getActiveTasks(result, "test-subtopology", "member1", "member2", "member3", "member4", "member5", "member6"));
+    }
+
+    @Test
+    public void shouldBalanceActiveAndStandbyTasksAcrossAvailableClients() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+        final AssignmentMemberSpec memberSpec5 = createAssignmentMemberSpec("process5");
+        final AssignmentMemberSpec memberSpec6 = createAssignmentMemberSpec("process6");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3),
+                mkEntry("member4", memberSpec4), mkEntry("member5", memberSpec5), mkEntry("member6", memberSpec6));
+
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(3, true)
+        );
+
+        for (String memberId : result.members().keySet()) {
+            assertEquals(1, getAllStandbyTasks(result, memberId).size() + getAllActiveTaskIds(result, memberId).size());
+
+        }
+    }
+
+    @Test
+    public void shouldAssignMoreTasksToClientWithMoreCapacity() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec21 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec22 = createAssignmentMemberSpec("process2");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2_1", memberSpec21), mkEntry("member2_2", memberSpec22));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Arrays.asList("test-subtopology0", "test-subtopology1", "test-subtopology2", "test-subtopology3"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(8, getAllActiveTaskCount(result, "member2_1", "member2_2"));
+        assertEquals(4, getAllActiveTaskCount(result, "member1"));
+    }
+
+    @Test
+    public void shouldNotHaveSameAssignmentOnAnyTwoHosts() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+
+        final List<String> allMemberIds = asList("member1", "member2", "member3", "member4");
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(4, true)
+        );
+
+
+        for (final String memberId : allMemberIds) {
+            final List<Integer> taskIds = getAllTaskIds(result, memberId);
+            for (final String otherMemberId : allMemberIds) {
+                if (!memberId.equals(otherMemberId)) {
+                    assertNotEquals(taskIds, getAllTaskIds(result, otherMemberId));
+                }
+            }
+        }
+    }
+
+    @Test
+    public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousActiveTasks() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+
+        final List<String> allMemberIds = asList("member1", "member2", "member3", "member4");
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(4, true)
+        );
+
+
+        for (final String memberId : allMemberIds) {
+            final List<Integer> taskIds = getAllTaskIds(result, memberId);
+            for (final String otherMemberId : allMemberIds) {
+                if (!memberId.equals(otherMemberId)) {
+                    assertNotEquals(taskIds, getAllTaskIds(result, otherMemberId));
+                }
+            }
+        }
+    }
+
+    @Test
+    public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousStandbyTasks() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
+                mkMap(mkEntry("test-subtopology", mkSet(1, 2))), mkMap(mkEntry("test-subtopology", mkSet(3, 0))));
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
+                mkMap(mkEntry("test-subtopology", mkSet(3, 0))), mkMap(mkEntry("test-subtopology", mkSet(1, 2))));
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+
+
+        final List<String> allMemberIds = asList("member1", "member2", "member3", "member4");
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4));
+        final GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members,
+                        Collections.singletonList("test-subtopology"),
+                        mkMap(mkEntry("numStandbyReplicas", "1"))),
+                new TopologyDescriberImpl(4, true)
+        );
+
+
+        for (final String memberId : allMemberIds) {
+            final List<Integer> taskIds = getAllTaskIds(result, memberId);
+            for (final String otherMemberId : allMemberIds) {
+                if (!memberId.equals(otherMemberId)) {
+                    assertNotEquals(taskIds, getAllTaskIds(result, otherMemberId));
+                }
+            }
+        }
+    }
+
+    @Test
+    public void shouldReBalanceTasksAcrossAllClientsWhenCapacityAndTaskCountTheSame() {
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+        final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("member4", memberSpec4));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(4, false)
+        );
+
+        assertEquals(1, getAllActiveTaskCount(result, "member1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2"));
+        assertEquals(1, getAllActiveTaskCount(result, "member3"));
+        assertEquals(1, getAllActiveTaskCount(result, "member4"));
+    }
+
+    @Test
+    public void shouldReBalanceTasksAcrossClientsWhenCapacityLessThanTaskCount() {
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(4, false)
+        );
+
+        assertEquals(1, getAllActiveTaskCount(result, "member1"));
+        assertEquals(1, getAllActiveTaskCount(result, "member2"));
+        assertEquals(2, getAllActiveTaskCount(result, "member3"));
+    }
+
+    @Test
+    public void shouldRebalanceTasksToClientsBasedOnCapacity() {
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(0, 3, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec31 = createAssignmentMemberSpec("process3");
+        final AssignmentMemberSpec memberSpec32 = createAssignmentMemberSpec("process3");
+
+        Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member2", memberSpec2), mkEntry("member3_1", memberSpec31), mkEntry("member3_2", memberSpec32));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(3, false)
+        );
+
+        assertEquals(1, getAllActiveTaskCount(result, "member2"));
+        assertEquals(2, getAllActiveTaskCount(result, "member3_1", "member3_2"));
+    }
+
+    @Test
+    public void shouldMoveMinimalNumberOfTasksWhenPreviouslyAboveCapacityAndNewClientAdded() {
+        final Set<Integer> p1PrevTasks = mkSet(0, 2);
+        final Set<Integer> p2PrevTasks = mkSet(1, 3);
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", p1PrevTasks)), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", p2PrevTasks)), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(4, false)
+        );
+
+
+
+        assertEquals(1, getAllActiveTaskCount(result, "member3"));
+        final List<Integer> p3ActiveTasks = getAllActiveTaskIds(result, "member3");
+
+        if (p1PrevTasks.removeAll(p3ActiveTasks)) {
+            assertEquals(p2PrevTasks, new HashSet<>(getAllActiveTaskIds(result, "member2")));
+        } else {
+            assertEquals(p1PrevTasks, new HashSet<>(getAllActiveTaskIds(result, "member1")));
+        }
+    }
+
+    @Test
+    public void shouldNotMoveAnyTasksWhenNewTasksAdded() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(2, 3))), Collections.emptyMap());
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(6, false)
+        );
+
+        final List<Integer> mem1Tasks = getAllActiveTaskIds(result, "member1");
+        assertTrue(mem1Tasks.contains(0));
+        assertTrue(mem1Tasks.contains(1));
+
+        final List<Integer> mem2Tasks = getAllActiveTaskIds(result, "member2");
+        assertTrue(mem2Tasks.contains(2));
+        assertTrue(mem2Tasks.contains(3));
+    }
+
+    @Test
+    public void shouldAssignNewTasksToNewClientWhenPreviousTasksAssignedToOldClients() {
+
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(2, 1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(0, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
+
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(6, false)
+        );
+
+        final List<Integer> mem1Tasks = getAllActiveTaskIds(result, "member1");
+        assertTrue(mem1Tasks.contains(2));
+        assertTrue(mem1Tasks.contains(1));
+
+        final List<Integer> mem2Tasks = getAllActiveTaskIds(result, "member2");
+        assertTrue(mem2Tasks.contains(0));
+        assertTrue(mem2Tasks.contains(3));
+
+        final List<Integer> mem3Tasks = getAllActiveTaskIds(result, "member3");
+        assertTrue(mem3Tasks.contains(4));
+        assertTrue(mem3Tasks.contains(5));
+    }
+
+    @Test
+    public void shouldAssignTasksNotPreviouslyActiveToNewClient() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
+                mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
+                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+                mkMap(mkEntry("test-subtopology0", mkSet(1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3",
+                mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
+                mkMap(mkEntry("test-subtopology0", mkSet(2)), mkEntry("test-subtopology1", mkSet(2))));
+        final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("process4",
+               Collections.emptyMap(),
+                mkMap(mkEntry("test-subtopology0", mkSet(0, 1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 1, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 2, 3))));
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("newMember", newMemberSpec));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Arrays.asList("test-subtopology0", "test-subtopology1", "test-subtopology2"), new HashMap<>()),
+                new TopologyDescriberImpl(4, false)
+        );
+
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+                getAllActiveTasks(result, "member1"));
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+                getAllActiveTasks(result, "member2"));
+        assertEquals(mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
+                getAllActiveTasks(result, "member3"));
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))),
+                getAllActiveTasks(result, "newMember"));
+    }
+
+    @Test
+    public void shouldAssignTasksNotPreviouslyActiveToMultipleNewClients() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
+                mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
+                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+                mkMap(mkEntry("test-subtopology0", mkSet(1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+
+
+        final AssignmentMemberSpec bounce1 = createAssignmentMemberSpec("bounce1",
+                Collections.emptyMap(),
+                mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+
+
+        final AssignmentMemberSpec bounce2 = createAssignmentMemberSpec("bounce2",
+                Collections.emptyMap(),
+                mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))));
+
+
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("bounce_member1", bounce1), mkEntry("bounce_member2", bounce2));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Arrays.asList("test-subtopology0", "test-subtopology1", "test-subtopology2"), new HashMap<>()),
+                new TopologyDescriberImpl(4, false)
+        );
+
+
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+                getAllActiveTasks(result, "member1"));
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+                getAllActiveTasks(result, "member2"));
+        assertEquals(mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
+                getAllActiveTasks(result, "bounce_member1"));
+        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))),
+                getAllActiveTasks(result, "bounce_member2"));
+    }
+
+    @Test
+    public void shouldAssignTasksToNewClient() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(2, false)
+        );
+
+        assertEquals(1, getAllActiveTaskCount(result, "member1"));
+    }
+
+    @Test
+    public void shouldAssignTasksToNewClientWithoutFlippingAssignmentBetweenExistingClients() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(3, 4, 5))), Collections.emptyMap());
+        final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("process3");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("newMember", newMemberSpec));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(6, false)
+        );
+
+        final List<Integer> mem1Tasks = getAllActiveTaskIds(result, "member1");
+        assertFalse(mem1Tasks.contains(3));
+        assertFalse(mem1Tasks.contains(4));
+        assertFalse(mem1Tasks.contains(5));
+        assertEquals(2, mem1Tasks.size());
+
+        final List<Integer> mem2Tasks = getAllActiveTaskIds(result, "member2");
+        assertFalse(mem2Tasks.contains(0));
+        assertFalse(mem2Tasks.contains(1));
+        assertFalse(mem2Tasks.contains(2));
+        assertEquals(2, mem2Tasks.size());
+
+        assertEquals(2, getAllActiveTaskIds(result, "newMember").size());
+    }
+
+    @Test
+    public void shouldAssignTasksToNewClientWithoutFlippingAssignmentBetweenExistingAndBouncedClients() {
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 6))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", mkSet(3, 4, 5))));
+        final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("newProcess");
+
+        final Map<String, AssignmentMemberSpec> members = mkMap(
+                mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("newMember", newMemberSpec));
+        GroupAssignment result = assignor.assign(
+                new GroupSpecImpl(members, Collections.singletonList("test-subtopology"), new HashMap<>()),
+                new TopologyDescriberImpl(7, false)
+        );
+
+        final List<Integer> mem1Tasks = getAllActiveTaskIds(result, "member1");
+        assertFalse(mem1Tasks.contains(3));
+        assertFalse(mem1Tasks.contains(4));
+        assertFalse(mem1Tasks.contains(5));
+        assertEquals(3, mem1Tasks.size());
+
+        final List<Integer> mem2Tasks = getAllActiveTaskIds(result, "member2");
+        assertFalse(mem2Tasks.contains(0));
+        assertFalse(mem2Tasks.contains(1));
+        assertFalse(mem2Tasks.contains(2));
+        assertEquals(2, mem2Tasks.size());
+
+        assertEquals(2, getAllActiveTaskIds(result, "newMember").size());
+    }
+
+
+    private int getAllActiveTaskCount(GroupAssignment result, String... memberIds) {
+        int size = 0;
+        for (String memberId : memberIds) {
+            final MemberAssignment testMember = result.members().get(memberId);
+            assertNotNull(testMember);
+            assertNotNull(testMember.activeTasks());
+            if (testMember.activeTasks().size() != 0) {
+                for (Map.Entry<String, Set<Integer>> entry : testMember.activeTasks().entrySet()) {
+                    size += entry.getValue().size();
+                }
+            }
+        }
+        return size;
+    }
+
+    private Set<Integer> getActiveTasks(GroupAssignment result, final String topologyId, String... memberIds) {
+        Set<Integer> res = new HashSet<>();
+        for (String memberId : memberIds) {
+            final MemberAssignment testMember = result.members().get(memberId);
+            assertNotNull(testMember);
+            assertNotNull(testMember.activeTasks());
+            if (testMember.activeTasks().get(topologyId) != null) {
+                res.addAll(testMember.activeTasks().get(topologyId));
+            }
+        }
+        return res;
+    }
+
+    private List<Integer> getAllActiveTaskIds(GroupAssignment result, String... memberIds) {
+        List<Integer> res = new ArrayList<>();
+        for (String memberId : memberIds) {
+            final MemberAssignment testMember = result.members().get(memberId);
+            assertNotNull(testMember);
+            assertNotNull(testMember.activeTasks());
+            if (testMember.activeTasks().size() != 0) {
+                for (Map.Entry<String, Set<Integer>> entry : testMember.activeTasks().entrySet()) {
+                    res.addAll(entry.getValue());
+                }
+            }
+        }
+        return res;
+    }
+
+    private List<Integer> getAllActiveTaskIds(GroupAssignment result) {
+        String[] memberIds = new String[result.members().size()];
+        return getAllActiveTaskIds(result, result.members().keySet().toArray(memberIds));
+    }
+
+    private Map<String, Set<Integer>> getAllActiveTasks(GroupAssignment result, String memberId) {
+
+        final MemberAssignment testMember = result.members().get(memberId);
+        assertNotNull(testMember);
+        assertNotNull(testMember.activeTasks());
+        if (testMember.activeTasks().size() != 0) {
+            return testMember.activeTasks();
+        }
+        return new HashMap<>();
+    }
+
+    private Map<String, Set<Integer>> getAllStandbyTasks(GroupAssignment result, String memberId) {
+
+        final MemberAssignment testMember = result.members().get(memberId);
+        assertNotNull(testMember);
+        assertNotNull(testMember.standbyTasks());
+        if (testMember.standbyTasks().size() != 0) {
+            return testMember.standbyTasks();
+        }
+        return new HashMap<>();
+    }
+
+    private List<Integer> getAllStandbyTaskIds(GroupAssignment result, String... memberIds) {
+        List<Integer> res = new ArrayList<>();
+        for (String memberId : memberIds) {
+            final MemberAssignment testMember = result.members().get(memberId);
+            assertNotNull(testMember);
+            assertNotNull(testMember.standbyTasks());
+            if (testMember.standbyTasks().size() != 0) {
+                for (Map.Entry<String, Set<Integer>> entry : testMember.standbyTasks().entrySet()) {
+                    res.addAll(entry.getValue());
+                }
+            }
+        }
+        return res;
+    }
+
+    private List<Integer> getAllStandbyTaskIds(GroupAssignment result) {
+        String[] memberIds = new String[result.members().size()];
+        return getAllStandbyTaskIds(result, result.members().keySet().toArray(memberIds));
+    }
+
+    private Map<String, Set<Integer>> mergeAllActiveTasks(GroupAssignment result, String... memberIds) {
+        Map<String, Set<Integer>> res = new HashMap<>();
+        for (String memberId : memberIds) {
+            Map<String, Set<Integer>> memberActiveTasks = getAllActiveTasks(result, memberId);
+            res = Stream.of(res, memberActiveTasks)
+                    .flatMap(map -> map.entrySet().stream())
+                    .collect(Collectors.toMap(
+                            Map.Entry::getKey,
+                            Map.Entry::getValue,
+                            (v1, v2) -> {
+                                v1.addAll(v2);
+                                return new HashSet<>(v1);
+                            }));
+
+
+        }
+        return res;
+    }
+
+    private List<Integer> getAllTaskIds(GroupAssignment result, String... memberIds) {
+        List<Integer> res = new ArrayList<>();
+        res.addAll(getAllActiveTaskIds(result, memberIds));
+        res.addAll(getAllStandbyTaskIds(result, memberIds));
+        return res;
+    }
+
+    private Map<String, Set<Integer>> mergeAllStandbyTasks(GroupAssignment result, String... memberIds) {
+        Map<String, Set<Integer>> res = new HashMap<>();
+        for (String memberId : memberIds) {
+            Map<String, Set<Integer>> memberStandbyTasks = getAllStandbyTasks(result, memberId);
+            res = Stream.of(res, memberStandbyTasks)
+                    .flatMap(map -> map.entrySet().stream())
+                    .collect(Collectors.toMap(
+                            Map.Entry::getKey,
+                            Map.Entry::getValue,
+                            (v1, v2) -> {
+                                v1.addAll(v2);
+                                return new HashSet<>(v1);
+                            }));
+
+
+        }
+        return res;
+    }
+
+    private Map<String, Set<Integer>> mergeAllStandbyTasks(GroupAssignment result) {
+        String[] memberIds = new String[result.members().size()];
+        return mergeAllStandbyTasks(result, result.members().keySet().toArray(memberIds));
+    }
+
+    private AssignmentMemberSpec createAssignmentMemberSpec(final String processId) {
+        return new AssignmentMemberSpec(
+                Optional.empty(),
+                Optional.empty(),
+                Collections.emptyMap(),
+                Collections.emptyMap(),
+                Collections.emptyMap(),
+                processId,
+                Collections.emptyMap(),
+                Collections.emptyMap());
+    }
+
+    private AssignmentMemberSpec createAssignmentMemberSpec(final String processId, final Map<String, Set<Integer>> prevActiveTasks,
+                                                            final Map<String, Set<Integer>> prevStandbyTasks) {
+        return new AssignmentMemberSpec(
+                Optional.empty(),
+                Optional.empty(),
+                prevActiveTasks,
+                prevStandbyTasks,
+                Collections.emptyMap(),
+                processId,
+                Collections.emptyMap(),
+                Collections.emptyMap());
+    }
+
+    static class TopologyDescriberImpl implements TopologyDescriber {
+        final int numPartitions;
+        final boolean isStateful;
+
+        TopologyDescriberImpl(int numPartitions, boolean isStateful) {
+            this.numPartitions = numPartitions;
+            this.isStateful = isStateful;
+        }
+
+        @Override
+        public int numPartitions(String subtopologyId) {
+            return numPartitions;
+        }
+
+        @Override
+        public boolean isStateful(String subtopologyId) {
+            return isStateful;
+        }
+    }
+
+    static class TopologyDescriberImpl2 implements TopologyDescriber {
+        @Override
+        public int numPartitions(String subtopologyId) {
+            if (subtopologyId.equals("test-subtopology1"))
+                return 6;
+            return 1;
+        }
+
+        @Override
+        public boolean isStateful(String subtopologyId) {
+            return false;
+        }
+    }
+}


(kafka) 12/42: Resolve conflict from 11/25 rebase Basic heartbeat RPC handler

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 4c64b358d6279d50dc3173ba24f21adf5e31f012
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Fri Jun 7 15:32:08 2024 +0200

    Resolve conflict from 11/25 rebase Basic heartbeat RPC handler
    
    See https://github.com/lucasbru/kafka/pull/18
---
 .../group/GroupCoordinatorAdapter.scala            |  11 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   |  26 +++++
 .../group/GroupCoordinatorAdapterTest.scala        |  18 +++-
 .../scala/unit/kafka/server/KafkaApisTest.scala    |  68 ++++++++++++-
 .../kafka/coordinator/group/GroupCoordinator.java  |  16 +++
 .../coordinator/group/GroupCoordinatorService.java |  31 ++++++
 .../coordinator/group/GroupCoordinatorShard.java   |  18 ++++
 .../coordinator/group/GroupMetadataManager.java    | 102 ++++++++++++++++++-
 .../coordinator/group/streams/Assignment.java      |   6 +-
 .../group/GroupCoordinatorServiceTest.java         | 113 +++++++++++++++++++++
 .../group/GroupCoordinatorShardTest.java           |  34 +++++++
 .../group/GroupMetadataManagerTest.java            |  94 +++++++++++++++++
 .../group/GroupMetadataManagerTestContext.java     |  32 ++++++
 .../coordinator/group/streams/AssignmentTest.java  |  18 ++--
 14 files changed, 569 insertions(+), 18 deletions(-)

diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index d45221d1e71..f7b456699d0 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,7 +18,7 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
@@ -86,6 +86,15 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
+  override def streamsHeartbeat(
+                                 context: RequestContext,
+                                 request: StreamsHeartbeatRequestData
+                               ): CompletableFuture[StreamsHeartbeatResponseData] = {
+    FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
+      s"The old group coordinator does not support ${ApiKeys.STREAMS_HEARTBEAT.name} API."
+    ))
+  }
+
   override def shareGroupHeartbeat(
     context: RequestContext,
     request: ShareGroupHeartbeatRequestData
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 046f1570707..3bd368bf1e5 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -277,6 +277,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
         case ApiKeys.STREAMS_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
+        case ApiKeys.STREAMS_HEARTBEAT => handleStreamsHeartbeat(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
       }
     } catch {
@@ -3911,6 +3912,31 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
   }
 
+  def handleStreamsGroupHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsHeartbeatRequest = request.body[StreamsHeartbeatRequest]
+
+    if (!config.isNewGroupCoordinatorEnabled) {
+      // The API is not supported by the "old" group coordinator (the default). If the
+      // new one is not enabled, we fail directly here.
+      requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      CompletableFuture.completedFuture[Unit](())
+    } else if (!authHelper.authorize(request.context, READ, GROUP, streamsHeartbeatRequest.data.groupId)) {
+      requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(Errors.GROUP_AUTHORIZATION_FAILED.exception))
+      CompletableFuture.completedFuture[Unit](())
+    } else {
+      groupCoordinator.streamsHeartbeat(
+        request.context,
+        streamsHeartbeatRequest.data,
+      ).handle[Unit] { (response, exception) =>
+        if (exception != null) {
+          requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(exception))
+        } else {
+          requestHelper.sendMaybeThrottle(request, new StreamsHeartbeatResponse(response))
+        }
+      }
+    }
+  }
+
   def handleGetTelemetrySubscriptionsRequest(request: RequestChannel.Request): Unit = {
     val subscriptionRequest = request.body[GetTelemetrySubscriptionsRequest]
 
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index 0d57eea15f9..03fcf3ff21d 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -19,7 +19,7 @@ package kafka.coordinator.group
 import kafka.coordinator.group.GroupCoordinatorConcurrencyTest.{JoinGroupCallback, SyncGroupCallback}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
 import org.apache.kafka.common.errors.{InvalidGroupIdException, UnsupportedVersionException}
-import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
+import org.apache.kafka.common.message.{ConsumerGroupHeartbeatRequestData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, OffsetFetchRequestData, OffsetFetchResponseData, ShareGroupHeartbeatRequestDa [...]
 import org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol
 import org.apache.kafka.common.message.JoinGroupResponseData.JoinGroupResponseMember
 import org.apache.kafka.common.message.OffsetDeleteRequestData.{OffsetDeleteRequestPartition, OffsetDeleteRequestTopic, OffsetDeleteRequestTopicCollection}
@@ -94,6 +94,22 @@ class GroupCoordinatorAdapterTest {
     assertFutureThrows(future, classOf[UnsupportedVersionException])
   }
 
+  @Test
+  def testStreamsHeartbeat(): Unit = {
+    val groupCoordinator = mock(classOf[GroupCoordinator])
+    val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
+
+    val ctx = makeContext(ApiKeys.STREAMS_HEARTBEAT, ApiKeys.STREAMS_HEARTBEAT.latestVersion)
+    val request = new StreamsHeartbeatRequestData()()
+      .setGroupId("group")
+
+    val future = adapter.streamsHeartbeat(ctx, request)
+
+    assertTrue(future.isDone)
+    assertTrue(future.isCompletedExceptionally)
+    assertFutureThrows(future, classOf[UnsupportedVersionException])
+  }
+
   @Test
   def testJoinShareGroup(): Unit = {
     val groupCoordinator = mock(classOf[GroupCoordinator])
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 4c0f3421e3f..c0bfa5d0f31 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11233,7 +11233,8 @@ class KafkaApisTest extends Logging {
     val response = verifyNoThrottling[ConsumerGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
-  
+
+  @Test
   def testStreamsInitializeRequest(): Unit = {
     val streamsInitializeRequest = new StreamsInitializeRequestData().setGroupId("group")
 
@@ -11296,6 +11297,71 @@ class KafkaApisTest extends Logging {
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
   }
 
+
+  @Test
+  def testStreamsHeartbeatRequest(): Unit = {
+    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+
+    val future = new CompletableFuture[StreamsHeartbeatResponseData]()
+    when(groupCoordinator.streamsHeartbeat(
+      requestChannelRequest.context,
+      streamsHeartbeatRequest
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(overrideProperties = Map(
+      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
+    ))
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    val streamsHeartbeatResponse = new StreamsHeartbeatResponseData()
+      .setMemberId("member")
+
+    future.complete(streamsHeartbeatResponse)
+    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    assertEquals(streamsHeartbeatResponse, response.data)
+  }
+
+  @Test
+  def testStreamsHeartbeatRequestFutureFailed(): Unit = {
+    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+
+    val future = new CompletableFuture[StreamsHeartbeatResponseData]()
+    when(groupCoordinator.streamsHeartbeat(
+      requestChannelRequest.context,
+      streamsHeartbeatRequest
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(overrideProperties = Map(
+      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
+    ))
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
+    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.errorCode)
+  }
+
+  @Test
+  def testStreamsHeartbeatRequestAuthorizationFailed(): Unit = {
+    val streamsHeartbeatRequest = new StreamsHeartbeatRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+
+    val authorizer: Authorizer = mock(classOf[Authorizer])
+    when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
+      .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
+    kafkaApis = createKafkaApis(
+      authorizer = Some(authorizer),
+      overrideProperties = Map(GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true")
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    val response = verifyNoThrottling[StreamsHeartbeatResponse](requestChannelRequest)
+    assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
+  }
+
   @ParameterizedTest
   @ValueSource(booleans = Array(true, false))
   def testConsumerGroupDescribe(includeAuthorizedOperations: Boolean): Unit = {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index 8a5032451b1..900a789f2c0 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -39,6 +39,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -98,6 +100,20 @@ public interface GroupCoordinator {
         StreamsInitializeRequestData request
     );
 
+    /**
+     * Heartbeat to a Streams Group.
+     *
+     * @param context           The request context.
+     * @param request           The StreamsHeartbeatResponseData data.
+     *
+     * @return  A future yielding the response.
+     *          The error code(s) of the response are set to indicate the error(s) occurred during the execution.
+     */
+    CompletableFuture<StreamsHeartbeatResponseData> streamsHeartbeat(
+        RequestContext context,
+        StreamsHeartbeatRequestData request
+    );
+
     /**
      * Heartbeat to a Share Group.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 2a3eef88a04..9f180c5798a 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -44,6 +44,8 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData.DescribedGroup;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -375,6 +377,35 @@ public class GroupCoordinatorService implements GroupCoordinator {
         ));
     }
 
+    /**
+     * See {@link GroupCoordinator#streamsHeartbeat(RequestContext, StreamsHeartbeatRequestData)}.
+     */
+    @Override
+    public CompletableFuture<StreamsHeartbeatResponseData> streamsHeartbeat(
+        RequestContext context,
+        StreamsHeartbeatRequestData request
+    ) {
+        if (!isActive.get()) {
+            return CompletableFuture.completedFuture(new StreamsHeartbeatResponseData()
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
+            );
+        }
+
+        return runtime.scheduleWriteOperation(
+            "streams-heartbeat",
+            topicPartitionFor(request.groupId()),
+            Duration.ofMillis(config.offsetCommitTimeoutMs),
+            coordinator -> coordinator.streamsHeartbeat(context, request)
+        ).exceptionally(exception -> handleOperationException(
+            "streams-heartbeat",
+            request,
+            exception,
+            (error, message) -> new StreamsHeartbeatResponseData()
+                .setErrorCode(error.code())
+                .setErrorMessage(message)
+        ));
+    }
+
     /**
      * See {@link GroupCoordinator#shareGroupHeartbeat(RequestContext, ShareGroupHeartbeatRequestData)}.
      */
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index b002f96b60b..2eed6f395e3 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -39,6 +39,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -379,6 +381,22 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
         return groupMetadataManager.streamsInitialize(context, request);
     }
 
+    /**
+     * Handles a StreamsHeartbeat request.
+     *
+     * @param context The request context.
+     * @param request The actual StreamsHeartbeat request.
+     *
+     * @return A Result containing the StreamsHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+        RequestContext context,
+        StreamsHeartbeatRequestData request
+    ) {
+        return groupMetadataManager.streamsHeartbeat(context, request);
+    }
+
     /**
      * Handles a ShareGroupHeartbeat request.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index c7cf02f7974..f95b9693ca8 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -53,6 +53,8 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -1427,6 +1429,52 @@ public class GroupMetadataManager {
     
 
     /**
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfStreamsHeartbeatRequestIsInvalid(
+        StreamsHeartbeatRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        throwIfEmptyString(request.groupId(), "GroupId can't be empty.");
+        throwIfEmptyString(request.instanceId(), "InstanceId can't be empty.");
+        throwIfEmptyString(request.rackId(), "RackId can't be empty.");
+
+        if (request.memberEpoch() > 0 || request.memberEpoch() == LEAVE_GROUP_MEMBER_EPOCH) {
+            throwIfEmptyString(request.memberId(), "MemberId can't be empty.");
+        } else if (request.memberEpoch() == 0) {
+            if (request.rebalanceTimeoutMs() == -1) {
+                throw new InvalidRequestException("RebalanceTimeoutMs must be provided in first request.");
+            }
+            if (request.activeTasks() == null || !request.activeTasks().isEmpty()) {
+                throw new InvalidRequestException("ActiveTasks must be empty when (re-)joining.");
+            }
+            if (request.standbyTasks() == null || !request.standbyTasks().isEmpty()) {
+                throw new InvalidRequestException("StandbyTasks must be empty when (re-)joining.");
+            }
+            if (request.warmupTasks() == null || !request.warmupTasks().isEmpty()) {
+                throw new InvalidRequestException("WarmupTasks must be empty when (re-)joining.");
+            }
+            // TODO: check that active, standby and warmup do not intersect
+        } else if (request.memberEpoch() == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
+            throwIfEmptyString(request.memberId(), "MemberId can't be empty.");
+            throwIfNull(request.instanceId(), "InstanceId can't be null.");
+        } else {
+            throw new InvalidRequestException("MemberEpoch is invalid.");
+        }
+
+        // TODO: Check that task assignor exists.
+//        if (request.assignor() != null && !assignors.containsKey(request.assignor())) {
+//            throw new UnsupportedAssignorException("Assignor " + request.assignor()
+//                + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
+//                + ".");
+//        }
+    }
+
     /**
      * Verifies that the partitions currently owned by the member (the ones set in the
      * request) matches the ones that the member should own. It matches if the consumer
@@ -3640,12 +3688,12 @@ public class GroupMetadataManager {
     }
 
     /**
-     * Handles a ConsumerGroupHeartbeat request.
+     * Handles a StreamsInitialize request.
      *
      * @param context The request context.
-     * @param request The actual ConsumerGroupHeartbeat request.
+     * @param request The actual StreamsInitialize request.
      *
-     * @return A Result containing the ConsumerGroupHeartbeat response and
+     * @return A Result containing the StreamsInitialize response and
      *         a list of records to update the state machine.
      */
     public CoordinatorResult<StreamsInitializeResponseData, CoordinatorRecord> streamsInitialize(
@@ -3660,6 +3708,54 @@ public class GroupMetadataManager {
         );
     }
 
+    /**
+     * Handles a StreamsHeartbeat request.
+     *
+     * @param context The request context.
+     * @param request The actual StreamsHeartbeat request.
+     *
+     * @return A Result containing the StreamsHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+        RequestContext context,
+        StreamsHeartbeatRequestData request
+    ) throws ApiException {
+        throwIfStreamsHeartbeatRequestIsInvalid(request);
+
+        return new CoordinatorResult<>(
+            Collections.emptyList(),
+            new StreamsHeartbeatResponseData()
+                .setErrorCode(Errors.NONE.code())
+        );
+
+//        if (request.memberEpoch() == LEAVE_GROUP_MEMBER_EPOCH || request.memberEpoch() == LEAVE_GROUP_STATIC_MEMBER_EPOCH) {
+//            // TODO: -1 means that the member wants to leave the group.
+//            // -2 means that a static member wants to leave the group.
+//            return consumerGroupLeave(
+//                request.groupId(),
+//                request.instanceId(),
+//                request.memberId(),
+//                request.memberEpoch()
+//            );
+//        } else {
+//            // TODO: Otherwise, it is a regular heartbeat.
+//            return consumerGroupHeartbeat(
+//                request.groupId(),
+//                request.memberId(),
+//                request.memberEpoch(),
+//                request.instanceId(),
+//                request.rackId(),
+//                request.rebalanceTimeoutMs(),
+//                context.clientId(),
+//                context.clientAddress.toString(),
+//                request.subscribedTopicNames(),
+//                request.serverAssignor(),
+//                request.topicPartitions()
+//            );
+//        }
+    }
+
     /**
      * Replays StreamsGroupTopologyKey/Value to update the hard state of
      * the streams group.
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
index 735ee414785..54e4cbc63a4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -103,19 +103,19 @@ public class Assignment {
         return new Assignment(
             record.activeTasks().stream()
                 .collect(Collectors.toMap(
-                    StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                    StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
                     taskId -> new HashSet<>(taskId.partitions())
                     )
                 ),
             record.standbyTasks().stream()
                 .collect(Collectors.toMap(
-                        StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
                         taskId -> new HashSet<>(taskId.partitions())
                     )
                 ),
             record.warmupTasks().stream()
                 .collect(Collectors.toMap(
-                        StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
                         taskId -> new HashSet<>(taskId.partitions())
                     )
                 )
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index 96273e368e1..fa19409b208 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -54,6 +54,8 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -375,6 +377,117 @@ public class GroupCoordinatorServiceTest {
         );
     }
 
+    @Test
+    public void testStreamsHeartbeatWhenNotStarted() throws ExecutionException, InterruptedException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+            .setGroupId("foo");
+
+        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+            request
+        );
+
+        assertEquals(
+            new StreamsHeartbeatResponseData()
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code()),
+            future.get()
+        );
+    }
+
+    @Test
+    public void testStreamsHeartbeat() throws ExecutionException, InterruptedException, TimeoutException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+            .setGroupId("foo");
+
+        service.startup(() -> 1);
+
+        when(runtime.scheduleWriteOperation(
+            ArgumentMatchers.eq("streams-heartbeat"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.eq(Duration.ofMillis(5000)),
+            ArgumentMatchers.any()
+        )).thenReturn(CompletableFuture.completedFuture(
+            new StreamsHeartbeatResponseData()
+        ));
+
+        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+            request
+        );
+
+        assertEquals(new StreamsHeartbeatResponseData(), future.get(5, TimeUnit.SECONDS));
+    }
+
+    private static Stream<Arguments> testStreamsHeartbeatWithExceptionSource() {
+        return Stream.of(
+            Arguments.arguments(new UnknownTopicOrPartitionException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new NotEnoughReplicasException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new org.apache.kafka.common.errors.TimeoutException(), Errors.COORDINATOR_NOT_AVAILABLE.code(), null),
+            Arguments.arguments(new NotLeaderOrFollowerException(), Errors.NOT_COORDINATOR.code(), null),
+            Arguments.arguments(new KafkaStorageException(), Errors.NOT_COORDINATOR.code(), null),
+            Arguments.arguments(new RecordTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new RecordBatchTooLargeException(), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new InvalidFetchSizeException(""), Errors.UNKNOWN_SERVER_ERROR.code(), null),
+            Arguments.arguments(new InvalidRequestException("Invalid"), Errors.INVALID_REQUEST.code(), "Invalid")
+        );
+    }
+
+    @ParameterizedTest
+    @MethodSource("testStreamsHeartbeatWithExceptionSource")
+    public void testStreamsHeartbeatWithException(
+        Throwable exception,
+        short expectedErrorCode,
+        String expectedErrorMessage
+    ) throws ExecutionException, InterruptedException, TimeoutException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+
+        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData()
+            .setGroupId("foo");
+
+        service.startup(() -> 1);
+
+        when(runtime.scheduleWriteOperation(
+            ArgumentMatchers.eq("streams-heartbeat"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.eq(Duration.ofMillis(5000)),
+            ArgumentMatchers.any()
+        )).thenReturn(FutureUtils.failedFuture(exception));
+
+        CompletableFuture<StreamsHeartbeatResponseData> future = service.streamsHeartbeat(
+            requestContext(ApiKeys.STREAMS_HEARTBEAT),
+            request
+        );
+
+        assertEquals(
+            new StreamsHeartbeatResponseData()
+                .setErrorCode(expectedErrorCode)
+                .setErrorMessage(expectedErrorMessage),
+            future.get(5, TimeUnit.SECONDS)
+        );
+    }
+    
     @Test
     public void testPartitionFor() {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index 33756fe53ac..da7fcc52de5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -24,6 +24,8 @@ import org.apache.kafka.common.message.OffsetCommitRequestData;
 import org.apache.kafka.common.message.OffsetCommitResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.TxnOffsetCommitRequestData;
@@ -165,6 +167,38 @@ public class GroupCoordinatorShardTest {
         assertEquals(result, coordinator.streamsInitialize(context, request));
     }
 
+    @Test
+    public void testStreamsHeartbeat() {
+        GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
+        OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
+        CoordinatorMetrics coordinatorMetrics = mock(CoordinatorMetrics.class);
+        CoordinatorMetricsShard metricsShard = mock(CoordinatorMetricsShard.class);
+        GroupCoordinatorShard coordinator = new GroupCoordinatorShard(
+            new LogContext(),
+            groupMetadataManager,
+            offsetMetadataManager,
+            Time.SYSTEM,
+            new MockCoordinatorTimer<>(Time.SYSTEM),
+            mock(GroupCoordinatorConfig.class),
+            coordinatorMetrics,
+            metricsShard
+        );
+
+        RequestContext context = requestContext(ApiKeys.STREAMS_HEARTBEAT);
+        StreamsHeartbeatRequestData request = new StreamsHeartbeatRequestData();
+        CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> result = new CoordinatorResult<>(
+            Collections.emptyList(),
+            new StreamsHeartbeatResponseData()
+        );
+
+        when(groupMetadataManager.streamsHeartbeat(
+            context,
+            request
+        )).thenReturn(result);
+
+        assertEquals(result, coordinator.streamsHeartbeat(context, request));
+    }
+    
     @Test
     public void testCommitOffset() {
         GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index c9f2d80ca2b..48afadb6ce7 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -54,6 +54,7 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData.Subtopology;
 import org.apache.kafka.common.message.StreamsInitializeRequestData.TopicConfig;
@@ -261,6 +262,99 @@ public class GroupMetadataManagerTest {
         assertEquals("InstanceId can't be null.", ex.getMessage());
     }
 
+
+    @Test
+    public void testStreamsRequestValidation() {
+//        TODO MockTaskAssignor assignor = new MockTaskAssignor("range");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+//            .withAssignors(Collections.singletonList(assignor))
+            .build();
+        Exception ex;
+
+        // GroupId must be present in all requests.
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()));
+        assertEquals("GroupId can't be empty.", ex.getMessage());
+
+        // GroupId can't be all whitespaces.
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("   ")));
+        assertEquals("GroupId can't be empty.", ex.getMessage());
+
+        // RebalanceTimeoutMs must be present in the first request (epoch == 0).
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberEpoch(0)));
+        assertEquals("RebalanceTimeoutMs must be provided in first request.", ex.getMessage());
+
+        // ActiveTasks must be present and empty in the first request (epoch == 0).
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberEpoch(0)
+                .setRebalanceTimeoutMs(5000)
+                .setStandbyTasks(Collections.emptyList())
+                .setWarmupTasks(Collections.emptyList())));
+        assertEquals("ActiveTasks must be empty when (re-)joining.", ex.getMessage());
+
+        // StandbyTasks must be present and empty in the first request (epoch == 0).
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberEpoch(0)
+                .setRebalanceTimeoutMs(5000)
+                .setActiveTasks(Collections.emptyList())
+                .setWarmupTasks(Collections.emptyList())));
+        assertEquals("StandbyTasks must be empty when (re-)joining.", ex.getMessage());
+
+        // WarmupTasks must be present and empty in the first request (epoch == 0).
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberEpoch(0)
+                .setRebalanceTimeoutMs(5000)
+                .setActiveTasks(Collections.emptyList())
+                .setStandbyTasks(Collections.emptyList())));
+        assertEquals("WarmupTasks must be empty when (re-)joining.", ex.getMessage());
+
+        // MemberId must be non-empty in all requests except for the first one where it
+        // could be empty (epoch != 0).
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberEpoch(1)));
+        assertEquals("MemberId can't be empty.", ex.getMessage());
+
+        // InstanceId must be non-empty if provided in all requests.
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberId(Uuid.randomUuid().toString())
+                .setMemberEpoch(1)
+                .setInstanceId("")));
+        assertEquals("InstanceId can't be empty.", ex.getMessage());
+
+        // RackId must be non-empty if provided in all requests.
+        ex = assertThrows(InvalidRequestException.class, () -> context.streamsHeartbeat(
+            new StreamsHeartbeatRequestData()
+                .setGroupId("foo")
+                .setMemberId(Uuid.randomUuid().toString())
+                .setMemberEpoch(1)
+                .setRackId("")));
+        assertEquals("RackId can't be empty.", ex.getMessage());
+
+//       TODO: // ServerAssignor must exist if provided in all requests.
+//        ex = assertThrows(UnsupportedAssignorException.class, () -> context.streamsHeartbeat(
+//            new StreamsHeartbeatRequestData()
+//                .setGroupId("foo")
+//                .setMemberId(Uuid.randomUuid().toString())
+//                .setMemberEpoch(1)
+//                .setServerAssignor("bar")));
+//        assertEquals("ServerAssignor bar is not supported. Supported assignors: range.", ex.getMessage());
+    }
+
     @Test
     public void testConsumerHeartbeatRegexValidation() {
         String memberId = Uuid.randomUuid().toString();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index bdcc0c9e012..e2e663466b3 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -36,6 +36,8 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
@@ -708,6 +710,36 @@ public class GroupMetadataManagerTestContext {
         return result;
     }
 
+    public CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> streamsHeartbeat(
+        StreamsHeartbeatRequestData request
+    ) {
+        RequestContext context = new RequestContext(
+            new RequestHeader(
+                ApiKeys.STREAMS_HEARTBEAT,
+                ApiKeys.STREAMS_HEARTBEAT.latestVersion(),
+                "client",
+                0
+            ),
+            "1",
+            InetAddress.getLoopbackAddress(),
+            KafkaPrincipal.ANONYMOUS,
+            ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT),
+            SecurityProtocol.PLAINTEXT,
+            ClientInformation.EMPTY,
+            false
+        );
+
+        CoordinatorResult<StreamsHeartbeatResponseData, CoordinatorRecord> result = groupMetadataManager.streamsHeartbeat(
+            context,
+            request
+        );
+
+        if (result.replayRecords()) {
+            result.records().forEach(this::replay);
+        }
+        return result;
+    }
+
     public List<MockCoordinatorTimer.ExpiredTimeout<Void, CoordinatorRecord>> sleep(long ms) {
         time.sleep(ms);
         List<MockCoordinatorTimer.ExpiredTimeout<Void, CoordinatorRecord>> timeouts = timer.poll();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
index baff38bceaf..49ba49753bc 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -62,25 +62,25 @@ public class AssignmentTest {
     public void testFromTargetAssignmentRecord() {
         String subtopology1 = "subtopology1";
         String subtopology2 = "subtopology2";
-        List<StreamsGroupTargetAssignmentMemberValue.TaskId> activeTasks = new ArrayList<>();
-        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> activeTasks = new ArrayList<>();
+        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology1)
             .setPartitions(Arrays.asList(1, 2, 3)));
-        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology2)
             .setPartitions(Arrays.asList(4, 5, 6)));
-        List<StreamsGroupTargetAssignmentMemberValue.TaskId> standbyTasks = new ArrayList<>();
-        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> standbyTasks = new ArrayList<>();
+        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology1)
             .setPartitions(Arrays.asList(7, 8, 9)));
-        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology2)
             .setPartitions(Arrays.asList(1, 2, 3)));
-        List<StreamsGroupTargetAssignmentMemberValue.TaskId> warmupTasks = new ArrayList<>();
-        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        List<StreamsGroupTargetAssignmentMemberValue.TaskIds> warmupTasks = new ArrayList<>();
+        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology1)
             .setPartitions(Arrays.asList(4, 5, 6)));
-        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskIds()
             .setSubtopology(subtopology2)
             .setPartitions(Arrays.asList(7, 8, 9)));
 


(kafka) 33/42: Resolve conflicts from 11/25 trunk rebase - MINOR: Rebase dev branch on current trunk

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 16c51af4e20bfa521d994d4430c1ea61a88c0893
Author: Bruno Cadonna <ca...@apache.org>
AuthorDate: Wed Oct 16 15:16:59 2024 +0200

    Resolve conflicts from 11/25 trunk rebase - MINOR: Rebase dev branch on current trunk
---
 .../StreamsGroupHeartbeatRequestManager.java       |  19 +++-
 .../events/ApplicationEventProcessor.java          |   4 +
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  10 +-
 .../StreamsGroupInitializeRequestManagerTest.java  |  27 ++---
 core/src/main/scala/kafka/server/KafkaConfig.scala |   4 +-
 .../group/GroupCoordinatorConfigTest.java          |   1 +
 .../group/GroupMetadataManagerTest.java            |   9 +-
 .../group/streams/TaskAssignmentTestUtil.java      |   4 +-
 .../group/taskassignor/MockAssignorTest.java       |  29 +++---
 .../group/taskassignor/StickyTaskAssignorTest.java | 111 ++++++++++-----------
 10 files changed, 121 insertions(+), 97 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 7e31859571d..896800cff3c 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -57,6 +57,8 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
     private final Logger logger;
 
+    private final int maxPollIntervalMs;
+
     private final CoordinatorRequestManager coordinatorRequestManager;
 
     private final StreamsGroupHeartbeatRequestManager.HeartbeatRequestState heartbeatRequestState;
@@ -96,7 +98,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         this.membershipManager = membershipManager;
         this.streamsGroupInitializeRequestManager = streamsGroupInitializeRequestManager;
         this.backgroundEventHandler = backgroundEventHandler;
-        int maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
+        this.maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
         long retryBackoffMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG);
         long retryBackoffMaxMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MAX_MS_CONFIG);
         this.heartbeatState = new StreamsGroupHeartbeatRequestManager.HeartbeatState(streamsAssignmentInterface, membershipManager,
@@ -144,6 +146,10 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         return new NetworkClientDelegate.PollResult(heartbeatRequestState.heartbeatIntervalMs, Collections.singletonList(request));
     }
 
+    public ConsumerMembershipManager membershipManager() {
+        return membershipManager;
+    }
+
     @Override
     public long maximumTimeToWait(long currentTimeMs) {
         pollTimer.update(currentTimeMs);
@@ -156,6 +162,17 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
         return Math.min(pollTimer.remainingMs() / 2, heartbeatRequestState.nextHeartbeatMs(currentTimeMs));
     }
 
+    public void resetPollTimer(final long pollMs) {
+        pollTimer.update(pollMs);
+        if (pollTimer.isExpired()) {
+            logger.warn("Time between subsequent calls to poll() was longer than the configured " +
+                    "max.poll.interval.ms, exceeded approximately by {} ms. Member {} will rejoin the group now.",
+                pollTimer.isExpiredBy(), membershipManager().memberId());
+            membershipManager().maybeRejoinStaleMember();
+        }
+        pollTimer.reset(maxPollIntervalMs);
+    }
+
     private NetworkClientDelegate.UnsentRequest makeHeartbeatRequest(final long currentTimeMs,
                                                                      final boolean ignoreResponse) {
         NetworkClientDelegate.UnsentRequest request = makeHeartbeatRequest(ignoreResponse);
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
index 52aee8f20e0..135857a06b6 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
@@ -192,6 +192,10 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
                 hrm.membershipManager().onConsumerPoll();
                 hrm.resetPollTimer(event.pollTimeMs());
             });
+            requestManagers.streamsGroupHeartbeatRequestManager.ifPresent(hrm -> {
+                hrm.membershipManager().onConsumerPoll();
+                hrm.resetPollTimer(event.pollTimeMs());
+            });
         } else {
             requestManagers.shareHeartbeatRequestManager.ifPresent(hrm -> {
                 hrm.membershipManager().onConsumerPoll();
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index 91b9b5ae45a..193c901e3b7 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -54,12 +54,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Properties;
+import java.util.Set;
 import java.util.UUID;
 import java.util.stream.Collectors;
 
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.common.utils.Utils.mkSet;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -251,7 +251,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
                 Collections.singleton("sink0"),
                 Collections.singletonMap("repartition0", emptyTopicInfo),
                 Collections.singletonMap("changelog0", emptyTopicInfo),
-                Collections.singletonList(mkSet("source0", "repartition0"))
+                Collections.singletonList(Set.of("source0", "repartition0"))
             ));
         streamsAssignmentInterface.subtopologyMap().put("1",
             new Subtopology(
@@ -259,7 +259,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
                 Collections.singleton("sink1"),
                 Collections.singletonMap("repartition1", emptyTopicInfo),
                 Collections.singletonMap("changelog1", emptyTopicInfo),
-                Collections.singletonList(mkSet("source1", "repartition1"))
+                Collections.singletonList(Set.of("source1", "repartition1"))
             ));
         streamsAssignmentInterface.subtopologyMap().put("2",
             new Subtopology(
@@ -267,7 +267,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
                 Collections.singleton("sink2"),
                 Collections.singletonMap("repartition2", emptyTopicInfo),
                 Collections.singletonMap("changelog2", emptyTopicInfo),
-                Collections.singletonList(mkSet("source2", "repartition2"))
+                Collections.singletonList(Set.of("source2", "repartition2"))
             ));
 
         StreamsGroupHeartbeatResponseData data = new StreamsGroupHeartbeatResponseData()
@@ -296,7 +296,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
         assertEquals(1000, response.heartbeatIntervalMs());
         final List<TopicPartitions> tps = response.assignment().topicPartitions();
         assertEquals(2, tps.size());
-        assertEquals(mkSet(uuid0, uuid1), tps.stream().map(TopicPartitions::topicId).collect(Collectors.toSet()));
+        assertEquals(Set.of(uuid0, uuid1), tps.stream().map(TopicPartitions::topicId).collect(Collectors.toSet()));
         assertEquals(Collections.singletonList(0), tps.get(0).partitions());
         assertEquals(Collections.singletonList(0), tps.get(1).partitions());
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index f5bc091e7b0..35eeaaf4baf 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -36,7 +36,6 @@ import java.util.Set;
 
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.common.utils.Utils.mkSet;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -71,8 +70,8 @@ class StreamsGroupInitializeRequestManagerTest {
         final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
         when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(node));
         final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
-        final Set<String> sourceTopics = mkSet("sourceTopic1", "sourceTopic2");
-        final Set<String> sinkTopics = mkSet("sinkTopic1", "sinkTopic2", "sinkTopic3");
+        final Set<String> sourceTopics = Set.of("sourceTopic1", "sourceTopic2");
+        final Set<String> sinkTopics = Set.of("sinkTopic1", "sinkTopic2", "sinkTopic3");
         final Map<String, StreamsAssignmentInterface.TopicInfo> repartitionTopics = mkMap(
             mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Optional.of((short) 1), Collections.emptyMap())),
             mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Optional.of((short) 3), Collections.emptyMap()))
@@ -82,9 +81,9 @@ class StreamsGroupInitializeRequestManagerTest {
             mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 2), Collections.emptyMap())),
             mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Optional.of((short) 3), Collections.emptyMap()))
         );
-        final Collection<Set<String>> copartitionGroup = mkSet(
-            mkSet("sourceTopic1", "repartitionTopic2"),
-            mkSet("sourceTopic2", "repartitionTopic1")
+        final Collection<Set<String>> copartitionGroup = Set.of(
+            Set.of("sourceTopic1", "repartitionTopic2"),
+            Set.of("sourceTopic2", "repartitionTopic1")
         );
         final StreamsAssignmentInterface.Subtopology subtopology1 = new StreamsAssignmentInterface.Subtopology(
             sourceTopics,
@@ -139,11 +138,15 @@ class StreamsGroupInitializeRequestManagerTest {
         });
 
         assertEquals(2, subtopology.copartitionGroups().size());
-        final StreamsGroupInitializeRequestData.CopartitionGroup copartitionGroupData1 = subtopology.copartitionGroups().get(0);
-        assertEquals(Collections.singletonList((short) 0), copartitionGroupData1.sourceTopics());
-        assertEquals(Collections.singletonList((short) 1), copartitionGroupData1.repartitionSourceTopics());
-        final StreamsGroupInitializeRequestData.CopartitionGroup copartitionGroupData2 = subtopology.copartitionGroups().get(1);
-        assertEquals(Collections.singletonList((short) 1), copartitionGroupData2.sourceTopics());
-        assertEquals(Collections.singletonList((short) 0), copartitionGroupData2.repartitionSourceTopics());
+        final StreamsGroupInitializeRequestData.CopartitionGroup expectedCopartitionGroupData1 =
+            new StreamsGroupInitializeRequestData.CopartitionGroup()
+                .setRepartitionSourceTopics(Collections.singletonList((short) 0))
+                .setSourceTopics(Collections.singletonList((short) 1));
+        final StreamsGroupInitializeRequestData.CopartitionGroup expectedCopartitionGroupData2 =
+            new StreamsGroupInitializeRequestData.CopartitionGroup()
+                .setRepartitionSourceTopics(Collections.singletonList((short) 1))
+                .setSourceTopics(Collections.singletonList((short) 0));
+        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData1));
+        assertTrue(subtopology.copartitionGroups().contains(expectedCopartitionGroupData2));
     }
 }
\ No newline at end of file
diff --git a/core/src/main/scala/kafka/server/KafkaConfig.scala b/core/src/main/scala/kafka/server/KafkaConfig.scala
index 3b9aa091b8a..378709eda0c 100755
--- a/core/src/main/scala/kafka/server/KafkaConfig.scala
+++ b/core/src/main/scala/kafka/server/KafkaConfig.scala
@@ -600,8 +600,8 @@ class KafkaConfig private(doLog: Boolean, val props: util.Map[_, _])
         "This is part of the early access of KIP-932 and MUST NOT be used in production.")
     }
     if (protocols.contains(GroupType.STREAMS)) {
-      if (processRoles.isEmpty) {
-        throw new ConfigException(s"The new '${GroupType.STREAMS}' rebalance protocol is only supported in KRaft cluster.")
+      if (processRoles.isEmpty || !isNewGroupCoordinatorEnabled) {
+        throw new ConfigException(s"The new '${GroupType.STREAMS}' rebalance protocol is only supported in KRaft cluster with the new group coordinator.")
       }
       warn(s"The new '${GroupType.STREAMS}' rebalance protocol is enabled along with the new group coordinator. " +
         "This is part of the preview of KIP-1071 and MUST NOT be used in production.")
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
index baf55529fa5..decfaea980e 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorConfigTest.java
@@ -186,6 +186,7 @@ public class GroupCoordinatorConfigTest {
         configs.put(GroupCoordinatorConfig.SHARE_GROUP_HEARTBEAT_INTERVAL_MS_CONFIG, 50000);
         configs.put(GroupCoordinatorConfig.SHARE_GROUP_SESSION_TIMEOUT_MS_CONFIG, 50000);
         assertEquals("group.share.heartbeat.interval.ms must be less than group.share.session.timeout.ms",
+                assertThrows(IllegalArgumentException.class, () -> createConfig(configs)).getMessage());
         
         configs.put(GroupCoordinatorConfig.STREAMS_GROUP_SESSION_TIMEOUT_MS_CONFIG, 0);
         assertEquals("Invalid value 0 for configuration group.streams.session.timeout.ms: Value must be at least 1",
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index bf458507eac..8ff26e74f35 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -576,14 +576,15 @@ public class GroupMetadataManagerTest {
         assertEquals(5, coordinatorRecords.size());
         assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
         assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(groupId, subtopologies)));
+
         org.apache.kafka.coordinator.group.streams.TopicMetadata topicMetadata = new org.apache.kafka.coordinator.group.streams.TopicMetadata(
             inputTopicId,
             inputTopicName,
             3,
             mkMap(
-                mkEntry(0, mkSet("rack0", "rack1")),
-                mkEntry(1, mkSet("rack1", "rack2")),
-                mkEntry(2, mkSet("rack2", "rack3"))
+                mkEntry(0, new HashSet<>(List.of("rack1", "rack0"))),
+                mkEntry(1, new HashSet<>(List.of("rack2", "rack1"))),
+                mkEntry(2, new HashSet<>(List.of("rack2", "rack3")))
             )
         );
         assertTrue(coordinatorRecords.contains(
@@ -837,7 +838,7 @@ public class GroupMetadataManagerTest {
                         mkMap(
                             mkEntry(
                                 subtopologyId,
-                                mkSet(0, 1, 2)
+                                new HashSet<>(List.of(0, 1, 2))
                             )
                         ),
                         Collections.emptyMap(),
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
index c3980d0343f..bcf1ba65be7 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
@@ -19,10 +19,10 @@ package org.apache.kafka.coordinator.group.streams;
 import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
 
 import java.util.AbstractMap;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
@@ -73,7 +73,7 @@ public class TaskAssignmentTestUtil {
     ) {
         return new AbstractMap.SimpleEntry<>(
             subtopologyId,
-            new HashSet<>(Arrays.asList(tasks))
+            new HashSet<>(List.of(tasks))
         );
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
index a63b2e7c7ca..e20ba62e5a5 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
@@ -21,13 +21,14 @@ import org.junit.jupiter.api.Test;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.common.utils.Utils.mkSet;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -81,7 +82,7 @@ public class MockAssignorTest {
         final MemberAssignment testMember = result.members().get("test_member");
         assertNotNull(testMember);
         assertEquals(mkMap(
-            mkEntry("test-subtopology", mkSet(0, 1, 2, 3))
+            mkEntry("test-subtopology", Set.of(0, 1, 2, 3))
         ), testMember.activeTasks());
     }
 
@@ -121,12 +122,12 @@ public class MockAssignorTest {
         );
 
         final Map<String, Set<Integer>> expected1 = mkMap(
-            mkEntry("test-subtopology1", mkSet(1, 3)),
-            mkEntry("test-subtopology2", mkSet(1, 3))
+            mkEntry("test-subtopology1", Set.of(1, 3)),
+            mkEntry("test-subtopology2", Set.of(1, 3))
         );
         final Map<String, Set<Integer>> expected2 = mkMap(
-            mkEntry("test-subtopology1", mkSet(0, 2)),
-            mkEntry("test-subtopology2", mkSet(0, 2))
+            mkEntry("test-subtopology1", Set.of(0, 2)),
+            mkEntry("test-subtopology2", Set.of(0, 2))
         );
 
         assertEquals(2, result.members().size());
@@ -145,8 +146,8 @@ public class MockAssignorTest {
             Optional.empty(),
             Optional.empty(),
             mkMap(
-                mkEntry("test-subtopology1", mkSet(0, 2, 3)),
-                mkEntry("test-subtopology2", mkSet(0))
+                mkEntry("test-subtopology1", new HashSet<>(List.of(0, 2, 3))),
+                mkEntry("test-subtopology2", new HashSet<>(List.of(0)))
             ),
             Collections.emptyMap(),
             Collections.emptyMap(),
@@ -159,8 +160,8 @@ public class MockAssignorTest {
             Optional.empty(),
             Optional.empty(),
             mkMap(
-                mkEntry("test-subtopology1", mkSet(1)),
-                mkEntry("test-subtopology2", mkSet(3))
+                mkEntry("test-subtopology1", new HashSet<>(List.of(1))),
+                mkEntry("test-subtopology2", new HashSet<>(List.of(3)))
             ),
             Collections.emptyMap(),
             Collections.emptyMap(),
@@ -183,12 +184,12 @@ public class MockAssignorTest {
         assertNotNull(testMember1);
         assertNotNull(testMember2);
         assertEquals(mkMap(
-            mkEntry("test-subtopology1", mkSet(0, 2, 3)),
-            mkEntry("test-subtopology2", mkSet(0))
+            mkEntry("test-subtopology1", Set.of(0, 2, 3)),
+            mkEntry("test-subtopology2", Set.of(0))
         ), testMember1.activeTasks());
         assertEquals(mkMap(
-            mkEntry("test-subtopology1", mkSet(1)),
-            mkEntry("test-subtopology2", mkSet(1, 2, 3))
+            mkEntry("test-subtopology1", Set.of(1)),
+            mkEntry("test-subtopology2", Set.of(1, 2, 3))
         ), testMember2.activeTasks());
     }
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java
index 6455fb5cd68..5ecc89158d9 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/StickyTaskAssignorTest.java
@@ -34,7 +34,6 @@ import java.util.stream.Stream;
 import static java.util.Arrays.asList;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.apache.kafka.common.utils.Utils.mkSet;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -69,7 +68,7 @@ public class StickyTaskAssignorTest {
             assertEquals(1, testMember.activeTasks().size());
             actualActiveTasks.addAll(testMember.activeTasks().get("test-subtopology"));
         }
-        assertEquals(mkSet(0, 1, 2), actualActiveTasks);
+        assertEquals(Set.of(0, 1, 2), actualActiveTasks);
     }
 
     @Test
@@ -100,13 +99,13 @@ public class StickyTaskAssignorTest {
         assertEquals(1, getAllActiveTaskCount(result, "member3_1"));
         assertEquals(1, getAllActiveTaskCount(result, "member3_2"));
 
-        assertEquals(mkMap(mkEntry("test-subtopology1", mkSet(0, 1, 2)), mkEntry("test-subtopology2", mkSet(0, 1, 2))),
+        assertEquals(mkMap(mkEntry("test-subtopology1", Set.of(0, 1, 2)), mkEntry("test-subtopology2", Set.of(0, 1, 2))),
                 mergeAllActiveTasks(result, "member1_1", "member1_2", "member2_1", "member2_2", "member3_1", "member3_2"));
     }
 
     @Test
     public void shouldAssignTopicGroupIdEvenlyAcrossClientsWithStandByTasks() {
-        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology1", mkSet(0, 1, 2)), mkEntry("test-subtopology2", mkSet(0, 1, 2)));
+        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology1", Set.of(0, 1, 2)), mkEntry("test-subtopology2", Set.of(0, 1, 2)));
         final AssignmentMemberSpec memberSpec11 = createAssignmentMemberSpec("process1");
         final AssignmentMemberSpec memberSpec12 = createAssignmentMemberSpec("process1");
 
@@ -187,7 +186,7 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldMigrateActiveTasksToNewProcessWithoutChangingAllAssignments() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(0, 2))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
 
@@ -252,8 +251,8 @@ public class StickyTaskAssignorTest {
     @Test
     public void shouldAssignTasksEvenlyWithUnequalTopicGroupSizes() {
         final Map<String, Set<Integer>> activeTasks = mkMap(
-                mkEntry("test-subtopology1", mkSet(0, 1, 2, 3, 4, 5)),
-                mkEntry("test-subtopology2", mkSet(0)));
+                mkEntry("test-subtopology1", Set.of(0, 1, 2, 3, 4, 5)),
+                mkEntry("test-subtopology2", Set.of(0)));
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", activeTasks, Collections.emptyMap());
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
 
@@ -443,7 +442,7 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldAssignStandbyTasksToDifferentClientThanCorrespondingActiveTaskIsAssignedTo() {
-        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3)));
+        final Map<String, Set<Integer>> tasks = mkMap(mkEntry("test-subtopology", Set.of(0, 1, 2, 3)));
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Collections.singleton(0))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Collections.singleton(1))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Collections.singleton(2))), Collections.emptyMap());
@@ -508,9 +507,9 @@ public class StickyTaskAssignorTest {
         );
 
 
-        assertEquals(mkSet(1, 2), new HashSet<>(getAllStandbyTaskIds(result, "member1")));
-        assertEquals(mkSet(0, 2), new HashSet<>(getAllStandbyTaskIds(result, "member2")));
-        assertEquals(mkSet(0, 1), new HashSet<>(getAllStandbyTaskIds(result, "member3")));
+        assertEquals(Set.of(1, 2), new HashSet<>(getAllStandbyTaskIds(result, "member1")));
+        assertEquals(Set.of(0, 2), new HashSet<>(getAllStandbyTaskIds(result, "member2")));
+        assertEquals(Set.of(0, 1), new HashSet<>(getAllStandbyTaskIds(result, "member3")));
     }
 
     @Test
@@ -549,8 +548,8 @@ public class StickyTaskAssignorTest {
 
 
 
-        assertEquals(mkSet(0, 1, 2), new HashSet<>(getAllActiveTaskIds(result)));
-        assertEquals(mkSet(0, 1, 2), new HashSet<>(getAllStandbyTaskIds(result)));
+        assertEquals(Set.of(0, 1, 2), new HashSet<>(getAllActiveTaskIds(result)));
+        assertEquals(Set.of(0, 1, 2), new HashSet<>(getAllStandbyTaskIds(result)));
     }
 
     @Test
@@ -593,7 +592,7 @@ public class StickyTaskAssignorTest {
         );
 
         assertEquals(3, getAllActiveTaskIds(result, "member1", "member2", "member3", "member4", "member5", "member6").size());
-        assertEquals(mkSet(0, 1, 2), getActiveTasks(result, "test-subtopology", "member1", "member2", "member3", "member4", "member5", "member6"));
+        assertEquals(Set.of(0, 1, 2), getActiveTasks(result, "test-subtopology", "member1", "member2", "member3", "member4", "member5", "member6"));
     }
 
     @Test
@@ -669,9 +668,9 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousActiveTasks() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(1, 2))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(3))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Set.of(3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Set.of(0))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
 
         final List<String> allMemberIds = asList("member1", "member2", "member3", "member4");
@@ -698,9 +697,9 @@ public class StickyTaskAssignorTest {
     @Test
     public void shouldNotHaveSameAssignmentOnAnyTwoHostsWhenThereArePreviousStandbyTasks() {
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
-                mkMap(mkEntry("test-subtopology", mkSet(1, 2))), mkMap(mkEntry("test-subtopology", mkSet(3, 0))));
+                mkMap(mkEntry("test-subtopology", Set.of(1, 2))), mkMap(mkEntry("test-subtopology", Set.of(3, 0))));
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
-                mkMap(mkEntry("test-subtopology", mkSet(3, 0))), mkMap(mkEntry("test-subtopology", mkSet(1, 2))));
+                mkMap(mkEntry("test-subtopology", Set.of(3, 0))), mkMap(mkEntry("test-subtopology", Set.of(1, 2))));
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
         final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
 
@@ -728,7 +727,7 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldReBalanceTasksAcrossAllClientsWhenCapacityAndTaskCountTheSame() {
-        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Set.of(0, 1, 2, 3))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
         final AssignmentMemberSpec memberSpec4 = createAssignmentMemberSpec("process4");
@@ -748,7 +747,7 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldReBalanceTasksAcrossClientsWhenCapacityLessThanTaskCount() {
-        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3", mkMap(mkEntry("test-subtopology", Set.of(0, 1, 2, 3))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1");
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
 
@@ -766,7 +765,7 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldRebalanceTasksToClientsBasedOnCapacity() {
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(0, 3, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Set.of(0, 3, 2))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec31 = createAssignmentMemberSpec("process3");
         final AssignmentMemberSpec memberSpec32 = createAssignmentMemberSpec("process3");
 
@@ -783,8 +782,8 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldMoveMinimalNumberOfTasksWhenPreviouslyAboveCapacityAndNewClientAdded() {
-        final Set<Integer> p1PrevTasks = mkSet(0, 2);
-        final Set<Integer> p2PrevTasks = mkSet(1, 3);
+        final Set<Integer> p1PrevTasks = Set.of(0, 2);
+        final Set<Integer> p2PrevTasks = Set.of(1, 3);
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", p1PrevTasks)), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", p2PrevTasks)), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
@@ -796,12 +795,10 @@ public class StickyTaskAssignorTest {
                 new TopologyDescriberImpl(4, false)
         );
 
-
-
         assertEquals(1, getAllActiveTaskCount(result, "member3"));
         final List<Integer> p3ActiveTasks = getAllActiveTaskIds(result, "member3");
 
-        if (p1PrevTasks.removeAll(p3ActiveTasks)) {
+        if (new HashSet<>(p1PrevTasks).removeAll(p3ActiveTasks)) {
             assertEquals(p2PrevTasks, new HashSet<>(getAllActiveTaskIds(result, "member2")));
         } else {
             assertEquals(p1PrevTasks, new HashSet<>(getAllActiveTaskIds(result, "member1")));
@@ -810,8 +807,8 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldNotMoveAnyTasksWhenNewTasksAdded() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(2, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(0, 1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Set.of(2, 3))), Collections.emptyMap());
 
         final Map<String, AssignmentMemberSpec> members = mkMap(
                 mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2));
@@ -832,8 +829,8 @@ public class StickyTaskAssignorTest {
     @Test
     public void shouldAssignNewTasksToNewClientWhenPreviousTasksAssignedToOldClients() {
 
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(2, 1))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(0, 3))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(2, 1))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Set.of(0, 3))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3");
 
 
@@ -860,17 +857,17 @@ public class StickyTaskAssignorTest {
     @Test
     public void shouldAssignTasksNotPreviouslyActiveToNewClient() {
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
-                mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
-                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+                mkMap(mkEntry("test-subtopology0", Set.of(1)), mkEntry("test-subtopology1", Set.of(2, 3))),
+                mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(0, 1, 3))));
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
-                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
-                mkMap(mkEntry("test-subtopology0", mkSet(1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+                mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(2))),
+                mkMap(mkEntry("test-subtopology0", Set.of(1, 2, 3)), mkEntry("test-subtopology1", Set.of(0, 2, 3)), mkEntry("test-subtopology2", Set.of(0, 1, 3))));
         final AssignmentMemberSpec memberSpec3 = createAssignmentMemberSpec("process3",
-                mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
-                mkMap(mkEntry("test-subtopology0", mkSet(2)), mkEntry("test-subtopology1", mkSet(2))));
+                mkMap(mkEntry("test-subtopology2", Set.of(0, 1, 3))),
+                mkMap(mkEntry("test-subtopology0", Set.of(2)), mkEntry("test-subtopology1", Set.of(2))));
         final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("process4",
                Collections.emptyMap(),
-                mkMap(mkEntry("test-subtopology0", mkSet(0, 1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 1, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 2, 3))));
+                mkMap(mkEntry("test-subtopology0", Set.of(0, 1, 2, 3)), mkEntry("test-subtopology1", Set.of(0, 1, 2, 3)), mkEntry("test-subtopology2", Set.of(0, 1, 2, 3))));
 
         final Map<String, AssignmentMemberSpec> members = mkMap(
                 mkEntry("member1", memberSpec1), mkEntry("member2", memberSpec2), mkEntry("member3", memberSpec3), mkEntry("newMember", newMemberSpec));
@@ -879,34 +876,34 @@ public class StickyTaskAssignorTest {
                 new TopologyDescriberImpl(4, false)
         );
 
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(1)), mkEntry("test-subtopology1", Set.of(2, 3))),
                 getAllActiveTasks(result, "member1"));
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(2))),
                 getAllActiveTasks(result, "member2"));
-        assertEquals(mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
+        assertEquals(mkMap(mkEntry("test-subtopology2", Set.of(0, 1, 3))),
                 getAllActiveTasks(result, "member3"));
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(2, 3)), mkEntry("test-subtopology1", Set.of(0))),
                 getAllActiveTasks(result, "newMember"));
     }
 
     @Test
     public void shouldAssignTasksNotPreviouslyActiveToMultipleNewClients() {
         final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1",
-                mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
-                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+                mkMap(mkEntry("test-subtopology0", Set.of(1)), mkEntry("test-subtopology1", Set.of(2, 3))),
+                mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(0, 1, 3))));
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2",
-                mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
-                mkMap(mkEntry("test-subtopology0", mkSet(1, 2, 3)), mkEntry("test-subtopology1", mkSet(0, 2, 3)), mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+                mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(2))),
+                mkMap(mkEntry("test-subtopology0", Set.of(1, 2, 3)), mkEntry("test-subtopology1", Set.of(0, 2, 3)), mkEntry("test-subtopology2", Set.of(0, 1, 3))));
 
 
         final AssignmentMemberSpec bounce1 = createAssignmentMemberSpec("bounce1",
                 Collections.emptyMap(),
-                mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))));
+                mkMap(mkEntry("test-subtopology2", Set.of(0, 1, 3))));
 
 
         final AssignmentMemberSpec bounce2 = createAssignmentMemberSpec("bounce2",
                 Collections.emptyMap(),
-                mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))));
+                mkMap(mkEntry("test-subtopology0", Set.of(2, 3)), mkEntry("test-subtopology1", Set.of(0))));
 
 
 
@@ -918,19 +915,19 @@ public class StickyTaskAssignorTest {
         );
 
 
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(1)), mkEntry("test-subtopology1", mkSet(2, 3))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(1)), mkEntry("test-subtopology1", Set.of(2, 3))),
                 getAllActiveTasks(result, "member1"));
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(0)), mkEntry("test-subtopology1", mkSet(1)), mkEntry("test-subtopology2", mkSet(2))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(0)), mkEntry("test-subtopology1", Set.of(1)), mkEntry("test-subtopology2", Set.of(2))),
                 getAllActiveTasks(result, "member2"));
-        assertEquals(mkMap(mkEntry("test-subtopology2", mkSet(0, 1, 3))),
+        assertEquals(mkMap(mkEntry("test-subtopology2", Set.of(0, 1, 3))),
                 getAllActiveTasks(result, "bounce_member1"));
-        assertEquals(mkMap(mkEntry("test-subtopology0", mkSet(2, 3)), mkEntry("test-subtopology1", mkSet(0))),
+        assertEquals(mkMap(mkEntry("test-subtopology0", Set.of(2, 3)), mkEntry("test-subtopology1", Set.of(0))),
                 getAllActiveTasks(result, "bounce_member2"));
     }
 
     @Test
     public void shouldAssignTasksToNewClient() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(1, 2))), Collections.emptyMap());
         final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2");
 
         final Map<String, AssignmentMemberSpec> members = mkMap(
@@ -945,8 +942,8 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldAssignTasksToNewClientWithoutFlippingAssignmentBetweenExistingClients() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", mkSet(3, 4, 5))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(0, 1, 2))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", mkMap(mkEntry("test-subtopology", Set.of(3, 4, 5))), Collections.emptyMap());
         final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("process3");
 
         final Map<String, AssignmentMemberSpec> members = mkMap(
@@ -973,8 +970,8 @@ public class StickyTaskAssignorTest {
 
     @Test
     public void shouldAssignTasksToNewClientWithoutFlippingAssignmentBetweenExistingAndBouncedClients() {
-        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", mkSet(0, 1, 2, 6))), Collections.emptyMap());
-        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", mkSet(3, 4, 5))));
+        final AssignmentMemberSpec memberSpec1 = createAssignmentMemberSpec("process1", mkMap(mkEntry("test-subtopology", Set.of(0, 1, 2, 6))), Collections.emptyMap());
+        final AssignmentMemberSpec memberSpec2 = createAssignmentMemberSpec("process2", Collections.emptyMap(), mkMap(mkEntry("test-subtopology", Set.of(3, 4, 5))));
         final AssignmentMemberSpec newMemberSpec = createAssignmentMemberSpec("newProcess");
 
         final Map<String, AssignmentMemberSpec> members = mkMap(


(kafka) 20/42: Resolve conflicts from 11/25 trunk rebase - Implement DescribeStreamsGroup RPC handling

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 6a4aa0cf1d40d0585efd4b13f21d9ed6691baa7f
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Thu Aug 15 15:32:21 2024 +0200

    Resolve conflicts from 11/25 trunk rebase - Implement DescribeStreamsGroup RPC handling
    
    Implement the DescribeStreamsGroup RPC handling for KIP-1071.
---
 .../org/apache/kafka/common/protocol/ApiKeys.java  |   2 +-
 .../kafka/common/requests/AbstractRequest.java     |   2 +
 .../kafka/common/requests/AbstractResponse.java    |   2 +
 .../requests/StreamsGroupDescribeRequest.java      |  98 +++++++++
 .../requests/StreamsGroupDescribeResponse.java     |  76 +++++++
 .../message/StreamsGroupDescribeRequest.json       |   2 +-
 .../message/StreamsGroupDescribeResponse.json      |  10 +-
 .../message/StreamsGroupHeartbeatRequest.json      |   2 +-
 .../message/StreamsGroupInitializeRequest.json     |   2 +-
 .../StreamsGroupHeartbeatRequestManagerTest.java   |   3 +-
 .../kafka/common/requests/RequestResponseTest.java |  57 +++---
 .../group/GroupCoordinatorAdapter.scala            |  11 +-
 core/src/main/scala/kafka/server/KafkaApis.scala   |  66 +++++-
 core/src/main/scala/kafka/server/KafkaConfig.scala |   7 +
 .../scala/unit/kafka/server/KafkaApisTest.scala    | 224 +++++++++++++++++----
 .../scala/unit/kafka/server/KafkaConfigTest.scala  |   6 +
 gradle/spotbugs-exclude.xml                        |   5 +
 .../kafka/coordinator/group/GroupCoordinator.java  |  14 ++
 .../coordinator/group/GroupCoordinatorService.java |  53 +++++
 .../coordinator/group/GroupCoordinatorShard.java   |  16 ++
 .../coordinator/group/GroupMetadataManager.java    |  35 +++-
 .../group/streams/CurrentAssignmentBuilder.java    |   8 +-
 .../coordinator/group/streams/StreamsGroup.java    | 109 ++--------
 .../group/streams/StreamsGroupMember.java          | 109 +++++-----
 .../coordinator/group/streams/StreamsTopology.java |  33 +++
 .../group/streams/TargetAssignmentBuilder.java     |  19 --
 .../group/GroupCoordinatorServiceTest.java         | 138 +++++++++++++
 .../group/GroupCoordinatorShardTest.java           |   2 +-
 .../group/GroupMetadataManagerTest.java            | 112 +++++++++++
 .../group/GroupMetadataManagerTestContext.java     |  94 ++++++++-
 .../group/streams/StreamsGroupBuilder.java         | 101 ++++++++++
 .../group/streams/StreamsGroupMemberTest.java      | 127 +++++++++++-
 .../group/streams/StreamsGroupTest.java            |   4 +-
 .../group/streams/StreamsTopologyTest.java         | 182 +++++++++++++++++
 .../group/streams/TargetAssignmentBuilderTest.java |   5 +-
 35 files changed, 1463 insertions(+), 273 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index a53b082c997..345b9b808a8 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -131,8 +131,8 @@ public enum ApiKeys {
     WRITE_SHARE_GROUP_STATE(ApiMessageType.WRITE_SHARE_GROUP_STATE, true),
     DELETE_SHARE_GROUP_STATE(ApiMessageType.DELETE_SHARE_GROUP_STATE, true),
     READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
-    STREAMS_GROUP_HEARTBEAT(ApiMessageType.STREAMS_GROUP_HEARTBEAT),
     STREAMS_GROUP_INITIALIZE(ApiMessageType.STREAMS_GROUP_INITIALIZE),
+    STREAMS_GROUP_HEARTBEAT(ApiMessageType.STREAMS_GROUP_HEARTBEAT),
     STREAMS_GROUP_DESCRIBE(ApiMessageType.STREAMS_GROUP_DESCRIBE);
     
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
index 3d99419987d..4e5d21251f8 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractRequest.java
@@ -354,6 +354,8 @@ public abstract class AbstractRequest implements AbstractRequestResponse {
                 return StreamsGroupHeartbeatRequest.parse(buffer, apiVersion);
             case STREAMS_GROUP_INITIALIZE:
                 return StreamsGroupInitializeRequest.parse(buffer, apiVersion);
+            case STREAMS_GROUP_DESCRIBE:
+                return StreamsGroupDescribeRequest.parse(buffer, apiVersion);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseRequest`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
index 9e25cfd99da..25f3afe0d5b 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/AbstractResponse.java
@@ -291,6 +291,8 @@ public abstract class AbstractResponse implements AbstractRequestResponse {
                 return StreamsGroupHeartbeatResponse.parse(responseBuffer, version);
             case STREAMS_GROUP_INITIALIZE:
                 return StreamsGroupInitializeResponse.parse(responseBuffer, version);
+            case STREAMS_GROUP_DESCRIBE:
+                return StreamsGroupDescribeResponse.parse(responseBuffer, version);
             default:
                 throw new AssertionError(String.format("ApiKey %s is not currently handled in `parseResponse`, the " +
                         "code should be updated to do so.", apiKey));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java
new file mode 100644
index 00000000000..2a3834d16a8
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java
@@ -0,0 +1,98 @@
+/*
+ * 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 org.apache.kafka.common.requests;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.kafka.common.message.StreamsGroupDescribeRequestData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+public class StreamsGroupDescribeRequest extends AbstractRequest {
+
+    public static class Builder extends AbstractRequest.Builder<StreamsGroupDescribeRequest> {
+
+        private final StreamsGroupDescribeRequestData data;
+
+        public Builder(StreamsGroupDescribeRequestData data) {
+            this(data, false);
+        }
+
+        public Builder(StreamsGroupDescribeRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_GROUP_DESCRIBE, enableUnstableLastVersion);
+            this.data = data;
+        }
+
+        @Override
+        public StreamsGroupDescribeRequest build(short version) {
+            return new StreamsGroupDescribeRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final StreamsGroupDescribeRequestData data;
+
+    public StreamsGroupDescribeRequest(StreamsGroupDescribeRequestData data, short version) {
+        super(ApiKeys.STREAMS_GROUP_DESCRIBE, version);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsGroupDescribeResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        StreamsGroupDescribeResponseData data = new StreamsGroupDescribeResponseData()
+            .setThrottleTimeMs(throttleTimeMs);
+        // Set error for each group
+        this.data.groupIds().forEach(
+            groupId -> data.groups().add(
+                new StreamsGroupDescribeResponseData.DescribedGroup()
+                    .setGroupId(groupId)
+                    .setErrorCode(Errors.forException(e).code())
+            )
+        );
+        return new StreamsGroupDescribeResponse(data);
+    }
+
+    @Override
+    public StreamsGroupDescribeRequestData data() {
+        return data;
+    }
+
+    public static StreamsGroupDescribeRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupDescribeRequest(
+            new StreamsGroupDescribeRequestData(new ByteBufferAccessor(buffer), version),
+            version
+        );
+    }
+
+    public static List<StreamsGroupDescribeResponseData.DescribedGroup> getErrorDescribedGroupList(
+        List<String> groupIds,
+        Errors error
+    ) {
+        return groupIds.stream()
+            .map(groupId -> new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupId(groupId)
+                .setErrorCode(error.code())
+            ).collect(Collectors.toList());
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java
new file mode 100644
index 00000000000..cf1d5529623
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java
@@ -0,0 +1,76 @@
+/*
+ * 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 org.apache.kafka.common.requests;
+
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+/**
+ * Possible error codes.
+ *
+ * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
+ * - {@link Errors#NOT_COORDINATOR}
+ * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
+ * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
+ * - {@link Errors#INVALID_REQUEST}
+ * - {@link Errors#INVALID_GROUP_ID}
+ * - {@link Errors#GROUP_ID_NOT_FOUND}
+ */
+public class StreamsGroupDescribeResponse extends AbstractResponse {
+
+    private final StreamsGroupDescribeResponseData data;
+
+    public StreamsGroupDescribeResponse(StreamsGroupDescribeResponseData data) {
+        super(ApiKeys.STREAMS_GROUP_DESCRIBE);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsGroupDescribeResponseData data() {
+        return data;
+    }
+
+    @Override
+    public Map<Errors, Integer> errorCounts() {
+        HashMap<Errors, Integer> counts = new HashMap<>();
+        data.groups().forEach(
+            group -> updateErrorCounts(counts, Errors.forCode(group.errorCode()))
+        );
+        return counts;
+    }
+
+    @Override
+    public int throttleTimeMs() {
+        return data.throttleTimeMs();
+    }
+
+    @Override
+    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
+        data.setThrottleTimeMs(throttleTimeMs);
+    }
+
+    public static StreamsGroupDescribeResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsGroupDescribeResponse(
+            new StreamsGroupDescribeResponseData(new ByteBufferAccessor(buffer), version)
+        );
+    }
+}
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
index 17b4abac9d2..b7047141e8a 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
@@ -16,7 +16,7 @@
 {
   "apiKey": 90,
   "type": "request",
-  "listeners": ["broker"],
+  "listeners": ["broker", "zkBroker"],
   "name": "StreamsGroupDescribeRequest",
   "validVersions": "0",
   "flexibleVersions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index 1093100992f..9cf580f0441 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -45,8 +45,8 @@
           "about": "The group epoch." },
         { "name": "AssignmentEpoch", "type": "int32", "versions": "0+",
           "about": "The assignment epoch." },
-        { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
-          "about": "The sub-topologies of the streams application.",
+        { "name":  "Topology", "type": "[]Subtopology", "versions": "0+", "nullableVersions": "0+", "default": "null",
+          "about": "The sub-topologies of the streams application. Null if uninitialized.",
           "fields": [
             { "name": "Subtopology", "type": "string", "versions": "0+",
               "about": "String to uniquely identify the sub-topology." },
@@ -54,8 +54,8 @@
               "about": "The topics the topology reads from." },
             { "name": "SourceTopicRegex", "type": "string", "versions": "0+",
               "about": "The regular expressions identifying topics the topology reads from." },
-            { "name": "SinkTopics", "type": "[]string", "versions": "0+",
-              "about": "The topics the topology writes to." },
+            { "name": "RepartitionSinkTopics", "type": "[]string", "versions": "0+",
+              "about": "The repartition topics the topology writes to." },
             { "name": "StateChangelogTopics", "type": "[]TopicInfo", "versions": "0+",
               "about": "The set of state changelog topics associated with this sub-topology. Created automatically." },
             { "name": "RepartitionSourceTopics", "type": "[]TopicInfo", "versions": "0+",
@@ -82,7 +82,7 @@
             { "name": "TopologyId", "type": "string", "versions": "0+",
               "about": "The ID of the topology. Must be non-empty." },
 
-            { "name": "ProcessId", "type": "uuid", "versions": "0+",
+            { "name": "ProcessId", "type": "string", "versions": "0+",
               "about": "Identity of the streams instance that may have multiple clients. " },
             { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
               "about": "Used for rack-aware assignment algorithm." },
diff --git a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
index ac765b2269c..7f829f1e410 100644
--- a/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupHeartbeatRequest.json
@@ -16,7 +16,7 @@
 {
   "apiKey": 89,
   "type": "request",
-  "listeners": ["broker"],
+  "listeners": ["broker", "zkBroker"],
   "name": "StreamsGroupHeartbeatRequest",
   "validVersions": "0",
   "flexibleVersions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
index 169629fb2c0..602b557e3e9 100644
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
@@ -16,7 +16,7 @@
 {
   "apiKey": 88,
   "type": "request",
-  "listeners": ["broker"],
+  "listeners": ["broker", "zkBroker"],
   "name": "StreamsGroupInitializeRequest",
   "validVersions": "0",
   "flexibleVersions": "0+",
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index bc91fc5df83..f4c67e1d9b9 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -214,7 +214,8 @@ class StreamsGroupHeartbeatRequestManagerTest {
         StreamsGroupHeartbeatRequest request = (StreamsGroupHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
 
         assertEquals(processID.toString(), request.data().processId());
-        assertEquals(endPoint, request.data().userEndpoint());
+        assertEquals(endPoint.host, request.data().userEndpoint().host());
+        assertEquals(endPoint.port, request.data().userEndpoint().port());
         assertEquals(1, request.data().clientTags().size());
         assertEquals("clientTag1", request.data().clientTags().get(0).key());
         assertEquals("value2", request.data().clientTags().get(0).value());
diff --git a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
index 5bf5baf7c8b..1e5a1c4c864 100644
--- a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
@@ -234,6 +234,8 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaPartitionState;
 import org.apache.kafka.common.message.StopReplicaRequestData.StopReplicaTopicState;
 import org.apache.kafka.common.message.StopReplicaResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeRequestData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -1127,8 +1129,9 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateRequest(version);
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateRequest(version);
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryRequest(version);
-            case STREAMS_GROUP_HEARTBEAT: return createStreamsHeartbeatRequest(version);
-            case STREAMS_GROUP_INITIALIZE: return createStreamsInitializeRequest(version);
+            case STREAMS_GROUP_HEARTBEAT: return createStreamsGroupHeartbeatRequest(version);
+            case STREAMS_GROUP_INITIALIZE: return createStreamsGroupInitializeRequest(version);
+            case STREAMS_GROUP_DESCRIBE: return createStreamsGroupDescribeRequest(version);
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -1223,8 +1226,9 @@ public class RequestResponseTest {
             case WRITE_SHARE_GROUP_STATE: return createWriteShareGroupStateResponse();
             case DELETE_SHARE_GROUP_STATE: return createDeleteShareGroupStateResponse();
             case READ_SHARE_GROUP_STATE_SUMMARY: return createReadShareGroupStateSummaryResponse();
-            case STREAMS_GROUP_HEARTBEAT: return createStreamsHeartbeatResponse();
-            case STREAMS_GROUP_INITIALIZE: return createStreamsInitializeResponse();
+            case STREAMS_GROUP_HEARTBEAT: return createStreamsGroupHeartbeatResponse();
+            case STREAMS_GROUP_INITIALIZE: return createStreamsGroupInitializeResponse();
+            case STREAMS_GROUP_DESCRIBE: return createStreamsGroupDescribeResponse();
             default: throw new IllegalArgumentException("Unknown API key " + apikey);
         }
     }
@@ -4023,35 +4027,42 @@ public class RequestResponseTest {
         return new ReadShareGroupStateSummaryResponse(data);
     }
 
-//    private AbstractRequest createStreamsPrepareAssignmentRequest(final short version) {
-//        return new StreamsPrepareAssignmentRequest.Builder(new StreamsPrepareAssignmentRequestData()).build(version);
-//    }
-//
-//    private AbstractRequest createStreamsInstallAssignmentRequest(final short version) {
-//        return new StreamsInstallAssignmentRequest.Builder(new StreamsInstallAssignmentRequestData()).build(version);
-//    }
+    private AbstractRequest createStreamsGroupDescribeRequest(final short version) {
+        return new StreamsGroupDescribeRequest.Builder(new StreamsGroupDescribeRequestData()
+            .setGroupIds(Collections.singletonList("group"))
+            .setIncludeAuthorizedOperations(false)).build(version);
+    }
 
-    private AbstractRequest createStreamsInitializeRequest(final short version) {
+    private AbstractRequest createStreamsGroupInitializeRequest(final short version) {
         return new StreamsGroupInitializeRequest.Builder(new StreamsGroupInitializeRequestData()).build(version);
     }
 
-    private AbstractRequest createStreamsHeartbeatRequest(final short version) {
+    private AbstractRequest createStreamsGroupHeartbeatRequest(final short version) {
         return new StreamsGroupHeartbeatRequest.Builder(new StreamsGroupHeartbeatRequestData()).build(version);
     }
 
-//    private AbstractResponse createStreamsPrepareAssignmentResponse() {
-//        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData());
-//    }
-//
-//    private AbstractResponse createStreamsInstallAssignmentResponse() {
-//        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData());
-//    }
-//
-    private AbstractResponse createStreamsInitializeResponse() {
+    private AbstractResponse createStreamsGroupDescribeResponse() {
+        StreamsGroupDescribeResponseData data = new StreamsGroupDescribeResponseData()
+            .setGroups(Collections.singletonList(
+                new StreamsGroupDescribeResponseData.DescribedGroup()
+                    .setGroupId("group")
+                    .setErrorCode((short) 0)
+                    .setErrorMessage(Errors.forCode((short) 0).message())
+                    .setGroupState("EMPTY")
+                    .setGroupEpoch(0)
+                    .setAssignmentEpoch(0)
+                    .setMembers(new ArrayList<>(0))
+                    .setTopology(new ArrayList<>(0))
+            ))
+            .setThrottleTimeMs(1000);
+        return new StreamsGroupDescribeResponse(data);
+    }
+
+    private AbstractResponse createStreamsGroupInitializeResponse() {
         return new StreamsGroupInitializeResponse(new StreamsGroupInitializeResponseData());
     }
 
-    private AbstractResponse createStreamsHeartbeatResponse() {
+    private AbstractResponse createStreamsGroupHeartbeatResponse() {
         return new StreamsGroupHeartbeatResponse(new StreamsGroupHeartbeatResponseData());
     }
 
diff --git a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
index 74f30f0d765..a48b2c6ffc8 100644
--- a/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
+++ b/core/src/main/scala/kafka/coordinator/group/GroupCoordinatorAdapter.scala
@@ -18,7 +18,7 @@ package kafka.coordinator.group
 
 import kafka.server.{KafkaConfig, ReplicaManager}
 import org.apache.kafka.common.{TopicIdPartition, TopicPartition, Uuid}
-import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
+import org.apache.kafka.common.message.{ConsumerGroupDescribeResponseData, ConsumerGroupHeartbeatRequestData, ConsumerGroupHeartbeatResponseData, DeleteGroupsResponseData, DescribeGroupsResponseData, HeartbeatRequestData, HeartbeatResponseData, JoinGroupRequestData, JoinGroupResponseData, LeaveGroupRequestData, LeaveGroupResponseData, ListGroupsRequestData, ListGroupsResponseData, OffsetCommitRequestData, OffsetCommitResponseData, OffsetDeleteRequestData, OffsetDeleteResponseData, Offset [...]
 import org.apache.kafka.common.metrics.Metrics
 import org.apache.kafka.common.protocol.{ApiKeys, Errors}
 import org.apache.kafka.common.record.RecordBatch
@@ -672,6 +672,15 @@ private[group] class GroupCoordinatorAdapter(
     ))
   }
 
+  override def streamsGroupDescribe(
+    context: RequestContext,
+    groupIds: util.List[String]
+  ): CompletableFuture[util.List[StreamsGroupDescribeResponseData.DescribedGroup]] = {
+    FutureUtils.failedFuture(Errors.UNSUPPORTED_VERSION.exception(
+      s"The old group coordinator does not support ${ApiKeys.STREAMS_GROUP_DESCRIBE.name} API."
+    ))
+  }
+
   override def shareGroupDescribe(
     context: RequestContext,
     groupIds: util.List[String]
diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 9b22b16a55f..d3bfd420ace 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -276,6 +276,7 @@ class KafkaApis(val requestChannel: RequestChannel,
         case ApiKeys.WRITE_SHARE_GROUP_STATE => handleWriteShareGroupStateRequest(request)
         case ApiKeys.DELETE_SHARE_GROUP_STATE => handleDeleteShareGroupStateRequest(request)
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY => handleReadShareGroupStateSummaryRequest(request)
+        case ApiKeys.STREAMS_GROUP_DESCRIBE => handleStreamsGroupDescribe(request).exceptionally(handleError)
         case ApiKeys.STREAMS_GROUP_INITIALIZE => handleStreamsInitialize(request).exceptionally(handleError)
         case ApiKeys.STREAMS_GROUP_HEARTBEAT => handleStreamsHeartbeat(request).exceptionally(handleError)
         case _ => throw new IllegalStateException(s"No handler for request api key ${request.header.apiKey}")
@@ -3885,12 +3886,16 @@ class KafkaApis(val requestChannel: RequestChannel,
 
   }
 
+  private def isStreamsGroupProtocolEnabled(): Boolean = {
+    config.groupCoordinatorRebalanceProtocols.contains(Group.GroupType.STREAMS)
+  }
+  
   def handleStreamsInitialize(request: RequestChannel.Request): CompletableFuture[Unit] = {
     val streamsInitializeRequest = request.body[StreamsGroupInitializeRequest]
 
     // TODO: Check ACLs on CREATE TOPIC & DESCRIBE_CONFIGS
 
-    if (!config.isNewGroupCoordinatorEnabled) {
+    if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
       requestHelper.sendMaybeThrottle(request, streamsInitializeRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
@@ -3915,7 +3920,7 @@ class KafkaApis(val requestChannel: RequestChannel,
   def handleStreamsHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
     val streamsHeartbeatRequest = request.body[StreamsGroupHeartbeatRequest]
 
-    if (!config.isNewGroupCoordinatorEnabled) {
+    if (!isStreamsGroupProtocolEnabled()) {
       // The API is not supported by the "old" group coordinator (the default). If the
       // new one is not enabled, we fail directly here.
       requestHelper.sendMaybeThrottle(request, streamsHeartbeatRequest.getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
@@ -3937,6 +3942,63 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
   }
 
+  def handleStreamsGroupDescribe(request: RequestChannel.Request): CompletableFuture[Unit] = {
+    val streamsGroupDescribeRequest = request.body[StreamsGroupDescribeRequest]
+    val includeAuthorizedOperations = streamsGroupDescribeRequest.data.includeAuthorizedOperations
+
+    if (!isStreamsGroupProtocolEnabled()) {
+      // The API is not supported by the "old" group coordinator (the default). If the
+      // new one is not enabled, we fail directly here.
+      requestHelper.sendMaybeThrottle(request, request.body[StreamsGroupDescribeRequest].getErrorResponse(Errors.UNSUPPORTED_VERSION.exception))
+      CompletableFuture.completedFuture[Unit](())
+    } else {
+      val response = new StreamsGroupDescribeResponseData()
+
+      val authorizedGroups = new ArrayBuffer[String]()
+      streamsGroupDescribeRequest.data.groupIds.forEach { groupId =>
+        if (!authHelper.authorize(request.context, DESCRIBE, GROUP, groupId)) {
+          response.groups.add(new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(groupId)
+            .setErrorCode(Errors.GROUP_AUTHORIZATION_FAILED.code)
+          )
+        } else {
+          authorizedGroups += groupId
+        }
+      }
+
+      groupCoordinator.streamsGroupDescribe(
+        request.context,
+        authorizedGroups.asJava
+      ).handle[Unit] { (results, exception) =>
+        if (exception != null) {
+          requestHelper.sendMaybeThrottle(request, streamsGroupDescribeRequest.getErrorResponse(exception))
+        } else {
+          if (includeAuthorizedOperations) {
+            results.forEach { groupResult =>
+              if (groupResult.errorCode == Errors.NONE.code) {
+                groupResult.setAuthorizedOperations(authHelper.authorizedOperations(
+                  request,
+                  new Resource(ResourceType.GROUP, groupResult.groupId)
+                ))
+              }
+            }
+          }
+
+          if (response.groups.isEmpty) {
+            // If the response is empty, we can directly reuse the results.
+            response.setGroups(results)
+          } else {
+            // Otherwise, we have to copy the results into the existing ones.
+            response.groups.addAll(results)
+          }
+
+          requestHelper.sendMaybeThrottle(request, new StreamsGroupDescribeResponse(response))
+        }
+      }
+    }
+
+  }
+  
   def handleGetTelemetrySubscriptionsRequest(request: RequestChannel.Request): Unit = {
     val subscriptionRequest = request.body[GetTelemetrySubscriptionsRequest]
 
diff --git a/core/src/main/scala/kafka/server/KafkaConfig.scala b/core/src/main/scala/kafka/server/KafkaConfig.scala
index 18327a59b55..3b9aa091b8a 100755
--- a/core/src/main/scala/kafka/server/KafkaConfig.scala
+++ b/core/src/main/scala/kafka/server/KafkaConfig.scala
@@ -599,6 +599,13 @@ class KafkaConfig private(doLog: Boolean, val props: util.Map[_, _])
       warn(s"Share groups and the new '${GroupType.SHARE}' rebalance protocol are enabled. " +
         "This is part of the early access of KIP-932 and MUST NOT be used in production.")
     }
+    if (protocols.contains(GroupType.STREAMS)) {
+      if (processRoles.isEmpty) {
+        throw new ConfigException(s"The new '${GroupType.STREAMS}' rebalance protocol is only supported in KRaft cluster.")
+      }
+      warn(s"The new '${GroupType.STREAMS}' rebalance protocol is enabled along with the new group coordinator. " +
+        "This is part of the preview of KIP-1071 and MUST NOT be used in production.")
+    }
     protocols
   }
 
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 917c47aeea2..202149fe747 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11235,42 +11235,48 @@ class KafkaApisTest extends Logging {
   }
 
   @Test
-  def testStreamsInitializeRequest(): Unit = {
-    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+  def testStreamsGroupInitializeRequest(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
     when(groupCoordinator.streamsInitialize(
       requestChannelRequest.context,
-      streamsInitializeRequest
+      streamsGroupInitializeRequest
     )).thenReturn(future)
-    kafkaApis = createKafkaApis(overrideProperties = Map(
-      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
-    ))
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val streamsInitializeResponse = new StreamsGroupInitializeResponseData()
+    val streamsGroupInitializeResponse = new StreamsGroupInitializeResponseData()
 
-    future.complete(streamsInitializeResponse)
+    future.complete(streamsGroupInitializeResponse)
     val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
-    assertEquals(streamsInitializeResponse, response.data)
+    assertEquals(streamsGroupInitializeResponse, response.data)
   }
 
   @Test
-  def testStreamsInitializeRequestFutureFailed(): Unit = {
-    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+  def testStreamsGroupInitializeRequestFutureFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupInitializeResponseData]()
     when(groupCoordinator.streamsInitialize(
       requestChannelRequest.context,
-      streamsInitializeRequest
+      streamsGroupInitializeRequest
     )).thenReturn(future)
-    kafkaApis = createKafkaApis(overrideProperties = Map(
-      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
-    ))
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
@@ -11279,17 +11285,20 @@ class KafkaApisTest extends Logging {
   }
 
   @Test
-  def testStreamsInitializeRequestAuthorizationFailed(): Unit = {
-    val streamsInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
+  def testStreamsGroupInitializeRequestAuthorizationFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupInitializeRequest = new StreamsGroupInitializeRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsInitializeRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupInitializeRequest.Builder(streamsGroupInitializeRequest, true).build())
 
     val authorizer: Authorizer = mock(classOf[Authorizer])
     when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
       .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
     kafkaApis = createKafkaApis(
       authorizer = Some(authorizer),
-      overrideProperties = Map(GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true")
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
@@ -11299,43 +11308,49 @@ class KafkaApisTest extends Logging {
 
 
   @Test
-  def testStreamsHeartbeatRequest(): Unit = {
-    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+  def testStreamsGroupHeartbeatRequest(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
     when(groupCoordinator.streamsHeartbeat(
       requestChannelRequest.context,
-      streamsHeartbeatRequest
+      streamsGroupHeartbeatRequest
     )).thenReturn(future)
-    kafkaApis = createKafkaApis(overrideProperties = Map(
-      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
-    ))
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
-    val streamsHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
+    val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
       .setMemberId("member")
 
-    future.complete(streamsHeartbeatResponse)
+    future.complete(streamsGroupHeartbeatResponse)
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
-    assertEquals(streamsHeartbeatResponse, response.data)
+    assertEquals(streamsGroupHeartbeatResponse, response.data)
   }
 
   @Test
-  def testStreamsHeartbeatRequestFutureFailed(): Unit = {
-    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+  def testStreamsGroupHeartbeatRequestFutureFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
 
-    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val future = new CompletableFuture[StreamsGroupHeartbeatResponseData]()
     when(groupCoordinator.streamsHeartbeat(
       requestChannelRequest.context,
-      streamsHeartbeatRequest
+      streamsGroupHeartbeatRequest
     )).thenReturn(future)
-    kafkaApis = createKafkaApis(overrideProperties = Map(
-      GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true"
-    ))
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
@@ -11344,17 +11359,20 @@ class KafkaApisTest extends Logging {
   }
 
   @Test
-  def testStreamsHeartbeatRequestAuthorizationFailed(): Unit = {
-    val streamsHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+  def testStreamsGroupHeartbeatRequestAuthorizationFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
 
-    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsHeartbeatRequest, true).build())
+    val streamsGroupHeartbeatRequest = new StreamsGroupHeartbeatRequestData().setGroupId("group")
+
+    val requestChannelRequest = buildRequest(new StreamsGroupHeartbeatRequest.Builder(streamsGroupHeartbeatRequest, true).build())
 
     val authorizer: Authorizer = mock(classOf[Authorizer])
     when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
       .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
     kafkaApis = createKafkaApis(
       authorizer = Some(authorizer),
-      overrideProperties = Map(GroupCoordinatorConfig.NEW_GROUP_COORDINATOR_ENABLE_CONFIG -> "true")
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
     )
     kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
 
@@ -11483,6 +11501,128 @@ class KafkaApisTest extends Logging {
     assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.groups.get(0).errorCode)
   }
 
+  @ParameterizedTest
+  @ValueSource(booleans = Array(true, false))
+  def testStreamsGroupDescribe(includeAuthorizedOperations: Boolean): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val groupIds = List("group-id-0", "group-id-1", "group-id-2").asJava
+    val streamsGroupDescribeRequestData = new StreamsGroupDescribeRequestData()
+      .setIncludeAuthorizedOperations(includeAuthorizedOperations)
+    streamsGroupDescribeRequestData.groupIds.addAll(groupIds)
+    val requestChannelRequest = buildRequest(new StreamsGroupDescribeRequest.Builder(streamsGroupDescribeRequestData, true).build())
+
+    val future = new CompletableFuture[util.List[StreamsGroupDescribeResponseData.DescribedGroup]]()
+    when(groupCoordinator.streamsGroupDescribe(
+      any[RequestContext],
+      any[util.List[String]]
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    future.complete(List(
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(0)),
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(1)),
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(2))
+    ).asJava)
+
+    var authorizedOperationsInt = Int.MinValue;
+    if (includeAuthorizedOperations) {
+      authorizedOperationsInt = Utils.to32BitField(
+        AclEntry.supportedOperations(ResourceType.GROUP).asScala
+          .map(_.code.asInstanceOf[JByte]).asJava)
+    }
+
+    // Can't reuse the above list here because we would not test the implementation in KafkaApis then
+    val describedGroups = List(
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(0)),
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(1)),
+      new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(2))
+    ).map(group => group.setAuthorizedOperations(authorizedOperationsInt))
+    val expectedStreamsGroupDescribeResponseData = new StreamsGroupDescribeResponseData()
+      .setGroups(describedGroups.asJava)
+
+    val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
+
+    assertEquals(expectedStreamsGroupDescribeResponseData, response.data)
+  }
+
+  @Test
+  def testStreamsGroupDescribeReturnsUnsupportedVersion(): Unit = {
+    metadataCache = mock(classOf[ZkMetadataCache])
+
+    val groupId = "group0"
+    val streamsGroupDescribeRequestData = new StreamsGroupDescribeRequestData()
+    streamsGroupDescribeRequestData.groupIds.add(groupId)
+    val requestChannelRequest = buildRequest(new StreamsGroupDescribeRequest.Builder(streamsGroupDescribeRequestData, true).build())
+
+    val errorCode = Errors.UNSUPPORTED_VERSION.code
+    val expectedDescribedGroup = new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupId).setErrorCode(errorCode)
+    val expectedResponse = new StreamsGroupDescribeResponseData()
+    expectedResponse.groups.add(expectedDescribedGroup)
+    kafkaApis = createKafkaApis()
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
+
+    assertEquals(expectedResponse, response.data)
+  }
+
+  @Test
+  def testStreamsGroupDescribeAuthorizationFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupDescribeRequestData = new StreamsGroupDescribeRequestData()
+    streamsGroupDescribeRequestData.groupIds.add("group-id")
+    val requestChannelRequest = buildRequest(new StreamsGroupDescribeRequest.Builder(streamsGroupDescribeRequestData, true).build())
+
+    val authorizer: Authorizer = mock(classOf[Authorizer])
+    when(authorizer.authorize(any[RequestContext], any[util.List[Action]]))
+      .thenReturn(Seq(AuthorizationResult.DENIED).asJava)
+
+    val future = new CompletableFuture[util.List[StreamsGroupDescribeResponseData.DescribedGroup]]()
+    when(groupCoordinator.streamsGroupDescribe(
+      any[RequestContext],
+      any[util.List[String]]
+    )).thenReturn(future)
+    future.complete(List().asJava)
+    kafkaApis = createKafkaApis(
+      authorizer = Some(authorizer),
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
+    assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.groups.get(0).errorCode)
+  }
+
+  @Test
+  def testStreamsGroupDescribeFutureFailed(): Unit = {
+    metadataCache = mock(classOf[KRaftMetadataCache])
+
+    val streamsGroupDescribeRequestData = new StreamsGroupDescribeRequestData()
+    streamsGroupDescribeRequestData.groupIds.add("group-id")
+    val requestChannelRequest = buildRequest(new StreamsGroupDescribeRequest.Builder(streamsGroupDescribeRequestData, true).build())
+
+    val future = new CompletableFuture[util.List[StreamsGroupDescribeResponseData.DescribedGroup]]()
+    when(groupCoordinator.streamsGroupDescribe(
+      any[RequestContext],
+      any[util.List[String]]
+    )).thenReturn(future)
+    kafkaApis = createKafkaApis(
+      overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
+      raftSupport = true
+    )
+    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+
+    future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
+    val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
+    assertEquals(Errors.FENCED_MEMBER_EPOCH.code, response.data.groups.get(0).errorCode)
+  }
+  
   @Test
   def testGetTelemetrySubscriptionsNotAllowedForZkClusters(): Unit = {
     val data = new GetTelemetrySubscriptionsRequestData()
diff --git a/core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala b/core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala
index 1c5c2d3b0cd..28717aee87b 100755
--- a/core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaConfigTest.scala
@@ -1938,6 +1938,12 @@ class KafkaConfigTest {
     assertEquals(Set(GroupType.CLASSIC, GroupType.CONSUMER, GroupType.SHARE), config.groupCoordinatorRebalanceProtocols)
     assertTrue(config.isNewGroupCoordinatorEnabled)
     assertTrue(config.shareGroupConfig.isShareGroupEnabled)
+    
+    // This is OK.
+    props.put(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,streams")
+    val config2 = KafkaConfig.fromProps(props)
+    assertEquals(Set(GroupType.CLASSIC, GroupType.STREAMS), config2.groupCoordinatorRebalanceProtocols)
+    assertTrue(config2.isNewGroupCoordinatorEnabled)
   }
 
   @Test
diff --git a/gradle/spotbugs-exclude.xml b/gradle/spotbugs-exclude.xml
index b5a3c9bd96e..2b3c5b128d8 100644
--- a/gradle/spotbugs-exclude.xml
+++ b/gradle/spotbugs-exclude.xml
@@ -562,4 +562,9 @@ For a detailed description of spotbugs bug categories, see https://spotbugs.read
         <Bug pattern="SING_SINGLETON_HAS_NONPRIVATE_CONSTRUCTOR"/>
     </Match>
 
+    <Match>
+        <Class name="org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder"/>
+        <Bug pattern="URF_UNREAD_FIELD"/>
+    </Match>
+
 </FindBugsFilter>
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
index f25b5c39461..cea5da08608 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinator.java
@@ -39,6 +39,7 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -229,6 +230,19 @@ public interface GroupCoordinator {
         List<String> groupIds
     );
 
+    /**
+     * Describe streams groups.
+     *
+     * @param context           The coordinator request context.
+     * @param groupIds          The group ids.
+     *
+     * @return A future yielding the results or an exception.
+     */
+    CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> streamsGroupDescribe(
+        RequestContext context,
+        List<String> groupIds
+    );
+
     /**
      * Describe share groups.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index b2e2460064c..5d632528961 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -44,6 +44,7 @@ import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData.DescribedGroup;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -60,6 +61,7 @@ import org.apache.kafka.common.requests.DescribeGroupsRequest;
 import org.apache.kafka.common.requests.OffsetCommitRequest;
 import org.apache.kafka.common.requests.RequestContext;
 import org.apache.kafka.common.requests.ShareGroupDescribeRequest;
+import org.apache.kafka.common.requests.StreamsGroupDescribeRequest;
 import org.apache.kafka.common.requests.TransactionResult;
 import org.apache.kafka.common.requests.TxnOffsetCommitRequest;
 import org.apache.kafka.common.utils.BufferSupplier;
@@ -723,6 +725,57 @@ public class GroupCoordinatorService implements GroupCoordinator {
         return FutureUtils.combineFutures(futures, ArrayList::new, List::addAll);
     }
 
+    /**
+     * See {@link GroupCoordinator#streamsGroupDescribe(RequestContext, List)}.
+     */
+    @Override
+    public CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> streamsGroupDescribe(
+        RequestContext context,
+        List<String> groupIds
+    ) {
+        if (!isActive.get()) {
+            return CompletableFuture.completedFuture(StreamsGroupDescribeRequest.getErrorDescribedGroupList(
+                groupIds,
+                Errors.COORDINATOR_NOT_AVAILABLE
+            ));
+        }
+
+        final List<CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>>> futures =
+            new ArrayList<>(groupIds.size());
+        final Map<TopicPartition, List<String>> groupsByTopicPartition = new HashMap<>();
+        groupIds.forEach(groupId -> {
+            if (isGroupIdNotEmpty(groupId)) {
+                groupsByTopicPartition
+                    .computeIfAbsent(topicPartitionFor(groupId), __ -> new ArrayList<>())
+                    .add(groupId);
+            } else {
+                futures.add(CompletableFuture.completedFuture(Collections.singletonList(
+                    new StreamsGroupDescribeResponseData.DescribedGroup()
+                        .setGroupId(null)
+                        .setErrorCode(Errors.INVALID_GROUP_ID.code())
+                )));
+            }
+        });
+
+        groupsByTopicPartition.forEach((topicPartition, groupList) -> {
+            CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> future =
+                runtime.scheduleReadOperation(
+                    "streams-group-describe",
+                    topicPartition,
+                    (coordinator, lastCommittedOffset) -> coordinator.streamsGroupDescribe(groupIds, lastCommittedOffset)
+                ).exceptionally(exception -> handleOperationException(
+                    "streams-group-describe",
+                    groupList,
+                    exception,
+                    (error, __) -> StreamsGroupDescribeRequest.getErrorDescribedGroupList(groupList, error)
+                ));
+
+            futures.add(future);
+        });
+
+        return FutureUtils.combineFutures(futures, ArrayList::new, List::addAll);
+    }
+    
     /**
      * See {@link GroupCoordinator#shareGroupDescribe(RequestContext, List)}.
      */
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 4816649d9f6..dff55c9b684 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -39,6 +39,7 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -645,6 +646,21 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
         return groupMetadataManager.consumerGroupDescribe(groupIds, committedOffset);
     }
 
+    /**
+     * Handles a StreamsGroupDescribe request.
+     *
+     * @param groupIds      The IDs of the groups to describe.
+     *
+     * @return A list containing the StreamsGroupDescribeResponseData.DescribedGroup.
+     *
+     */
+    public List<StreamsGroupDescribeResponseData.DescribedGroup> streamsGroupDescribe(
+        List<String> groupIds,
+        long committedOffset
+    ) {
+        return groupMetadataManager.streamsGroupDescribe(groupIds, committedOffset);
+    }
+
     /**
      * Handles a ShareGroupDescribe request.
      *
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 1d95cad5a7e..e934304b168 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -53,6 +53,7 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.Endpoint;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData.KeyValue;
@@ -863,6 +864,33 @@ public class GroupMetadataManager {
         return describedGroups;
     }
 
+    /**
+     * Handles a StreamsGroupDescribe request.
+     *
+     * @param groupIds          The IDs of the groups to describe.
+     * @param committedOffset   A specified committed offset corresponding to this shard.
+     *
+     * @return A list containing the StreamsGroupDescribeResponseData.DescribedGroup.
+     */
+    public List<StreamsGroupDescribeResponseData.DescribedGroup> streamsGroupDescribe(
+        List<String> groupIds,
+        long committedOffset
+    ) {
+        final List<StreamsGroupDescribeResponseData.DescribedGroup> describedGroups = new ArrayList<>();
+        groupIds.forEach(groupId -> {
+            try {
+                describedGroups.add(streamsGroup(groupId, committedOffset).asDescribedGroup(committedOffset));
+            } catch (GroupIdNotFoundException exception) {
+                describedGroups.add(new StreamsGroupDescribeResponseData.DescribedGroup()
+                    .setGroupId(groupId)
+                    .setErrorCode(Errors.GROUP_ID_NOT_FOUND.code())
+                );
+            }
+        });
+
+        return describedGroups;
+    }
+    
     /**
      * Handles a DescribeGroup request.
      *
@@ -3839,10 +3867,8 @@ public class GroupMetadataManager {
         boolean staticMemberReplaced,
         List<CoordinatorRecord> records
     ) {
-        String preferredServerAssignor = group.computePreferredServerAssignor(
-            member,
-            updatedMember
-        ).orElse(defaultTaskAssignor.name());
+        // TODO: Read the preferred server assignor from the group configuration
+        String preferredServerAssignor = defaultTaskAssignor.name();
         try {
             org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder assignmentResultBuilder =
                 new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(group.groupId(), groupEpoch, taskAssignors.get(preferredServerAssignor))
@@ -3851,7 +3877,6 @@ public class GroupMetadataManager {
                     .withStaticMembers(group.staticMembers())
                     .withSubscriptionMetadata(subscriptionMetadata)
                     .withTargetAssignment(group.targetAssignment())
-                    .withTopicsImage(metadataImage.topics())
                     .addOrUpdateMember(updatedMember.memberId(), updatedMember);
             org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult assignmentResult;
             // A new static member is replacing an older one with the same subscriptions.
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
index 19eb79e36e6..f7690381708 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilder.java
@@ -182,7 +182,7 @@ public class CurrentAssignmentBuilder {
 
                 // If the member provides its owned tasks. We verify if it still
                 // owns any of the revoked tasks. If it does, we cannot progress.
-                if (ownsRevokedTasks(member.activeTasksPendingRevocation())) {
+                if (ownsRevokedActiveTasks(member.activeTasksPendingRevocation())) {
                     return member;
                 }
 
@@ -229,12 +229,12 @@ public class CurrentAssignmentBuilder {
     }
 
     /**
-     * Decides whether the current ownedTopicTasks contains any partition that is pending revocation.
+     * Decides whether the current ownedActiveTasks contains any partition that is pending revocation.
      *
      * @param assignment The assignment that has the tasks pending revocation.
      * @return A boolean based on the condition mentioned above.
      */
-    private boolean ownsRevokedTasks(
+    private boolean ownsRevokedActiveTasks(
         Map<String, Set<Integer>> assignment
     ) {
         if (ownedActiveTasks == null) {
@@ -313,7 +313,7 @@ public class CurrentAssignmentBuilder {
             }
         }
 
-        if (!newTasksPendingRevocation.isEmpty() && ownsRevokedTasks(newTasksPendingRevocation)) {
+        if (!newTasksPendingRevocation.isEmpty() && ownsRevokedActiveTasks(newTasksPendingRevocation)) {
             // If there are tasks to be revoked, the member remains in its current
             // epoch and requests the revocation of those tasks. It transitions to
             // the UNREVOKED_TASKS state to wait until the client acknowledges the
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 09dcf7817a5..1d4c2ace5e1 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -23,6 +23,7 @@ import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.StaleMemberEpochException;
 import org.apache.kafka.common.errors.UnknownMemberIdException;
 import org.apache.kafka.common.message.ListGroupsResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.coordinator.group.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.Group;
@@ -131,11 +132,6 @@ public class StreamsGroup implements Group {
      */
     private final TimelineHashMap<String, String> staticMembers;
 
-    /**
-     * The number of members supporting each assignor name.
-     */
-    private final TimelineHashMap<String, Integer> assignors;
-
     /**
      * The metadata associated with each subscribed topic name.
      */
@@ -175,7 +171,7 @@ public class StreamsGroup implements Group {
     /**
      * The Streams topology.
      */
-    private TimelineObject<Optional<StreamsTopology>> topology;
+    private final TimelineObject<Optional<StreamsTopology>> topology;
 
     /**
      * The metadata refresh deadline. It consists of a timestamp in milliseconds together with the group epoch at the time of setting it.
@@ -197,7 +193,6 @@ public class StreamsGroup implements Group {
         this.groupEpoch = new TimelineInteger(snapshotRegistry);
         this.members = new TimelineHashMap<>(snapshotRegistry, 0);
         this.staticMembers = new TimelineHashMap<>(snapshotRegistry, 0);
-        this.assignors = new TimelineHashMap<>(snapshotRegistry, 0);
         this.subscribedTopicMetadata = new TimelineHashMap<>(snapshotRegistry, 0);
         this.targetAssignmentEpoch = new TimelineInteger(snapshotRegistry);
         this.targetAssignment = new TimelineHashMap<>(snapshotRegistry, 0);
@@ -369,7 +364,6 @@ public class StreamsGroup implements Group {
         maybeUpdateTaskEpoch(oldMember, newMember);
         updateStaticMember(newMember);
         maybeUpdateGroupState();
-        maybeUpdateAssignors(oldMember, newMember);
     }
 
     /**
@@ -461,36 +455,6 @@ public class StreamsGroup implements Group {
         return Collections.unmodifiableMap(invertedTargetWarmupTasksAssignment);
     }
 
-    /**
-     * Updates the server assignors count.
-     *
-     * @param oldMember The old member.
-     * @param newMember The new member.
-     */
-    private void maybeUpdateAssignors(
-        StreamsGroupMember oldMember,
-        StreamsGroupMember newMember
-    ) {
-        maybeUpdateAssignors(assignors, oldMember, newMember);
-    }
-
-    private static void maybeUpdateAssignors(
-        Map<String, Integer> serverAssignorCount,
-        StreamsGroupMember oldMember,
-        StreamsGroupMember newMember
-    ) {
-        if (oldMember != null) {
-            oldMember.assignor().ifPresent(name ->
-                serverAssignorCount.compute(name, StreamsGroup::decValue)
-            );
-        }
-        if (newMember != null) {
-            newMember.assignor().ifPresent(name ->
-                serverAssignorCount.compute(name, StreamsGroup::incValue)
-            );
-        }
-    }
-
     /**
      * Updates the target assignment of a member.
      *
@@ -656,43 +620,6 @@ public class StreamsGroup implements Group {
         }
     }
 
-    /**
-     * Compute the preferred (server side) assignor for the group while taking into account the updated member. The computation relies on
-     * {{@link StreamsGroup#assignors}} persisted structure but it does not update it.
-     *
-     * @param oldMember The old member.
-     * @param newMember The new member.
-     * @return An Optional containing the preferred assignor.
-     */
-    public Optional<String> computePreferredServerAssignor(
-        StreamsGroupMember oldMember,
-        StreamsGroupMember newMember
-    ) {
-        // Copy the current count and update it.
-        Map<String, Integer> counts = new HashMap<>(this.assignors);
-        maybeUpdateAssignors(counts, oldMember, newMember);
-
-        return counts.entrySet().stream()
-            .max(Map.Entry.comparingByValue())
-            .map(Map.Entry::getKey);
-    }
-
-    /**
-     * @return The preferred assignor for the group.
-     */
-    public Optional<String> preferredServerAssignor() {
-        return preferredServerAssignor(Long.MAX_VALUE);
-    }
-
-    /**
-     * @return The preferred assignor for the group with given offset.
-     */
-    public Optional<String> preferredServerAssignor(long committedOffset) {
-        return assignors.entrySet(committedOffset).stream()
-            .max(Map.Entry.comparingByValue())
-            .map(Map.Entry::getKey);
-    }
-
     /**
      * @return An immutable Map of subscription metadata for each topic that the consumer group is subscribed to.
      */
@@ -1097,21 +1024,23 @@ public class StreamsGroup implements Group {
         });
     }
 
-    /**
-     * Decrements value by 1; returns null when reaching zero. This helper is meant to be used with Map#compute.
-     */
-    private static Integer decValue(String key, Integer value) {
-        if (value == null) {
-            return null;
-        }
-        return value == 1 ? null : value - 1;
-    }
-
-    /**
-     * Increments value by 1; This helper is meant to be used with Map#compute.
-     */
-    private static Integer incValue(String key, Integer value) {
-        return value == null ? 1 : value + 1;
+    public StreamsGroupDescribeResponseData.DescribedGroup asDescribedGroup(
+        long committedOffset
+    ) {
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(groupId)
+            .setGroupEpoch(groupEpoch.get(committedOffset))
+            .setGroupState(state.get(committedOffset).toString())
+            .setAssignmentEpoch(targetAssignmentEpoch.get(committedOffset))
+            .setTopology(topology.get(committedOffset).map(StreamsTopology::asStreamsGroupDescribeTopology).orElse(null));
+        members.entrySet(committedOffset).forEach(
+            entry -> describedGroup.members().add(
+                entry.getValue().asStreamsGroupDescribeMember(
+                    targetAssignment.get(entry.getValue().memberId(), committedOffset)
+                )
+            )
+        );
+        return describedGroup;
     }
 
     /**
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
index 5ad4370a5ab..e50e450feb4 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMember.java
@@ -16,12 +16,9 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.common.Uuid;
-import org.apache.kafka.common.message.ConsumerGroupDescribeResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
-import org.apache.kafka.image.TopicImage;
-import org.apache.kafka.image.TopicsImage;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -40,7 +37,7 @@ import java.util.stream.Collectors;
  */
 public class StreamsGroupMember {
 
-    /**
+  /**
      * A builder that facilitates the creation of a new member or the update of an existing one.
      * <p>
      * Please refer to the javadoc of {{@link StreamsGroupMember}} for the definition of the fields.
@@ -57,10 +54,9 @@ public class StreamsGroupMember {
         private String clientId = "";
         private String clientHost = "";
         private String topologyId;
-        private String assignor;
         private String processId;
         private StreamsGroupMemberMetadataValue.Endpoint userEndpoint;
-        private Map<String, String> clientTags;
+        private Map<String, String> clientTags = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedActiveTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedStandbyTasks = Collections.emptyMap();
         private Map<String, Set<Integer>> assignedWarmupTasks = Collections.emptyMap();
@@ -82,7 +78,6 @@ public class StreamsGroupMember {
             this.clientId = member.clientId;
             this.clientHost = member.clientHost;
             this.topologyId = member.topologyId;
-            this.assignor = member.assignor;
             this.processId = member.processId;
             this.userEndpoint = member.userEndpoint;
             this.clientTags = member.clientTags;
@@ -140,11 +135,6 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public StreamsGroupMember.Builder maybeUpdateAssignor(Optional<String> assignor) {
-            this.assignor = assignor.orElse(this.assignor);
-            return this;
-        }
-
         public Builder setClientId(String clientId) {
             this.clientId = clientId;
             return this;
@@ -170,11 +160,6 @@ public class StreamsGroupMember {
             return this;
         }
 
-        public Builder setAssignor(String assignor) {
-            this.assignor = assignor;
-            return this;
-        }
-
         public Builder setProcessId(String processId) {
             this.processId = processId;
             return this;
@@ -271,7 +256,6 @@ public class StreamsGroupMember {
                 clientId,
                 clientHost,
                 topologyId,
-                assignor,
                 processId,
                 userEndpoint,
                 clientTags,
@@ -334,11 +318,6 @@ public class StreamsGroupMember {
      */
     private final String topologyId;
 
-    /**
-     * The assignor
-     */
-    private final String assignor;
-
     /**
      * The process ID
      */
@@ -385,7 +364,6 @@ public class StreamsGroupMember {
         String clientId,
         String clientHost,
         String topologyId,
-        String assignor,
         String processId,
         StreamsGroupMemberMetadataValue.Endpoint userEndpoint,
         Map<String, String> clientTags,
@@ -405,7 +383,6 @@ public class StreamsGroupMember {
         this.clientId = clientId;
         this.clientHost = clientHost;
         this.topologyId = topologyId;
-        this.assignor = assignor;
         this.processId = processId;
         this.userEndpoint = userEndpoint;
         this.clientTags = clientTags;
@@ -478,13 +455,6 @@ public class StreamsGroupMember {
         return topologyId;
     }
 
-    /**
-     * @return The assignor
-     */
-    public Optional<String> assignor() {
-        return Optional.ofNullable(assignor);
-    }
-
     /**
      * @return The process ID
      */
@@ -548,33 +518,58 @@ public class StreamsGroupMember {
         return activeTasksPendingRevocation;
     }
 
-    private static List<ConsumerGroupDescribeResponseData.TopicPartitions> topicPartitionsFromMap(
-        Map<Uuid, Set<Integer>> partitions,
-        TopicsImage topicsImage
+    /**
+     * @param targetAssignment The target assignment of this member in the corresponding group.
+     *
+     * @return The StreamsGroupMember mapped as StreamsGroupDescribeResponseData.Member.
+     */
+    public StreamsGroupDescribeResponseData.Member asStreamsGroupDescribeMember(
+        Assignment targetAssignment
     ) {
-        List<ConsumerGroupDescribeResponseData.TopicPartitions> topicPartitions = new ArrayList<>();
-        partitions.forEach((topicId, partitionSet) -> {
-            String topicName = lookupTopicNameById(topicId, topicsImage);
-            if (topicName != null) {
-                topicPartitions.add(new ConsumerGroupDescribeResponseData.TopicPartitions()
-                    .setTopicId(topicId)
-                    .setTopicName(topicName)
-                    .setPartitions(new ArrayList<>(partitionSet)));
-            }
-        });
-        return topicPartitions;
+        final StreamsGroupDescribeResponseData.Assignment describedTargetAssignment =
+            new StreamsGroupDescribeResponseData.Assignment();
+
+        if (targetAssignment != null) {
+            describedTargetAssignment
+                .setActiveTasks(taskIdsFromMap(targetAssignment.activeTasks()))
+                .setStandbyTasks(taskIdsFromMap(targetAssignment.standbyTasks()))
+                .setWarmupTasks(taskIdsFromMap(targetAssignment.warmupTasks()));
+        }
+
+        return new StreamsGroupDescribeResponseData.Member()
+            .setMemberEpoch(memberEpoch)
+            .setMemberId(memberId)
+            .setAssignment(
+                new StreamsGroupDescribeResponseData.Assignment()
+                    .setActiveTasks(taskIdsFromMap(assignedActiveTasks))
+                    .setStandbyTasks(taskIdsFromMap(assignedStandbyTasks))
+                    .setWarmupTasks(taskIdsFromMap(assignedWarmupTasks)))
+            .setTargetAssignment(describedTargetAssignment)
+            .setClientHost(clientHost)
+            .setClientId(clientId)
+            .setInstanceId(instanceId)
+            .setRackId(rackId)
+            .setClientTags(clientTags.entrySet().stream().map(
+                entry -> new StreamsGroupDescribeResponseData.KeyValue()
+                    .setKey(entry.getKey())
+                    .setValue(entry.getValue())
+            ).collect(Collectors.toList()))
+            .setProcessId(processId)
+            .setTopologyId(topologyId);
+        // TODO: TaskOffset and TaskEndOffset are missing.
+
     }
 
-    private static String lookupTopicNameById(
-        Uuid topicId,
-        TopicsImage topicsImage
+    private static List<StreamsGroupDescribeResponseData.TaskIds> taskIdsFromMap(
+        Map<String, Set<Integer>> tasks
     ) {
-        TopicImage topicImage = topicsImage.getTopic(topicId);
-        if (topicImage != null) {
-            return topicImage.name();
-        } else {
-            return null;
-        }
+        List<StreamsGroupDescribeResponseData.TaskIds> taskIds = new ArrayList<>();
+        tasks.forEach((subtopologyId, partitionSet) -> {
+            taskIds.add(new StreamsGroupDescribeResponseData.TaskIds()
+                .setSubtopology(subtopologyId)
+                .setPartitions(new ArrayList<>(partitionSet)));
+        });
+        return taskIds;
     }
 
     @SuppressWarnings("checkstyle:CyclomaticComplexity")
@@ -597,7 +592,6 @@ public class StreamsGroupMember {
             && Objects.equals(clientId, that.clientId)
             && Objects.equals(clientHost, that.clientHost)
             && Objects.deepEquals(topologyId, that.topologyId)
-            && Objects.equals(assignor, that.assignor)
             && Objects.equals(processId, that.processId)
             && Objects.equals(userEndpoint, that.userEndpoint)
             && Objects.equals(clientTags, that.clientTags)
@@ -619,7 +613,6 @@ public class StreamsGroupMember {
         result = 31 * result + Objects.hashCode(clientId);
         result = 31 * result + Objects.hashCode(clientHost);
         result = 31 * result + Objects.hashCode(topologyId);
-        result = 31 * result + Objects.hashCode(assignor);
         result = 31 * result + Objects.hashCode(processId);
         result = 31 * result + Objects.hashCode(userEndpoint);
         result = 31 * result + Objects.hashCode(clientTags);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index e0bec1c292a..5f09941fae9 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -16,6 +16,8 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
+import java.util.List;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
@@ -88,4 +90,35 @@ public class StreamsTopology {
             ", subtopologies=" + subtopologies +
             '}';
     }
+
+    public List<StreamsGroupDescribeResponseData.Subtopology> asStreamsGroupDescribeTopology() {
+        return subtopologies.values().stream().map(
+            subtopology -> new StreamsGroupDescribeResponseData.Subtopology()
+                .setSourceTopicRegex(subtopology.sourceTopicRegex())
+                .setSubtopology(subtopology.subtopology())
+                .setSourceTopics(subtopology.sourceTopics())
+                .setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
+                .setRepartitionSourceTopics(
+                    asStreamsGroupDescribeTopicInfo(subtopology.repartitionSourceTopics()))
+                .setStateChangelogTopics(
+                    asStreamsGroupDescribeTopicInfo(subtopology.stateChangelogTopics()))
+        ).collect(Collectors.toList());
+    }
+
+    private static List<StreamsGroupDescribeResponseData.TopicInfo> asStreamsGroupDescribeTopicInfo(
+        final List<TopicInfo> topicInfos) {
+        return topicInfos.stream().map(x ->
+            new StreamsGroupDescribeResponseData.TopicInfo()
+                .setName(x.name())
+                .setPartitions(x.partitions())
+                .setTopicConfigs(
+                    x.topicConfigs() != null ?
+                        x.topicConfigs().stream().map(
+                            y -> new StreamsGroupDescribeResponseData.KeyValue()
+                                .setKey(y.key())
+                                .setValue(y.value())
+                        ).collect(Collectors.toList()) : null
+                )
+        ).collect(Collectors.toList());
+    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index 1fd34e27e89..51e07c3418c 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -23,7 +23,6 @@ import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
 import org.apache.kafka.coordinator.group.taskassignor.MemberAssignment;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignorException;
-import org.apache.kafka.image.TopicsImage;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -115,11 +114,6 @@ public class TargetAssignmentBuilder {
      */
     private Map<String, org.apache.kafka.coordinator.group.streams.Assignment> targetAssignment = Collections.emptyMap();
 
-    /**
-     * The topics image.
-     */
-    private TopicsImage topicsImage = TopicsImage.EMPTY;
-
     /**
      * The topology.
      */
@@ -204,19 +198,6 @@ public class TargetAssignmentBuilder {
         return this;
     }
 
-    /**
-     * Adds the topics image.
-     *
-     * @param topicsImage The topics image.
-     * @return This object.
-     */
-    public TargetAssignmentBuilder withTopicsImage(
-        TopicsImage topicsImage
-    ) {
-        this.topicsImage = topicsImage;
-        return this;
-    }
-
     /**
      * Adds the topology image.
      *
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
index fcdd221c907..5b1aad09027 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java
@@ -54,6 +54,7 @@ import org.apache.kafka.common.message.OffsetFetchResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -1771,6 +1772,143 @@ public class GroupCoordinatorServiceTest {
         );
     }
 
+    @Test
+    public void testStreamsGroupDescribe() throws InterruptedException, ExecutionException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+        int partitionCount = 2;
+        service.startup(() -> partitionCount);
+
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup1 = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId("group-id-1");
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup2 = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId("group-id-2");
+        List<StreamsGroupDescribeResponseData.DescribedGroup> expectedDescribedGroups = Arrays.asList(
+            describedGroup1,
+            describedGroup2
+        );
+
+        when(runtime.scheduleReadOperation(
+            ArgumentMatchers.eq("streams-group-describe"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.any()
+        )).thenReturn(CompletableFuture.completedFuture(Collections.singletonList(describedGroup1)));
+
+        CompletableFuture<Object> describedGroupFuture = new CompletableFuture<>();
+        when(runtime.scheduleReadOperation(
+            ArgumentMatchers.eq("streams-group-describe"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 1)),
+            ArgumentMatchers.any()
+        )).thenReturn(describedGroupFuture);
+
+        CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> future =
+            service.streamsGroupDescribe(requestContext(ApiKeys.STREAMS_GROUP_DESCRIBE), Arrays.asList("group-id-1", "group-id-2"));
+
+        assertFalse(future.isDone());
+        describedGroupFuture.complete(Collections.singletonList(describedGroup2));
+        assertEquals(expectedDescribedGroups, future.get());
+    }
+
+    @Test
+    public void testStreamsGroupDescribeInvalidGroupId() throws ExecutionException, InterruptedException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+        int partitionCount = 1;
+        service.startup(() -> partitionCount);
+
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(null)
+            .setErrorCode(Errors.INVALID_GROUP_ID.code());
+        List<StreamsGroupDescribeResponseData.DescribedGroup> expectedDescribedGroups = Arrays.asList(
+            new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupId(null)
+                .setErrorCode(Errors.INVALID_GROUP_ID.code()),
+            describedGroup
+        );
+
+        when(runtime.scheduleReadOperation(
+            ArgumentMatchers.eq("streams-group-describe"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.any()
+        )).thenReturn(CompletableFuture.completedFuture(Collections.singletonList(describedGroup)));
+
+        CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> future =
+            service.streamsGroupDescribe(requestContext(ApiKeys.STREAMS_GROUP_DESCRIBE), Arrays.asList("", null));
+
+        assertEquals(expectedDescribedGroups, future.get());
+    }
+
+    @Test
+    public void testStreamsGroupDescribeCoordinatorLoadInProgress() throws ExecutionException, InterruptedException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+        int partitionCount = 1;
+        service.startup(() -> partitionCount);
+
+        when(runtime.scheduleReadOperation(
+            ArgumentMatchers.eq("streams-group-describe"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.any()
+        )).thenReturn(FutureUtils.failedFuture(
+            new CoordinatorLoadInProgressException(null)
+        ));
+
+        CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> future =
+            service.streamsGroupDescribe(requestContext(ApiKeys.STREAMS_GROUP_DESCRIBE), Collections.singletonList("group-id"));
+
+        assertEquals(
+            Collections.singletonList(new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupId("group-id")
+                .setErrorCode(Errors.COORDINATOR_LOAD_IN_PROGRESS.code())
+            ),
+            future.get()
+        );
+    }
+
+    @Test
+    public void testStreamsGroupDescribeCoordinatorNotActive() throws ExecutionException, InterruptedException {
+        CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
+        GroupCoordinatorService service = new GroupCoordinatorService(
+            new LogContext(),
+            createConfig(),
+            runtime,
+            new GroupCoordinatorMetrics()
+        );
+        when(runtime.scheduleReadOperation(
+            ArgumentMatchers.eq("streams-group-describe"),
+            ArgumentMatchers.eq(new TopicPartition("__consumer_offsets", 0)),
+            ArgumentMatchers.any()
+        )).thenReturn(FutureUtils.failedFuture(
+            Errors.COORDINATOR_NOT_AVAILABLE.exception()
+        ));
+
+        CompletableFuture<List<StreamsGroupDescribeResponseData.DescribedGroup>> future =
+            service.streamsGroupDescribe(requestContext(ApiKeys.STREAMS_GROUP_DESCRIBE), Collections.singletonList("group-id"));
+
+        assertEquals(
+            Collections.singletonList(new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupId("group-id")
+                .setErrorCode(Errors.COORDINATOR_NOT_AVAILABLE.code())
+            ),
+            future.get()
+        );
+    }
+    
     @Test
     public void testDeleteOffsets() throws Exception {
         CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index 2adadc1be4d..e7fffb90c8c 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -100,7 +100,7 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-@SuppressWarnings({"ClassFanOutComplexity"})
+@SuppressWarnings("ClassFanOutComplexity")
 public class GroupCoordinatorShardTest {
 
     @Test
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 4602593b6e3..bbbfe346539 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -54,6 +54,7 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
@@ -90,6 +91,10 @@ import org.apache.kafka.coordinator.group.modern.consumer.ResolvedRegularExpress
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
+import org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.image.MetadataProvenance;
@@ -8839,6 +8844,113 @@ public class GroupMetadataManagerTest {
         assertEquals(expected, actual);
     }
 
+    @Test
+    public void testStreamsGroupDescribeNoErrors() {
+        List<String> streamsGroupIds = Arrays.asList("group-id-1", "group-id-2");
+        int epoch = 10;
+        String memberId = "member-id";
+        StreamsGroupMember.Builder memberBuilder = new StreamsGroupMember.Builder(memberId)
+            .setClientTags(Collections.singletonMap("clientTag", "clientValue"))
+            .setProcessId("processId")
+            .setMemberEpoch(epoch)
+            .setPreviousMemberEpoch(epoch - 1);
+
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withStreamsGroup(new StreamsGroupBuilder(streamsGroupIds.get(0), epoch))
+            .withStreamsGroup(new StreamsGroupBuilder(streamsGroupIds.get(1), epoch)
+                .withMember(memberBuilder.build()))
+            .build();
+
+        List<StreamsGroupDescribeResponseData.DescribedGroup> expected = Arrays.asList(
+            new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupEpoch(epoch)
+                .setGroupId(streamsGroupIds.get(0))
+                .setGroupState(StreamsGroup.StreamsGroupState.EMPTY.toString())
+                .setAssignmentEpoch(0),
+            new StreamsGroupDescribeResponseData.DescribedGroup()
+                .setGroupEpoch(epoch)
+                .setGroupId(streamsGroupIds.get(1))
+                .setMembers(Collections.singletonList(
+                    memberBuilder.build().asStreamsGroupDescribeMember(
+                        new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())
+                    )
+                ))
+                .setGroupState(StreamsGroup.StreamsGroupState.ASSIGNING.toString())
+        );
+        List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.sendStreamsGroupDescribe(streamsGroupIds);
+
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void testStreamsGroupDescribeWithErrors() {
+        String groupId = "groupId";
+
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+
+        List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.sendStreamsGroupDescribe(Collections.singletonList(groupId));
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(groupId)
+            .setErrorCode(Errors.GROUP_ID_NOT_FOUND.code());
+        List<StreamsGroupDescribeResponseData.DescribedGroup> expected = Collections.singletonList(
+            describedGroup
+        );
+
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void testStreamsGroupDescribeBeforeAndAfterCommittingOffset() {
+        String streamsGroupId = "streamsGroupId";
+        int epoch = 10;
+        String memberId1 = "memberId1";
+        String memberId2 = "memberId2";
+        String subtopologyId = "subtopology1";
+
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+
+        StreamsGroupMember.Builder memberBuilder1 = new StreamsGroupMember.Builder(memberId1);
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(streamsGroupId, memberBuilder1.build()));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(streamsGroupId, epoch + 1));
+
+        Map<String, Set<Integer>> assignmentMap = new HashMap<>();
+        assignmentMap.put(subtopologyId, Collections.emptySet());
+
+        StreamsGroupMember.Builder memberBuilder2 = new StreamsGroupMember.Builder(memberId2);
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(streamsGroupId, memberBuilder2.build()));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(streamsGroupId, memberId2, assignmentMap, assignmentMap, assignmentMap));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(streamsGroupId, memberBuilder2.build()));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(streamsGroupId, epoch + 2));
+
+        List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.groupMetadataManager.streamsGroupDescribe(Collections.singletonList(streamsGroupId), context.lastCommittedOffset);
+        StreamsGroupDescribeResponseData.DescribedGroup describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(streamsGroupId)
+            .setErrorCode(Errors.GROUP_ID_NOT_FOUND.code());
+        assertEquals(1, actual.size());
+        assertEquals(describedGroup, actual.get(0));
+
+        // Commit the offset and test again
+        context.commit();
+
+        actual = context.groupMetadataManager.streamsGroupDescribe(Collections.singletonList(streamsGroupId), context.lastCommittedOffset);
+        describedGroup = new StreamsGroupDescribeResponseData.DescribedGroup()
+            .setGroupId(streamsGroupId)
+            .setMembers(Arrays.asList(
+                memberBuilder1.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())),
+                memberBuilder2.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(assignmentMap, assignmentMap, assignmentMap))
+            ))
+            .setGroupState(StreamsGroup.StreamsGroupState.ASSIGNING.toString())
+            .setGroupEpoch(epoch + 2);
+        assertEquals(1, actual.size());
+        assertEquals(describedGroup, actual.get(0));
+    }
+    
     @Test
     public void testDescribeGroupStable() {
         GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index 7e38f61ffd5..45654736316 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -36,6 +36,7 @@ import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.ShareGroupDescribeResponseData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
@@ -88,6 +89,18 @@ import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMe
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMemberValue;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataKey;
 import org.apache.kafka.coordinator.group.generated.ShareGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
@@ -96,6 +109,7 @@ import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
@@ -139,6 +153,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 import static org.mockito.Mockito.mock;
 
+@SuppressWarnings("CyclomaticComplexity")
 public class GroupMetadataManagerTestContext {
     static final String DEFAULT_CLIENT_ID = "client";
     static final InetAddress DEFAULT_CLIENT_ADDRESS = InetAddress.getLoopbackAddress();
@@ -417,6 +432,9 @@ public class GroupMetadataManagerTestContext {
         private final List<ConsumerGroupBuilder> consumerGroupBuilders = new ArrayList<>();
         private int consumerGroupMaxSize = Integer.MAX_VALUE;
         private int consumerGroupMetadataRefreshIntervalMs = Integer.MAX_VALUE;
+        private final List<StreamsGroupBuilder> streamsGroupBuilders = new ArrayList<>();
+        private int streamsGroupMaxSize = Integer.MAX_VALUE;
+        private int streamsGroupMetadataRefreshIntervalMs = Integer.MAX_VALUE;
         private int classicGroupMaxSize = Integer.MAX_VALUE;
         private int classicGroupInitialRebalanceDelayMs = 3000;
         private final int classicGroupNewMemberJoinTimeoutMs = 5 * 60 * 1000;
@@ -428,7 +446,7 @@ public class GroupMetadataManagerTestContext {
         private ShareGroupPartitionAssignor shareGroupAssignor = new MockPartitionAssignor("share");
         private final List<ShareGroupBuilder> shareGroupBuilders = new ArrayList<>();
         private int shareGroupMaxSize = Integer.MAX_VALUE;
-        private List<TaskAssignor> taskAssignors = Collections.singletonList(new MockTaskAssignor("mock"));
+        private List<TaskAssignor> streamsGroupAssignors = Collections.singletonList(new MockTaskAssignor("mock"));
 
         public Builder withMetadataImage(MetadataImage metadataImage) {
             this.metadataImage = metadataImage;
@@ -485,6 +503,26 @@ public class GroupMetadataManagerTestContext {
             return this;
         }
 
+        public Builder withTaskAssignors(List<TaskAssignor> assignors) {
+            this.streamsGroupAssignors = assignors;
+            return this;
+        }
+
+        public Builder withStreamsGroup(StreamsGroupBuilder builder) {
+            this.streamsGroupBuilders.add(builder);
+            return this;
+        }
+
+        public Builder withStreamsGroupMaxSize(int streamsGroupMaxSize) {
+            this.streamsGroupMaxSize = streamsGroupMaxSize;
+            return this;
+        }
+
+        public Builder withStreamsGroupMetadataRefreshIntervalMs(int streamsGroupMetadataRefreshIntervalMs) {
+            this.streamsGroupMetadataRefreshIntervalMs = streamsGroupMetadataRefreshIntervalMs;
+            return this;
+        }
+
         public Builder withShareGroupAssignor(ShareGroupPartitionAssignor shareGroupAssignor) {
             this.shareGroupAssignor = shareGroupAssignor;
             return this;
@@ -528,7 +566,11 @@ public class GroupMetadataManagerTestContext {
                     .withShareGroupAssignor(shareGroupAssignor)
                     .withShareGroupMaxSize(shareGroupMaxSize)
                     .withGroupConfigManager(groupConfigManager)
-                    .withStreamsGroupAssignors(taskAssignors)
+                    .withStreamsGroupHeartbeatInterval(5000)
+                    .withStreamsGroupSessionTimeout(45000)
+                    .withStreamsGroupMaxSize(streamsGroupMaxSize)
+                    .withStreamsGroupAssignors(streamsGroupAssignors)
+                    .withStreamsGroupMetadataRefreshIntervalMs(streamsGroupMetadataRefreshIntervalMs)
                     .build(),
                 groupConfigManager,
                 classicGroupInitialRebalanceDelayMs,
@@ -538,6 +580,8 @@ public class GroupMetadataManagerTestContext {
             consumerGroupBuilders.forEach(builder -> builder.build(metadataImage.topics()).forEach(context::replay));
             shareGroupBuilders.forEach(builder -> builder.build(metadataImage.topics()).forEach(context::replay));
 
+            streamsGroupBuilders.forEach(builder -> builder.build().forEach(context::replay));
+
             context.commit();
 
             return context;
@@ -1354,6 +1398,10 @@ public class GroupMetadataManagerTestContext {
         return groupMetadataManager.consumerGroupDescribe(groupIds, lastCommittedOffset);
     }
 
+    public List<StreamsGroupDescribeResponseData.DescribedGroup> sendStreamsGroupDescribe(List<String> groupIds) {
+        return groupMetadataManager.streamsGroupDescribe(groupIds, lastCommittedOffset);
+    }
+
     public List<DescribeGroupsResponseData.DescribedGroup> describeGroups(List<String> groupIds) {
         return groupMetadataManager.describeGroups(groupIds, lastCommittedOffset);
     }
@@ -1653,6 +1701,48 @@ public class GroupMetadataManagerTestContext {
                 );
                 break;
 
+            case StreamsGroupCurrentMemberAssignmentKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupCurrentMemberAssignmentKey) key.message(),
+                    (StreamsGroupCurrentMemberAssignmentValue) messageOrNull(value)
+                );
+                break;
+
+            case StreamsGroupMemberMetadataKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupMemberMetadataKey) key.message(),
+                    (StreamsGroupMemberMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case StreamsGroupMetadataKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupMetadataKey) key.message(),
+                    (StreamsGroupMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case StreamsGroupPartitionMetadataKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupPartitionMetadataKey) key.message(),
+                    (StreamsGroupPartitionMetadataValue) messageOrNull(value)
+                );
+                break;
+
+            case StreamsGroupTargetAssignmentMemberKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupTargetAssignmentMemberKey) key.message(),
+                    (StreamsGroupTargetAssignmentMemberValue) messageOrNull(value)
+                );
+                break;
+
+            case StreamsGroupTargetAssignmentMetadataKey.HIGHEST_SUPPORTED_VERSION:
+                groupMetadataManager.replay(
+                    (StreamsGroupTargetAssignmentMetadataKey) key.message(),
+                    (StreamsGroupTargetAssignmentMetadataValue) messageOrNull(value)
+                );
+                break;
+
             case StreamsGroupTopologyKey.HIGHEST_SUPPORTED_VERSION:
                 groupMetadataManager.replay(
                     (StreamsGroupTopologyKey) key.message(),
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
new file mode 100644
index 00000000000..b07dabc05e1
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
@@ -0,0 +1,101 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.kafka.coordinator.group.CoordinatorRecord;
+
+public class StreamsGroupBuilder {
+
+    private final String groupId;
+    private final int groupEpoch;
+    private int assignmentEpoch;
+    private final Map<String, StreamsGroupMember> members = new HashMap<>();
+    private final Map<String, Assignment> assignments = new HashMap<>();
+    private Map<String, TopicMetadata> partitionMetadata = new HashMap<>();
+
+    public StreamsGroupBuilder(String groupId, int groupEpoch) {
+        this.groupId = groupId;
+        this.groupEpoch = groupEpoch;
+        this.assignmentEpoch = 0;
+    }
+
+    public StreamsGroupBuilder withMember(StreamsGroupMember member) {
+        this.members.put(member.memberId(), member);
+        return this;
+    }
+
+    public StreamsGroupBuilder withPartitionMetadata(
+        Map<String, TopicMetadata> partitionMetadata) {
+        this.partitionMetadata = partitionMetadata;
+        return this;
+    }
+
+    public StreamsGroupBuilder withAssignment(String memberId,
+        Map<String, Set<Integer>> assignment) {
+        this.assignments.put(memberId, new Assignment(assignment));
+        return this;
+    }
+
+    public StreamsGroupBuilder withAssignmentEpoch(int assignmentEpoch) {
+        this.assignmentEpoch = assignmentEpoch;
+        return this;
+    }
+
+    public List<CoordinatorRecord> build() {
+        List<CoordinatorRecord> records = new ArrayList<>();
+
+        // Add records for members.
+        members.forEach((memberId, member) ->
+            records.add(
+                CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId, member))
+        );
+
+        if (!partitionMetadata.isEmpty()) {
+            records.add(
+                CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId,
+                    partitionMetadata));
+        }
+
+        // Add group epoch record.
+        records.add(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, groupEpoch));
+
+        // Add target assignment records.
+        assignments.forEach((memberId, assignment) ->
+            records.add(
+                CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(groupId, memberId,
+                    assignment.activeTasks(), assignment.standbyTasks(), assignment.warmupTasks()))
+        );
+
+        // Add target assignment epoch.
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId,
+            assignmentEpoch));
+
+        // Add current assignment records for members.
+        members.forEach((memberId, member) ->
+            records.add(
+                CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(groupId, member))
+        );
+
+        return records;
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index f4e4eccdaa0..35ab964d1b6 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -16,6 +16,11 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue.TaskIds;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
@@ -50,7 +55,6 @@ public class StreamsGroupMemberTest {
             .setClientId("client-id")
             .setClientHost("hostname")
             .setTopologyId("topology-hash")
-            .setAssignor("assignor")
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
@@ -68,7 +72,6 @@ public class StreamsGroupMemberTest {
         assertEquals("client-id", member.clientId());
         assertEquals("hostname", member.clientHost());
         assertEquals("topology-hash", member.topologyId());
-        assertEquals("assignor", member.assignor().get());
         assertEquals("process-id", member.processId());
         assertEquals(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090), member.userEndpoint());
         assertEquals(
@@ -107,7 +110,6 @@ public class StreamsGroupMemberTest {
             .setClientId("client-id")
             .setClientHost("hostname")
             .setTopologyId("topology-hash")
-            .setAssignor("assignor")
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
@@ -126,7 +128,6 @@ public class StreamsGroupMemberTest {
             .setClientId("client-id")
             .setClientHost("hostname")
             .setTopologyId("topology-hash")
-            .setAssignor("assignor")
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
@@ -145,7 +146,6 @@ public class StreamsGroupMemberTest {
             .setClientId("client-id")
             .setClientHost("hostname")
             .setTopologyId("topology-hash")
-            .setAssignor("assignor")
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
@@ -173,7 +173,6 @@ public class StreamsGroupMemberTest {
             .setClientId("client-id")
             .setClientHost("hostname")
             .setTopologyId("topology-hash")
-            .setAssignor("assignor")
             .setProcessId("process-id")
             .setUserEndpoint(new StreamsGroupMemberMetadataValue.Endpoint().setHost("host").setPort(9090))
             .setClientTags(mkMap(mkEntry("client", "tag")))
@@ -188,7 +187,6 @@ public class StreamsGroupMemberTest {
             .maybeUpdateRackId(Optional.empty())
             .maybeUpdateInstanceId(Optional.empty())
             .maybeUpdateRebalanceTimeoutMs(OptionalInt.empty())
-            .maybeUpdateAssignor(Optional.empty())
             .build();
 
         assertEquals(member, updatedMember);
@@ -197,13 +195,11 @@ public class StreamsGroupMemberTest {
             .maybeUpdateRackId(Optional.of("new-rack-id"))
             .maybeUpdateInstanceId(Optional.of("new-instance-id"))
             .maybeUpdateRebalanceTimeoutMs(OptionalInt.of(6000))
-            .maybeUpdateAssignor(Optional.of("new-assignor"))
             .build();
 
         assertEquals("new-instance-id", updatedMember.instanceId());
         assertEquals("new-rack-id", updatedMember.rackId());
         assertEquals(6000, updatedMember.rebalanceTimeoutMs());
-        assertEquals("new-assignor", updatedMember.assignor().get());
     }
 
     @Test
@@ -275,4 +271,117 @@ public class StreamsGroupMemberTest {
         assertEquals(mkAssignment(mkTaskAssignment(subtopologyId1, 7, 8, 9)), member.assignedWarmupTasks());
         assertEquals(mkAssignment(mkTaskAssignment(subtopologyId2, 2, 3, 1)), member.activeTasksPendingRevocation());
     }
+
+    @Test
+    public void testAsStreamsGroupDescribeMember() {
+        String subTopology1 = Uuid.randomUuid().toString();
+        String subTopology2 = Uuid.randomUuid().toString();
+        String subTopology3 = Uuid.randomUuid().toString();
+        String subTopology4 = Uuid.randomUuid().toString();
+        List<Integer> assignedTasks1 = Arrays.asList(0, 1, 2);
+        List<Integer> assignedTasks2 = Arrays.asList(3, 4, 5);
+        List<Integer> assignedTasks3 = Arrays.asList(6, 7, 8);
+        List<Integer> assignedTasks4 = Arrays.asList(5, 6, 7);
+        int epoch = 10;
+        StreamsGroupCurrentMemberAssignmentValue record = new StreamsGroupCurrentMemberAssignmentValue()
+            .setMemberEpoch(epoch)
+            .setPreviousMemberEpoch(epoch - 1)
+            .setActiveTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subTopology1)
+                .setPartitions(assignedTasks1)))
+            .setStandbyTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subTopology2)
+                .setPartitions(assignedTasks2)))
+            .setWarmupTasks(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subTopology3)
+                .setPartitions(assignedTasks3)))
+            .setActiveTasksPendingRevocation(Collections.singletonList(new StreamsGroupCurrentMemberAssignmentValue.TaskIds()
+                .setSubtopology(subTopology4)
+                .setPartitions(assignedTasks4)));
+        String memberId = Uuid.randomUuid().toString();
+        String clientId = "clientId";
+        String instanceId = "instanceId";
+        String rackId = "rackId";
+        String clientHost = "clientHost";
+        String processId = "processId";
+        String topologyId = "topologyId";
+        Map<String, String> clientTags = Collections.singletonMap("key", "value");
+        org.apache.kafka.coordinator.group.streams.Assignment targetAssignment = new org.apache.kafka.coordinator.group.streams.Assignment(
+            mkMap(mkEntry(subTopology1, new HashSet<>(assignedTasks3))),
+            mkMap(mkEntry(subTopology2, new HashSet<>(assignedTasks2))),
+            mkMap(mkEntry(subTopology3, new HashSet<>(assignedTasks1)))
+        );
+        StreamsGroupMember member = new StreamsGroupMember.Builder(memberId)
+            .updateWith(record)
+            .setClientId(clientId)
+            .setInstanceId(instanceId)
+            .setRackId(rackId)
+            .setClientHost(clientHost)
+            .setProcessId(processId)
+            .setTopologyId(topologyId)
+            .setClientTags(clientTags)
+            .setAssignedActiveTasks(
+                mkMap(mkEntry(subTopology1, new HashSet<>(assignedTasks1)))
+            )
+            .setAssignedStandbyTasks(
+                mkMap(mkEntry(subTopology2, new HashSet<>(assignedTasks2)))
+            )
+            .setAssignedWarmupTasks(
+                mkMap(mkEntry(subTopology3, new HashSet<>(assignedTasks3)))
+            )
+            .setActiveTasksPendingRevocation(
+                mkMap(mkEntry(subTopology3, new HashSet<>(assignedTasks4)))
+            )
+            .build();
+
+        StreamsGroupDescribeResponseData.Member actual = member.asStreamsGroupDescribeMember(targetAssignment);
+        StreamsGroupDescribeResponseData.Member expected = new StreamsGroupDescribeResponseData.Member()
+            .setMemberId(memberId)
+            .setMemberEpoch(epoch)
+            .setClientId(clientId)
+            .setInstanceId(instanceId)
+            .setRackId(rackId)
+            .setClientHost(clientHost)
+            .setProcessId(processId)
+            .setTopologyId(topologyId)
+            .setClientTags(Collections.singletonList(new StreamsGroupDescribeResponseData.KeyValue().setKey("key").setValue("value")))
+            .setAssignment(
+                new StreamsGroupDescribeResponseData.Assignment()
+                    .setActiveTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology1)
+                        .setPartitions(assignedTasks1)))
+                    .setStandbyTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology2)
+                        .setPartitions(assignedTasks2)))
+                    .setWarmupTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology3)
+                        .setPartitions(assignedTasks3)))
+            )
+            .setTargetAssignment(
+                new StreamsGroupDescribeResponseData.Assignment()
+                    .setActiveTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology1)
+                        .setPartitions(assignedTasks3)))
+                    .setStandbyTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology2)
+                        .setPartitions(assignedTasks2)))
+                    .setWarmupTasks(Collections.singletonList(new StreamsGroupDescribeResponseData.TaskIds()
+                        .setSubtopology(subTopology3)
+                        .setPartitions(assignedTasks1)))
+            );
+        // TODO: Add TaskOffsets
+
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void testAsStreamsGroupDescribeWithTargetAssignmentNull() {
+        StreamsGroupMember member = new StreamsGroupMember.Builder(Uuid.randomUuid().toString())
+            .build();
+
+        StreamsGroupDescribeResponseData.Member streamsGroupDescribeMember = member.asStreamsGroupDescribeMember(
+            null);
+
+        assertEquals(new StreamsGroupDescribeResponseData.Assignment(), streamsGroupDescribeMember.targetAssignment());
+    }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index c142c9b9cd7..3da224f3a95 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -88,9 +88,7 @@ public class StreamsGroupTest {
 
         member = streamsGroup.getOrMaybeCreateMember("member", true);
 
-        member = new StreamsGroupMember.Builder(member)
-            .setAssignor("client")
-            .build();
+        member = new StreamsGroupMember.Builder(member).build();
 
         streamsGroup.updateMember(member);
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
new file mode 100644
index 00000000000..7ef086c9be5
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -0,0 +1,182 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
+import org.junit.jupiter.api.Test;
+
+public class StreamsTopologyTest {
+
+    @Test
+    public void streamsTopologyIdShouldBeCorrect() {
+        StreamsTopology topology = new StreamsTopology("topology-id", Collections.emptyMap());
+        assertEquals("topology-id", topology.topologyId());
+    }
+
+    @Test
+    public void subtopologiesShouldBeCorrect() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+        );
+        StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
+        assertEquals(subtopologies, topology.subtopologies());
+    }
+
+    @Test
+    public void topicSubscriptionShouldBeCorrect() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology()
+                .setSourceTopics(Arrays.asList("source-topic-1", "source-topic-2"))
+                .setRepartitionSourceTopics(Arrays.asList(
+                    new TopicInfo().setName("repartition-topic-1"),
+                    new TopicInfo().setName("repartition-topic-2")
+                ))
+            ),
+            mkEntry("subtopology-2", new Subtopology()
+                .setSourceTopics(Arrays.asList("source-topic-3", "source-topic-4"))
+                .setRepartitionSourceTopics(Arrays.asList(
+                    new TopicInfo().setName("repartition-topic-3"),
+                    new TopicInfo().setName("repartition-topic-4")
+                ))
+            )
+        );
+        StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
+        Set<String> expectedTopics = new HashSet<>(Arrays.asList(
+            "source-topic-1", "source-topic-2", "repartition-topic-1", "repartition-topic-2",
+            "source-topic-3", "source-topic-4", "repartition-topic-3", "repartition-topic-4"
+        ));
+        assertEquals(expectedTopics, topology.topicSubscription());
+    }
+
+    @Test
+    public void fromRecordShouldCreateCorrectTopology() {
+        StreamsGroupTopologyValue record = new StreamsGroupTopologyValue()
+            .setTopologyId("topology-id")
+            .setTopology(Arrays.asList(
+                new Subtopology().setSubtopology("subtopology-1"),
+                new Subtopology().setSubtopology("subtopology-2")
+            ));
+        StreamsTopology topology = StreamsTopology.fromRecord(record);
+        assertEquals("topology-id", topology.topologyId());
+        assertEquals(2, topology.subtopologies().size());
+        assertTrue(topology.subtopologies().containsKey("subtopology-1"));
+        assertTrue(topology.subtopologies().containsKey("subtopology-2"));
+    }
+
+    @Test
+    public void equalsShouldReturnTrueForEqualTopologies() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+        );
+        StreamsTopology topology1 = new StreamsTopology("topology-id", subtopologies);
+        StreamsTopology topology2 = new StreamsTopology("topology-id", subtopologies);
+        assertEquals(topology1, topology2);
+    }
+
+    @Test
+    public void equalsShouldReturnFalseForDifferentTopologies() {
+        Map<String, Subtopology> subtopologies1 = mkMap(
+            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1"))
+        );
+        Map<String, Subtopology> subtopologies2 = mkMap(
+            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+        );
+        StreamsTopology topology1 = new StreamsTopology("topology-id-1", subtopologies1);
+        StreamsTopology topology2 = new StreamsTopology("topology-id-2", subtopologies2);
+        assertNotEquals(topology1, topology2);
+    }
+
+    @Test
+    public void hashCodeShouldBeConsistentWithEquals() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+        );
+        StreamsTopology topology1 = new StreamsTopology("topology-id", subtopologies);
+        StreamsTopology topology2 = new StreamsTopology("topology-id", subtopologies);
+        assertEquals(topology1.hashCode(), topology2.hashCode());
+    }
+
+    @Test
+    public void toStringShouldReturnCorrectRepresentation() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology().setSubtopology("subtopology-1")),
+            mkEntry("subtopology-2", new Subtopology().setSubtopology("subtopology-2"))
+        );
+        StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
+        String expectedString = "StreamsTopology{topologyId=topology-id, subtopologies=" + subtopologies + "}";
+        assertEquals(expectedString, topology.toString());
+    }
+
+    @Test
+    public void asStreamsGroupDescribeTopologyShouldReturnCorrectSubtopologies() {
+        Map<String, Subtopology> subtopologies = mkMap(
+            mkEntry("subtopology-1", new Subtopology()
+                .setSourceTopicRegex("regex-1")
+                .setSubtopology("subtopology-1")
+                .setSourceTopics(Collections.singletonList("source-topic-1"))
+                .setRepartitionSinkTopics(Collections.singletonList("sink-topic-1"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(new TopicInfo().setName("repartition-topic-1")))
+                .setStateChangelogTopics(
+                    Collections.singletonList(new TopicInfo().setName("changelog-topic-1")))
+            ),
+            mkEntry("subtopology-2", new Subtopology()
+                .setSourceTopicRegex("regex-2")
+                .setSubtopology("subtopology-2")
+                .setSourceTopics(Collections.singletonList("source-topic-2"))
+                .setRepartitionSinkTopics(Collections.singletonList("sink-topic-2"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(new TopicInfo().setName("repartition-topic-2")))
+                .setStateChangelogTopics(
+                    Collections.singletonList(new TopicInfo().setName("changelog-topic-2")))
+            )
+        );
+        StreamsTopology topology = new StreamsTopology("topology-id", subtopologies);
+        List<StreamsGroupDescribeResponseData.Subtopology> result = topology.asStreamsGroupDescribeTopology();
+        assertEquals(2, result.size());
+        assertEquals("regex-1", result.get(0).sourceTopicRegex());
+        assertEquals("subtopology-1", result.get(0).subtopology());
+        assertEquals(Collections.singletonList("source-topic-1"), result.get(0).sourceTopics());
+        assertEquals(Collections.singletonList("sink-topic-1"), result.get(0).repartitionSinkTopics());
+        assertEquals("repartition-topic-1", result.get(0).repartitionSourceTopics().get(0).name());
+        assertEquals("changelog-topic-1", result.get(0).stateChangelogTopics().get(0).name());
+        assertEquals("regex-2", result.get(1).sourceTopicRegex());
+        assertEquals("subtopology-2", result.get(1).subtopology());
+        assertEquals(Collections.singletonList("source-topic-2"), result.get(1).sourceTopics());
+        assertEquals(Collections.singletonList("sink-topic-2"), result.get(1).repartitionSinkTopics());
+        assertEquals("repartition-topic-2", result.get(1).repartitionSourceTopics().get(0).name());
+        assertEquals("changelog-topic-2", result.get(1).stateChangelogTopics().get(0).name());
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index b16664b8f30..d97832eb969 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -225,8 +225,7 @@ public class TargetAssignmentBuilderTest {
                 .withTopology(topology)
                 .withStaticMembers(staticMembers)
                 .withSubscriptionMetadata(subscriptionMetadata)
-                .withTargetAssignment(targetAssignment)
-                .withTopicsImage(topicsImage);
+                .withTargetAssignment(targetAssignment);
 
             // Add the updated members or delete the deleted members.
             updatedMembers.forEach((memberId, updatedMemberOrNull) -> {
@@ -262,12 +261,10 @@ public class TargetAssignmentBuilderTest {
             .topics();
 
         final Map<String, String> clientTags = mkMap(mkEntry("tag1", "value1"), mkEntry("tag2", "value2"));
-        final Map<String, String> assignmentConfigs = mkMap(mkEntry("conf1", "value1"), mkEntry("conf2", "value2"));
         StreamsGroupMember member = new StreamsGroupMember.Builder("member-id")
             .setRackId("rackId")
             .setInstanceId("instanceId")
             .setProcessId("processId")
-            .setAssignor("assignor")
             .setClientTags(clientTags)
             .build();
 


(kafka) 06/42: Resolve conflict from 11/25 trunk rebase - Create and inject StreamsHeartbeatRequestManager

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit b2e6b80df6e78287cf0dab58b16ee7f77bf836a3
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Mon May 27 23:01:53 2024 +0200

    Resolve conflict from 11/25 trunk rebase - Create and inject StreamsHeartbeatRequestManager
    
    Find a way to inject the StreamsHeartbeatRequestManager into AsyncKafkaConsumer from Kafka Streams
    
    Also trigger assignment logic in Kafka Streams
    
    See https://github.com/lucasbru/kafka/pull/12
---
 .../consumer/internals/RequestManagers.java        |  11 +-
 .../internals/StreamsAssignmentInterface.java      | 138 +++--
 .../internals/StreamsHeartbeatRequestManager.java  | 579 ++++++++++++++++++++-
 .../StreamsInstallAssignmentRequestManager.java    |   2 +-
 .../StreamsPrepareAssignmentRequestManager.java    |   2 +-
 ...ava => StreamsGroupUninitializedException.java} |   4 +-
 ...java => StreamsInvalidAssignmentException.java} |   4 +-
 .../org/apache/kafka/common/protocol/Errors.java   |  10 +-
 .../common/requests/StreamsHeartbeatResponse.java  |  14 +-
 .../common/requests/StreamsInitializeRequest.java  |  17 +-
 .../common/requests/StreamsInitializeResponse.java |  16 +
 .../requests/StreamsInstallAssignmentRequest.java  |  18 +-
 .../requests/StreamsInstallAssignmentResponse.java |  19 +-
 .../requests/StreamsPrepareAssignmentRequest.java  |  18 +-
 .../requests/StreamsPrepareAssignmentResponse.java |  19 +-
 .../common/message/StreamsHeartbeatRequest.json    |   6 +-
 .../common/message/StreamsHeartbeatResponse.json   |  14 +-
 .../StreamsHeartbeatRequestManagerTest.java        | 408 +++++++++++++++
 .../internals/DefaultKafkaClientSupplier.java      |   6 +-
 .../streams/processor/internals/StreamThread.java  | 150 +++++-
 .../internals/StreamsRebalanceListener.java        |   3 +
 .../processor/internals/StreamThreadTest.java      |  50 +-
 22 files changed, 1390 insertions(+), 118 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 65dec12140b..f370cf15c67 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -262,9 +262,18 @@ public class RequestManagers implements Closeable {
                         streamsInstallAssignmentRequestManager = new StreamsInstallAssignmentRequestManager(
                             streamsInstanceMetadata.get());
                         streamsHeartbeatRequestManager = new StreamsHeartbeatRequestManager(
+                            logContext,
+                            time,
+                            config,
+                            coordinator,
                             streamsInitializeRequestManager,
                             streamsPrepareAssignmentRequestManager,
-                            streamsInstanceMetadata.get());
+                            membershipManager,
+                            backgroundEventHandler,
+                            metrics,
+                            streamsInstanceMetadata.get(),
+                            metadata
+                            );
                     } else {
                         heartbeatRequestManager = new HeartbeatRequestManager(
                             logContext,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index acc7e314362..d09ffbda4f4 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -16,28 +16,33 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
+import org.apache.kafka.common.TopicPartition;
+
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * Defines a self-contained object to exchange assignment-related metadata with the Kafka Streams instance.
- *
+ * <p>
  * It's used to exchange information between the streams module and the clients module, and should be mostly self-contained
  */
 public class StreamsAssignmentInterface {
 
     private UUID processID;
 
-    private String userEndPointHost;
+    private HostInfo endPoint;
 
-    private int userEndPointPort;
+    private String assignor;
 
-    private Map<String, SubTopology> subtopologyMap;
+    private Map<String, Subtopology> subtopologyMap;
 
     private Map<String, Object> assignmentConfiguration;
 
@@ -51,15 +56,15 @@ public class StreamsAssignmentInterface {
         return processID;
     }
 
-    public String userEndPointHost() {
-        return userEndPointHost;
+    public HostInfo endPoint() {
+        return endPoint;
     }
 
-    public int userEndPointPort() {
-        return userEndPointPort;
+    public String assignor() {
+        return assignor;
     }
 
-    public Map<String, SubTopology> subtopologyMap() {
+    public Map<String, Subtopology> subtopologyMap() {
         return subtopologyMap;
     }
 
@@ -67,6 +72,7 @@ public class StreamsAssignmentInterface {
         return assignmentConfiguration;
     }
 
+    // TODO: This needs to be used somewhere
     public Map<TaskId, Long> taskLags() {
         return taskLags;
     }
@@ -84,19 +90,45 @@ public class StreamsAssignmentInterface {
         shutdownRequested.set(true);
     }
 
+    // TODO: This needs to be checked somewhere.
     public boolean shutdownRequested() {
         return shutdownRequested.get();
     }
 
+    // TODO: This needs to be called somewhere
     public void setTaskLags(Map<TaskId, Long> taskLags) {
         this.taskLags = taskLags;
     }
 
-    // TODO: Reconciled assignment updated by the stream thread
-    public final Assignment reconciledAssignment = new Assignment();
+    public final AtomicReference<Assignment> reconciledAssignment = new AtomicReference<>();
+
+    public final AtomicReference<Assignment> targetAssignment = new AtomicReference<>();
+
+    /**
+     * List of partitions available on each host. Updated by the streams protocol client.
+     */
+    public final AtomicReference<Map<HostInfo, List<TopicPartition>>> partitionsByHost = new AtomicReference<>();
+
+    public static class HostInfo {
+
+        public final String host;
+
+        public final int port;
+
+        public HostInfo(final String host, final int port) {
+            this.host = host;
+            this.port = port;
+        }
+
+        @Override
+        public String toString() {
+            return "HostInfo{" +
+                "host='" + host + '\'' +
+                ", port=" + port +
+                '}';
+        }
 
-    // TODO: Target assignment read by the stream thread
-    public final Assignment targetAssignment = new Assignment();
+    }
 
     public static class Assignment {
 
@@ -106,6 +138,37 @@ public class StreamsAssignmentInterface {
 
         public final Set<TaskId> warmupTasks = new HashSet<>();
 
+        public Assignment() {
+        }
+
+        public Assignment(final Set<TaskId> activeTasks, final Set<TaskId> standbyTasks, final Set<TaskId> warmupTasks) {
+            this.activeTasks.addAll(activeTasks);
+            this.standbyTasks.addAll(standbyTasks);
+            this.warmupTasks.addAll(warmupTasks);
+        }
+
+        @Override
+        public boolean equals(final Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+            final Assignment that = (Assignment) o;
+            return Objects.equals(activeTasks, that.activeTasks)
+                && Objects.equals(standbyTasks, that.standbyTasks)
+                && Objects.equals(warmupTasks, that.warmupTasks);
+        }
+
+        @Override
+        public int hashCode() {
+            return Objects.hash(activeTasks, standbyTasks, warmupTasks);
+        }
+
+        public Assignment copy() {
+            return new Assignment(activeTasks, standbyTasks, warmupTasks);
+        }
     }
 
     public static class TopicInfo {
@@ -130,53 +193,54 @@ public class StreamsAssignmentInterface {
     }
 
     public static class TaskId {
+
         public final String subtopologyId;
-        public final int taskId;
+        public final int partitionId;
 
-        public int taskId() {
-            return taskId;
+        public int partitionId() {
+            return partitionId;
         }
 
         public String subtopologyId() {
             return subtopologyId;
         }
 
-        public TaskId(final String subtopologyId, final int taskId) {
+        public TaskId(final String subtopologyId, final int partitionId) {
             this.subtopologyId = subtopologyId;
-            this.taskId = taskId;
+            this.partitionId = partitionId;
         }
 
         @Override
         public String toString() {
             return "TaskId{" +
                 "subtopologyId=" + subtopologyId +
-                ", taskId=" + taskId +
+                ", partitionId=" + partitionId +
                 '}';
         }
     }
 
-    public static class SubTopology {
+    public static class Subtopology {
 
-        public final Set<String> sinkTopics;
         public final Set<String> sourceTopics;
+        public final Set<String> sinkTopics;
         public final Map<String, TopicInfo> stateChangelogTopics;
         public final Map<String, TopicInfo> repartitionSourceTopics;
 
-       public SubTopology(final Set<String> sinkTopics,
-                          final Set<String> sourceTopics,
-                          final Map<String, TopicInfo> repartitionSourceTopics,
-                          final Map<String, TopicInfo> stateChangelogTopics) {
-            this.sinkTopics = sinkTopics;
+        public Subtopology(final Set<String> sourceTopics,
+                           final Set<String> sinkTopics,
+                           final Map<String, TopicInfo> repartitionSourceTopics,
+                           final Map<String, TopicInfo> stateChangelogTopics) {
             this.sourceTopics = sourceTopics;
+            this.sinkTopics = sinkTopics;
             this.stateChangelogTopics = stateChangelogTopics;
             this.repartitionSourceTopics = repartitionSourceTopics;
         }
 
         @Override
         public String toString() {
-            return "SubTopology{" +
-                "sinkTopics=" + sinkTopics +
-                ", sourceTopics=" + sourceTopics +
+            return "Subtopology{" +
+                "sourceTopics=" + sourceTopics +
+                ", sinkTopics=" + sinkTopics +
                 ", stateChangelogTopics=" + stateChangelogTopics +
                 ", repartitionSourceTopics=" + repartitionSourceTopics +
                 '}';
@@ -184,15 +248,15 @@ public class StreamsAssignmentInterface {
     }
 
     public StreamsAssignmentInterface(UUID processID,
-                                      String userEndPointHost,
-                                      int userEndPointPort,
-                                      Map<String, SubTopology> subtopologyMap,
+                                      HostInfo endPoint,
+                                      String assignor,
+                                      Map<String, Subtopology> subtopologyMap,
                                       Map<String, Object> assignmentConfiguration,
                                       Map<String, String> clientTags
-                                      ) {
+    ) {
         this.processID = processID;
-        this.userEndPointHost = userEndPointHost;
-        this.userEndPointPort = userEndPointPort;
+        this.endPoint = endPoint;
+        this.assignor = assignor;
         this.subtopologyMap = subtopologyMap;
         this.assignmentConfiguration = assignmentConfiguration;
         this.taskLags = new HashMap<>();
@@ -204,8 +268,8 @@ public class StreamsAssignmentInterface {
     public String toString() {
         return "StreamsAssignmentMetadata{" +
             "processID=" + processID +
-            ", userEndPointHost='" + userEndPointHost + '\'' +
-            ", userEndPointPort=" + userEndPointPort +
+            ", endPoint='" + endPoint + '\'' +
+            ", assignor='" + assignor + '\'' +
             ", subtopologyMap=" + subtopologyMap +
             ", assignmentConfiguration=" + assignmentConfiguration +
             ", taskLags=" + taskLags +
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
index 685ab28da69..ffa6bb2657f 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
@@ -18,15 +18,16 @@ package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.clients.CommonClientConfigs;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
-import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
 import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
 import org.apache.kafka.clients.consumer.internals.events.ErrorEvent;
 import org.apache.kafka.clients.consumer.internals.metrics.HeartbeatMetricsManager;
+import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.GroupAuthorizationException;
 import org.apache.kafka.common.errors.RetriableException;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskId;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
@@ -42,27 +43,599 @@ import org.slf4j.Logger;
 
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 public class StreamsHeartbeatRequestManager implements RequestManager {
 
+    private final Logger logger;
+
+    private final CoordinatorRequestManager coordinatorRequestManager;
+
+    private final StreamsHeartbeatRequestManager.HeartbeatRequestState heartbeatRequestState;
+
+    private final StreamsHeartbeatRequestManager.HeartbeatState heartbeatState;
+
+    private final MembershipManager membershipManager;
+
+    private final StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager;
+
+    private final StreamsInitializeRequestManager streamsInitializeRequestManager;
+
+    private final BackgroundEventHandler backgroundEventHandler;
+
+    private final Timer pollTimer;
+
+    private final HeartbeatMetricsManager metricsManager;
+
     private StreamsAssignmentInterface streamsInterface;
 
+    private final Map<String, Uuid> assignedTopicIdCache;
+
+    private final ConsumerMetadata metadata;
+
     public StreamsHeartbeatRequestManager(
+        final LogContext logContext,
+        final Time time,
+        final ConsumerConfig config,
+        final CoordinatorRequestManager coordinatorRequestManager,
         final StreamsInitializeRequestManager streamsInitializeRequestManager,
         final StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager,
-        final StreamsAssignmentInterface streamsAssignmentInterface
+        final MembershipManager membershipManager,
+        final BackgroundEventHandler backgroundEventHandler,
+        final Metrics metrics,
+        final StreamsAssignmentInterface streamsAssignmentInterface,
+        final ConsumerMetadata metadata
     ) {
+        this.coordinatorRequestManager = coordinatorRequestManager;
+        this.logger = logContext.logger(getClass());
+        this.membershipManager = membershipManager;
+        this.streamsInitializeRequestManager = streamsInitializeRequestManager;
+        this.streamsPrepareAssignmentRequestManager = streamsPrepareAssignmentRequestManager;
+        this.backgroundEventHandler = backgroundEventHandler;
+        int maxPollIntervalMs = config.getInt(CommonClientConfigs.MAX_POLL_INTERVAL_MS_CONFIG);
+        long retryBackoffMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG);
+        long retryBackoffMaxMs = config.getLong(ConsumerConfig.RETRY_BACKOFF_MAX_MS_CONFIG);
+        this.heartbeatState = new StreamsHeartbeatRequestManager.HeartbeatState(streamsAssignmentInterface, membershipManager,
+            maxPollIntervalMs);
+        this.heartbeatRequestState = new StreamsHeartbeatRequestManager.HeartbeatRequestState(logContext, time, 0, retryBackoffMs,
+            retryBackoffMaxMs, maxPollIntervalMs);
+        this.pollTimer = time.timer(maxPollIntervalMs);
+        this.metricsManager = new HeartbeatMetricsManager(metrics);
         this.streamsInterface = streamsAssignmentInterface;
+        this.assignedTopicIdCache = new HashMap<>();
+        this.metadata = metadata;
     }
 
     @Override
     public NetworkClientDelegate.PollResult poll(long currentTimeMs) {
-        return null;
+        if (!coordinatorRequestManager.coordinator().isPresent() ||
+            membershipManager.shouldSkipHeartbeat()) {
+            membershipManager.onHeartbeatRequestSkipped();
+            return NetworkClientDelegate.PollResult.EMPTY;
+        }
+        pollTimer.update(currentTimeMs);
+        if (pollTimer.isExpired() && !membershipManager.isLeavingGroup()) {
+            logger.warn("Consumer poll timeout has expired. This means the time between " +
+                "subsequent calls to poll() was longer than the configured max.poll.interval.ms, " +
+                "which typically implies that the poll loop is spending too much time processing " +
+                "messages. You can address this either by increasing max.poll.interval.ms or by " +
+                "reducing the maximum size of batches returned in poll() with max.poll.records.");
+
+            membershipManager.transitionToSendingLeaveGroup(true);
+            NetworkClientDelegate.UnsentRequest leaveHeartbeat = makeHeartbeatRequest(currentTimeMs, true);
+
+            // We can ignore the leave response because we can join before or after receiving the response.
+            heartbeatRequestState.reset();
+            heartbeatState.reset();
+            return new NetworkClientDelegate.PollResult(heartbeatRequestState.heartbeatIntervalMs,
+                Collections.singletonList(leaveHeartbeat));
+        }
+
+        boolean heartbeatNow = membershipManager.shouldHeartbeatNow() && !heartbeatRequestState.requestInFlight();
+        if (!heartbeatRequestState.canSendRequest(currentTimeMs) && !heartbeatNow) {
+            return new NetworkClientDelegate.PollResult(heartbeatRequestState.nextHeartbeatMs(currentTimeMs));
+        }
+
+        NetworkClientDelegate.UnsentRequest request = makeHeartbeatRequest(currentTimeMs, false);
+        return new NetworkClientDelegate.PollResult(heartbeatRequestState.heartbeatIntervalMs, Collections.singletonList(request));
+    }
+
+    @Override
+    public long maximumTimeToWait(long currentTimeMs) {
+        pollTimer.update(currentTimeMs);
+        if (
+            pollTimer.isExpired() ||
+                (membershipManager.shouldHeartbeatNow() && !heartbeatRequestState.requestInFlight())
+        ) {
+            return 0L;
+        }
+        return Math.min(pollTimer.remainingMs() / 2, heartbeatRequestState.nextHeartbeatMs(currentTimeMs));
+    }
+
+    private NetworkClientDelegate.UnsentRequest makeHeartbeatRequest(final long currentTimeMs,
+                                                                     final boolean ignoreResponse) {
+        NetworkClientDelegate.UnsentRequest request = makeHeartbeatRequest(ignoreResponse);
+        heartbeatRequestState.onSendAttempt(currentTimeMs);
+        membershipManager.onHeartbeatRequestSent();
+        metricsManager.recordHeartbeatSentMs(currentTimeMs);
+        return request;
+    }
+
+    private NetworkClientDelegate.UnsentRequest makeHeartbeatRequest(final boolean ignoreResponse) {
+        NetworkClientDelegate.UnsentRequest request = new NetworkClientDelegate.UnsentRequest(
+            new StreamsHeartbeatRequest.Builder(this.heartbeatState.buildRequestData()),
+            coordinatorRequestManager.coordinator());
+        if (ignoreResponse) {
+            return logResponse(request);
+        } else {
+            return request.whenComplete((response, exception) -> {
+                long completionTimeMs = request.handler().completionTimeMs();
+                if (response != null) {
+                    metricsManager.recordRequestLatency(response.requestLatencyMs());
+                    onResponse((StreamsHeartbeatResponse) response.responseBody(), completionTimeMs);
+                } else {
+                    onFailure(exception, completionTimeMs);
+                }
+            });
+        }
+    }
+
+    private NetworkClientDelegate.UnsentRequest logResponse(final NetworkClientDelegate.UnsentRequest request) {
+        return request.whenComplete((response, exception) -> {
+            if (response != null) {
+                metricsManager.recordRequestLatency(response.requestLatencyMs());
+                Errors error =
+                    Errors.forCode(((StreamsHeartbeatResponse) response.responseBody()).data().errorCode());
+                if (error == Errors.NONE) {
+                    logger.debug("StreamsHeartbeat responded successfully: {}", response);
+                } else {
+                    logger.error("StreamsHeartbeat failed because of {}: {}", error, response);
+                }
+            } else {
+                logger.error("StreamsHeartbeat failed because of unexpected exception.", exception);
+            }
+        });
+    }
+
+    private void onFailure(final Throwable exception, final long responseTimeMs) {
+        this.heartbeatRequestState.onFailedAttempt(responseTimeMs);
+        this.heartbeatState.reset();
+        if (exception instanceof RetriableException) {
+            String message = String.format("StreamsHeartbeatRequest failed because of the retriable exception. " +
+                    "Will retry in %s ms: %s",
+                heartbeatRequestState.remainingBackoffMs(responseTimeMs),
+                exception.getMessage());
+            logger.debug(message);
+        } else {
+            logger.error("StreamsHeartbeatRequest failed due to fatal error: {}", exception.getMessage());
+            handleFatalFailure(exception);
+        }
+    }
+
+    private void onResponse(final StreamsHeartbeatResponse response, long currentTimeMs) {
+        if (Errors.forCode(response.data().errorCode()) == Errors.NONE) {
+            onSuccessResponse(response, currentTimeMs);
+        } else {
+            onErrorResponse(response, currentTimeMs);
+        }
+    }
+
+    private void onSuccessResponse(final StreamsHeartbeatResponse response, final long currentTimeMs) {
+        final StreamsHeartbeatResponseData data = response.data();
+
+        heartbeatRequestState.updateHeartbeatIntervalMs(data.heartbeatIntervalMs());
+        heartbeatRequestState.onSuccessfulAttempt(currentTimeMs);
+        heartbeatRequestState.resetTimer();
+
+        if (data.shouldInitializeTopology()) {
+            streamsInitializeRequestManager.initialize();
+        }
+        if (data.shouldComputeAssignment()) {
+            streamsPrepareAssignmentRequestManager.prepareAssignment();
+        }
+        if (data.partitionsByHost() != null) {
+            streamsInterface.partitionsByHost.set(convertHostInfoMap(data));
+        }
+
+        ConsumerGroupHeartbeatResponseData cgData = new ConsumerGroupHeartbeatResponseData();
+        cgData.setMemberId(data.memberId());
+        cgData.setMemberEpoch(data.memberEpoch());
+        cgData.setErrorCode(data.errorCode());
+        cgData.setErrorMessage(data.errorMessage());
+        cgData.setThrottleTimeMs(data.throttleTimeMs());
+        cgData.setHeartbeatIntervalMs(data.heartbeatIntervalMs());
+
+        Errors assignmentError = response.assignmentError();
+        String assignmentErrorMessage = response.data().errorMessage();
+        if (assignmentError != Errors.NONE) {
+            logger.warn("Assignment incomplete. {}. {}", assignmentError.message(), assignmentErrorMessage);
+            switch (assignmentError) {
+                case STREAMS_SHUTDOWN_APPLICATION:
+                    streamsInterface.requestShutdown();
+                    break;
+                case STREAMS_INCONSISTENT_TOPOLOGY:
+                case STREAMS_MISSING_SOURCE_TOPICS:
+                case STREAMS_GROUP_UNINITIALIZED:
+                    break;
+            }
+        }
+
+        if (data.activeTasks() != null && data.standbyTasks() != null && data.warmupTasks() != null) {
+
+            setTargetAssignment(data);
+            setTargetAssignmentForConsumerGroup(data, cgData);
+
+        } else {
+            if (data.activeTasks() != null || data.standbyTasks() != null || data.warmupTasks() != null) {
+                throw new IllegalStateException("Invalid response data, task collections must be all null or all non-null: " + data);
+            }
+        }
+
+        membershipManager.onHeartbeatSuccess(cgData);
+    }
+
+    private void setTargetAssignmentForConsumerGroup(final StreamsHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
+        Map<String, TopicPartitions> tps = new HashMap<>();
+        data.activeTasks().forEach(taskId -> Stream.concat(
+                streamsInterface.subtopologyMap().get(taskId.subtopology()).sourceTopics.stream(),
+                streamsInterface.subtopologyMap().get(taskId.subtopology()).repartitionSourceTopics.keySet().stream()
+            )
+            .forEach(topic -> {
+                final TopicPartitions toInsert = tps.computeIfAbsent(topic, k -> {
+                    final Optional<Uuid> uuid = findTopicIdInGlobalOrLocalCache(topic);
+                    if (uuid.isPresent()) {
+                        TopicPartitions t =
+                            new TopicPartitions();
+                        t.setTopicId(uuid.get());
+                        return t;
+                    } else {
+                        return null;
+                    }
+                });
+                if (toInsert != null) {
+                    toInsert.partitions().addAll(taskId.partitions());
+                }
+            }));
+        ConsumerGroupHeartbeatResponseData.Assignment cgAssignment = new ConsumerGroupHeartbeatResponseData.Assignment();
+        cgAssignment.setTopicPartitions(new ArrayList<>(tps.values()));
+        cgData.setAssignment(cgAssignment);
+    }
+
+    private void setTargetAssignment(final StreamsHeartbeatResponseData data) {
+        Assignment targetAssignment = new Assignment();
+        updateTaskIdCollection(data.activeTasks(), targetAssignment.activeTasks);
+        updateTaskIdCollection(data.standbyTasks(), targetAssignment.standbyTasks);
+        updateTaskIdCollection(data.warmupTasks(), targetAssignment.warmupTasks);
+        streamsInterface.targetAssignment.set(targetAssignment);
+    }
+
+    private static Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> convertHostInfoMap(
+        final StreamsHeartbeatResponseData data) {
+        Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> partitionsByHost = new HashMap<>();
+        data.partitionsByHost().forEach(hostInfo -> {
+            List<TopicPartition> topicPartitions = hostInfo.partitions().stream()
+                .flatMap(partition ->
+                    partition.partitions().stream().map(partitionId -> new TopicPartition(partition.topic(), partitionId)))
+                .collect(Collectors.toList());
+            partitionsByHost.put(new StreamsAssignmentInterface.HostInfo(hostInfo.host(), hostInfo.port()), topicPartitions);
+        });
+        return partitionsByHost;
+    }
+
+    private void updateTaskIdCollection(
+        final List<StreamsHeartbeatResponseData.TaskId> source,
+        final Set<StreamsAssignmentInterface.TaskId> target
+    ) {
+        target.clear();
+        source.forEach(taskId -> {
+            taskId.partitions().forEach(partition -> {
+                target.add(new StreamsAssignmentInterface.TaskId(taskId.subtopology(), partition));
+            });
+        });
+    }
+
+    private void onErrorResponse(final StreamsHeartbeatResponse response,
+                                 final long currentTimeMs) {
+        Errors error = Errors.forCode(response.data().errorCode());
+        String errorMessage = response.data().errorMessage();
+        String message;
+
+        this.heartbeatState.reset();
+        this.heartbeatRequestState.onFailedAttempt(currentTimeMs);
+        membershipManager.onHeartbeatFailure();
+
+        switch (error) {
+            case NOT_COORDINATOR:
+                // the manager should retry immediately when the coordinator node becomes available again
+                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is incorrect. " +
+                        "Will attempt to find the coordinator again and retry",
+                    coordinatorRequestManager.coordinator());
+                logInfo(message, response, currentTimeMs);
+                coordinatorRequestManager.markCoordinatorUnknown(errorMessage, currentTimeMs);
+                // Skip backoff so that the next HB is sent as soon as the new coordinator is discovered
+                heartbeatRequestState.reset();
+                break;
+
+            case COORDINATOR_NOT_AVAILABLE:
+                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is not available. " +
+                        "Will attempt to find the coordinator again and retry",
+                    coordinatorRequestManager.coordinator());
+                logInfo(message, response, currentTimeMs);
+                coordinatorRequestManager.markCoordinatorUnknown(errorMessage, currentTimeMs);
+                // Skip backoff so that the next HB is sent as soon as the new coordinator is discovered
+                heartbeatRequestState.reset();
+                break;
+
+            case COORDINATOR_LOAD_IN_PROGRESS:
+                // the manager will backoff and retry
+                message = String.format("StreamsHeartbeatRequest failed because the group coordinator %s is still loading." +
+                        "Will retry",
+                    coordinatorRequestManager.coordinator());
+                logInfo(message, response, currentTimeMs);
+                break;
+
+            case GROUP_AUTHORIZATION_FAILED:
+                GroupAuthorizationException exception =
+                    GroupAuthorizationException.forGroupId(membershipManager.groupId());
+                logger.error("StreamsHeartbeatRequest failed due to group authorization failure: {}", exception.getMessage());
+                handleFatalFailure(error.exception(exception.getMessage()));
+                break;
+
+            case UNRELEASED_INSTANCE_ID:
+                logger.error("StreamsHeartbeatRequest failed due to the instance id {} was not released: {}",
+                    membershipManager.groupInstanceId().orElse("null"), errorMessage);
+                handleFatalFailure(Errors.UNRELEASED_INSTANCE_ID.exception(errorMessage));
+                break;
+
+            case INVALID_REQUEST:
+            case GROUP_MAX_SIZE_REACHED:
+            case UNSUPPORTED_ASSIGNOR:
+            case UNSUPPORTED_VERSION:
+                logger.error("StreamsHeartbeatRequest failed due to error: {}", error);
+                handleFatalFailure(error.exception(errorMessage));
+                break;
+
+            case FENCED_MEMBER_EPOCH:
+                message = String.format("StreamsHeartbeatRequest failed for member %s because epoch %s is fenced.",
+                    membershipManager.memberId(), membershipManager.memberEpoch());
+                logInfo(message, response, currentTimeMs);
+                membershipManager.transitionToFenced();
+                // Skip backoff so that a next HB to rejoin is sent as soon as the fenced member releases its assignment
+                heartbeatRequestState.reset();
+                break;
+
+            case UNKNOWN_MEMBER_ID:
+                message = String.format("StreamsHeartbeatRequest failed because member %s is unknown.",
+                    membershipManager.memberId());
+                logInfo(message, response, currentTimeMs);
+                membershipManager.transitionToFenced();
+                // Skip backoff so that a next HB to rejoin is sent as soon as the fenced member releases its assignment
+                heartbeatRequestState.reset();
+                break;
+
+            default:
+                // If the manager receives an unknown error - there could be a bug in the code or a new error code
+                logger.error("StreamsHeartbeatRequest failed due to unexpected error: {}", error);
+                handleFatalFailure(error.exception(errorMessage));
+                break;
+        }
+    }
+
+    private void logInfo(final String message,
+                         final StreamsHeartbeatResponse response,
+                         final long currentTimeMs) {
+        logger.info("{} in {}ms: {}",
+            message,
+            heartbeatRequestState.remainingBackoffMs(currentTimeMs),
+            response.data().errorMessage());
+    }
+
+    private void handleFatalFailure(Throwable error) {
+        backgroundEventHandler.add(new ErrorEvent(error));
+        membershipManager.transitionToFatal();
+    }
+
+    /**
+     * Represents the state of a heartbeat request, including logic for timing, retries, and exponential backoff. The object extends
+     * {@link RequestState} to enable exponential backoff and duplicated request handling. The two fields that it holds are:
+     */
+    static class HeartbeatRequestState extends RequestState {
+
+        /**
+         * heartbeatTimer tracks the time since the last heartbeat was sent
+         */
+        private final Timer heartbeatTimer;
+
+        /**
+         * The heartbeat interval which is acquired/updated through the heartbeat request
+         */
+        private long heartbeatIntervalMs;
+
+        public HeartbeatRequestState(
+            final LogContext logContext,
+            final Time time,
+            final long heartbeatIntervalMs,
+            final long retryBackoffMs,
+            final long retryBackoffMaxMs,
+            final double jitter) {
+            super(logContext, StreamsHeartbeatRequestManager.HeartbeatRequestState.class.getName(), retryBackoffMs, 2, retryBackoffMaxMs,
+                jitter);
+            this.heartbeatIntervalMs = heartbeatIntervalMs;
+            this.heartbeatTimer = time.timer(heartbeatIntervalMs);
+        }
+
+        private void update(final long currentTimeMs) {
+            this.heartbeatTimer.update(currentTimeMs);
+        }
+
+        public void resetTimer() {
+            this.heartbeatTimer.reset(heartbeatIntervalMs);
+        }
+
+        @Override
+        public boolean canSendRequest(final long currentTimeMs) {
+            update(currentTimeMs);
+            return heartbeatTimer.isExpired() && super.canSendRequest(currentTimeMs);
+        }
+
+        public long nextHeartbeatMs(final long currentTimeMs) {
+            if (heartbeatTimer.remainingMs() == 0) {
+                return this.remainingBackoffMs(currentTimeMs);
+            }
+            return heartbeatTimer.remainingMs();
+        }
+
+        private void updateHeartbeatIntervalMs(final long heartbeatIntervalMs) {
+            if (this.heartbeatIntervalMs == heartbeatIntervalMs) {
+                // no need to update the timer if the interval hasn't changed
+                return;
+            }
+            this.heartbeatIntervalMs = heartbeatIntervalMs;
+            this.heartbeatTimer.updateAndReset(heartbeatIntervalMs);
+        }
+    }
+
+    private Optional<Uuid> findTopicIdInGlobalOrLocalCache(String topicName) {
+        Uuid idFromMetadataCache = metadata.topicIds().getOrDefault(topicName, null);
+        if (idFromMetadataCache != null) {
+            // Add topic name to local cache, so it can be reused if included in a next target
+            // assignment if metadata cache not available.
+            assignedTopicIdCache.put(topicName, idFromMetadataCache);
+            return Optional.of(idFromMetadataCache);
+        } else {
+            Uuid idFromLocalCache = assignedTopicIdCache.getOrDefault(topicName, null);
+            return Optional.ofNullable(idFromLocalCache);
+        }
+    }
+
+    static class HeartbeatState {
+
+        private final MembershipManager membershipManager;
+        private final int rebalanceTimeoutMs;
+        private final StreamsHeartbeatRequestManager.HeartbeatState.SentFields sentFields;
+
+        /*
+         * StreamsGroupMetadata holds the metadata for the streams group
+         */
+        private final StreamsAssignmentInterface streamsInterface;
+
+        public HeartbeatState(
+            final StreamsAssignmentInterface streamsInterface,
+            final MembershipManager membershipManager,
+            final int rebalanceTimeoutMs) {
+            this.membershipManager = membershipManager;
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+            this.sentFields = new StreamsHeartbeatRequestManager.HeartbeatState.SentFields();
+            this.streamsInterface = streamsInterface;
+        }
+
+        public void reset() {
+            sentFields.reset();
+        }
+
+        public StreamsHeartbeatRequestData buildRequestData() {
+            StreamsHeartbeatRequestData data = new StreamsHeartbeatRequestData();
+
+            // GroupId - always sent
+            data.setGroupId(membershipManager.groupId());
+
+            // MemberId - always sent, empty until it has been received from the coordinator
+            data.setMemberId(membershipManager.memberId());
+
+            // MemberEpoch - always sent
+            data.setMemberEpoch(membershipManager.memberEpoch());
+
+            // InstanceId - set if present
+            membershipManager.groupInstanceId().ifPresent(data::setInstanceId);
+
+            boolean joining = membershipManager.state() == MemberState.JOINING;
+
+            // RebalanceTimeoutMs - only sent when joining or if it has changed since the last heartbeat
+            if (joining || sentFields.rebalanceTimeoutMs != rebalanceTimeoutMs) {
+                data.setRebalanceTimeoutMs(rebalanceTimeoutMs);
+                sentFields.rebalanceTimeoutMs = rebalanceTimeoutMs;
+            }
+
+            // Immutable -- only sent when joining
+            if (joining) {
+                data.setProcessId(streamsInterface.processID().toString());
+                HostInfo hostInfo = new HostInfo();
+                hostInfo.setHost(streamsInterface.endPoint().host);
+                hostInfo.setPort(streamsInterface.endPoint().port);
+                data.setHostInfo(hostInfo);
+                data.setAssignor(streamsInterface.assignor());
+                data.setClientTags(streamsInterface.clientTags().entrySet().stream().map(entry -> {
+                    StreamsHeartbeatRequestData.KeyValue tag = new StreamsHeartbeatRequestData.KeyValue();
+                    tag.setKey(entry.getKey());
+                    tag.setValue(entry.getValue());
+                    return tag;
+                }).collect(Collectors.toList()));
+                data.setAssignmentConfigs(streamsInterface.assignmentConfiguration().entrySet().stream().map(entry -> {
+                    StreamsHeartbeatRequestData.KeyValue config = new StreamsHeartbeatRequestData.KeyValue();
+                    config.setKey(entry.getKey());
+                    config.setValue(entry.getValue().toString());
+                    return config;
+                }).collect(Collectors.toList()));
+            } else {
+                // FIXME: This seems to be a bug in the RPC serialization code. The default should be null, but it's empty.
+                data.setAssignor(null);
+            }
+
+            if (streamsInterface.shutdownRequested()) {
+                data.setShutdownApplication(true);
+            }
+
+            Assignment reconciledAssignment = streamsInterface.reconciledAssignment.get();
+
+            if (reconciledAssignment != null) {
+                if (!reconciledAssignment.equals(sentFields.assignment)) {
+                    data.setActiveTasks(convertTaskIdCollection(reconciledAssignment.activeTasks));
+                    data.setStandbyTasks(convertTaskIdCollection(reconciledAssignment.standbyTasks));
+                    data.setWarmupTasks(convertTaskIdCollection(reconciledAssignment.warmupTasks));
+                    sentFields.assignment = reconciledAssignment;
+                }
+            }
+
+            return data;
+        }
+
+        private List<TaskId> convertTaskIdCollection(final Set<StreamsAssignmentInterface.TaskId> tasks) {
+            return tasks.stream()
+                .collect(
+                    Collectors.groupingBy(StreamsAssignmentInterface.TaskId::subtopologyId,
+                        Collectors.mapping(StreamsAssignmentInterface.TaskId::partitionId, Collectors.toList()))
+                )
+                .entrySet()
+                .stream()
+                .map(entry -> {
+                    TaskId id = new TaskId();
+                    id.setSubtopology(entry.getKey());
+                    id.setPartitions(entry.getValue());
+                    return id;
+                })
+                .collect(Collectors.toList());
+        }
+
+        // Fields of StreamsHeartbeatRequest sent in the most recent request
+        static class SentFields {
+
+            private int rebalanceTimeoutMs = -1;
+            private Assignment assignment = null;
+
+            SentFields() {
+            }
+
+            void reset() {
+                rebalanceTimeoutMs = -1;
+                assignment = null;
+            }
+        }
     }
 
 }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
index 7936e885b56..b47572637bb 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInstallAssignmentRequestManager.java
@@ -28,7 +28,7 @@ public class StreamsInstallAssignmentRequestManager implements RequestManager {
 
     @Override
     public PollResult poll(final long currentTimeMs) {
-        return null;
+        return PollResult.EMPTY;
     }
 
 }
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
index 069661f4893..fb4f59cdf96 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsPrepareAssignmentRequestManager.java
@@ -28,7 +28,7 @@ public class StreamsPrepareAssignmentRequestManager implements RequestManager {
 
     @Override
     public PollResult poll(final long currentTimeMs) {
-        return null;
+        return PollResult.EMPTY;
     }
 
     public void prepareAssignment() {
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsGroupUninitializedException.java
similarity index 86%
rename from clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java
rename to clients/src/main/java/org/apache/kafka/common/errors/StreamsGroupUninitializedException.java
index ffd0b63d8e3..204ba1e2186 100644
--- a/clients/src/main/java/org/apache/kafka/common/errors/StreamsMissingInternalTopicsException.java
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsGroupUninitializedException.java
@@ -16,8 +16,8 @@
  */
 package org.apache.kafka.common.errors;
 
-public class StreamsMissingInternalTopicsException extends ApiException {
-    public StreamsMissingInternalTopicsException(String message) {
+public class StreamsGroupUninitializedException extends ApiException {
+    public StreamsGroupUninitializedException(String message) {
         super(message);
     }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignmentException.java
similarity index 86%
rename from clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java
rename to clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignmentException.java
index dd6509f90f0..8fae67b6b4b 100644
--- a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignmentException.java
@@ -16,8 +16,8 @@
  */
 package org.apache.kafka.common.errors;
 
-public class StreamsInvalidAssignment extends ApiException {
-    public StreamsInvalidAssignment(String message) {
+public class StreamsInvalidAssignmentException extends ApiException {
+    public StreamsInvalidAssignmentException(String message) {
         super(message);
     }
 }
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index 9790d87863a..f9f063051b7 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -21,9 +21,9 @@ import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.BrokerIdNotRegisteredException;
 import org.apache.kafka.common.errors.BrokerNotAvailableException;
 import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
-import org.apache.kafka.common.errors.StreamsInvalidAssignment;
+import org.apache.kafka.common.errors.StreamsInvalidAssignmentException;
 import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
-import org.apache.kafka.common.errors.StreamsMissingInternalTopicsException;
+import org.apache.kafka.common.errors.StreamsGroupUninitializedException;
 import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
 import org.apache.kafka.common.errors.StreamsShutdownApplicationException;
 import org.apache.kafka.common.errors.ClusterAuthorizationException;
@@ -428,8 +428,10 @@ public enum Errors {
         StreamsMissingSourceTopicsException::new),
     STREAMS_MISSING_INTERNAL_TOPICS(133, "One or more internal topics are missing.",
         StreamsMissingInternalTopicsException::new),
-    STREAMS_SHUTDOWN_APPLICATION(134, "A client requested the shutdown of the whole application.",
-        StreamsShutdownApplicationException::new);
+    STREAMS_GROUP_UNINITIALIZED(134, "The group is not (fully) initialized, broker-side topology information or internal topics are missing.",
+            StreamsGroupUninitializedException::new),
+    STREAMS_SHUTDOWN_APPLICATION(135, "A client requested the shutdown of the whole application.",
+            StreamsShutdownApplicationException::new);
 
     private static final Logger log = LoggerFactory.getLogger(Errors.class);
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
index 1e8c7a5b7e9..835fec5c8ff 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsHeartbeatResponse.java
@@ -41,7 +41,7 @@ import java.util.Map;
  * - {@link Errors#STREAMS_SHUTDOWN_APPLICATION}
  * - {@link Errors#STREAMS_INCONSISTENT_TOPOLOGY}
  * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
- * - {@link Errors#STREAMS_MISSING_INTERNAL_TOPICS}
+ * - {@link Errors#STREAMS_GROUP_UNINITIALIZED}
  */
 public class StreamsHeartbeatResponse extends AbstractResponse {
     private final StreamsHeartbeatResponseData data;
@@ -71,6 +71,18 @@ public class StreamsHeartbeatResponse extends AbstractResponse {
         data.setThrottleTimeMs(throttleTimeMs);
     }
 
+    /**
+     * Possible error codes.
+     *
+     * - {@link Errors#STREAMS_SHUTDOWN_APPLICATION}
+     * - {@link Errors#STREAMS_INCONSISTENT_TOPOLOGY}
+     * - {@link Errors#STREAMS_MISSING_SOURCE_TOPICS}
+     * - {@link Errors#STREAMS_GROUP_UNINITIALIZED}
+     */
+    public Errors assignmentError() {
+        return Errors.forCode(data.assignmentErrorCode());
+    }
+
     public static StreamsHeartbeatResponse parse(ByteBuffer buffer, short version) {
         return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData(
             new ByteBufferAccessor(buffer), version));
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
index 04072dd8565..83761d805de 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeRequest.java
@@ -1,9 +1,24 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ApiMessage;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
index 7b7d19961de..81c281aba98 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInitializeResponse.java
@@ -1,3 +1,19 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
index d793101c537..7063ec61676 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
@@ -1,10 +1,24 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
 import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
 import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
-import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ApiMessage;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
index 3a09420f796..cc389760577 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
@@ -1,10 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
-import org.apache.kafka.common.message.StreamsInitializeResponseData;
 import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ApiMessage;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
index 3c83273bf4f..adeef79393b 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
@@ -1,10 +1,24 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
 import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
 import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
-import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ApiMessage;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
index 99997022783..f0c478ec81b 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
@@ -1,10 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.requests;
 
-import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
-import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
 import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ApiMessage;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
index c97d0b912ff..cd8df8c477e 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -34,11 +34,11 @@
     { "name": "RebalanceTimeoutMs", "type": "int32", "versions": "0+", "default": -1,
       "about": "-1 if it didn't change since the last heartbeat; the maximum time in milliseconds that the coordinator will wait on the member to revoke its partitions otherwise." },
 
-    // If the topology hash does not match the server's topology hash, return INVALID_TOPOLOGY and send ShouldInitializeTopology to one consumer
     { "name": "TopologyHash", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": null,
       "about": "The hash of the topology. Only sent when memberEpoch = 0. Null otherwise. Used to check if topology corresponds to server-topology. " },
+    { "name": "Assignor", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
+      "about": "The desired assignor. Picked by majority vote among clients. If null, the client votes for the broker to pick the assignor." },
 
-    // The coordinator knows which partitions to fetch from given this information
     { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
     { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
@@ -80,8 +80,6 @@
   ],
   "commonStructs": [
     { "name": "TaskId", "versions": "0+", "fields": [
-      // We are using strings here, to avoid fixing a structure on task IDs which will
-      // allow introducing stable naming for subtopologies in the future.
       { "name": "Subtopology", "type": "string", "versions": "0+",
         "about": "subtopology ID" },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
index 272a5a4cd51..513e1d78911 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
@@ -30,10 +30,6 @@
   // - UNSUPPORTED_ASSIGNOR (version 0+)
   // - UNRELEASED_INSTANCE_ID (version 0+)
   // - GROUP_MAX_SIZE_REACHED (version 0+)
-  // - STREAMS_INCONSISTENT_TOPOLOGY (version 0+)
-  // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
-  // - STREAMS_MISSING_INTERNAL_TOPICS (version 0+)
-  // - STREAMS_SHUTDOWN_APPLICATION (version 0+)
   "fields": [
     // Same as consumer group heart beat
     { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
@@ -55,6 +51,16 @@
     { "name": "ShouldInitializeTopology", "type":  "bool", "versions":  "0+", "default": false,
       "about": "true if this streams application should initialize the topology on the broker" },
 
+    // Possible errors:
+    // - STREAMS_INCONSISTENT_TOPOLOGY (version 0+)
+    // - STREAMS_MISSING_SOURCE_TOPICS (version 0+)
+    // - STREAMS_SHUTDOWN_APPLICATION (version 0+)
+    // - STREAMS_GROUP_UNITIALIZED (version 0+)
+    { "name": "AssignmentErrorCode", "type":  "int16", "versions":  "0+", "default": 0,
+      "about": "An error code relating to the current state of the assignment to this member." },
+    { "name": "AssignmentErrorMessage", "type":  "string", "versions":  "0+", "default": "",
+      "about": "An error message relating to the current state of the assignment to this member." },
+
     // The streams app knows which partitions to fetch from given this information
     { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
new file mode 100644
index 00000000000..17b99c9c72f
--- /dev/null
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
@@ -0,0 +1,408 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.UnsentRequest;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.HostInfo;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TaskId;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.TopicInfo;
+import org.apache.kafka.clients.consumer.internals.events.BackgroundEventHandler;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
+import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
+import org.apache.kafka.common.metrics.Sensor;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.requests.StreamsHeartbeatRequest;
+import org.apache.kafka.common.requests.StreamsHeartbeatResponse;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.utils.LogContext;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.clients.consumer.internals.ConsumerTestBuilder.DEFAULT_MAX_POLL_INTERVAL_MS;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class StreamsHeartbeatRequestManagerTest {
+
+    public static final String TEST_GROUP_ID = "testGroupId";
+    public static final String TEST_MEMBER_ID = "testMemberId";
+    public static final int TEST_MEMBER_EPOCH = 5;
+    public static final String TEST_INSTANCE_ID = "instanceId";
+    public static final int TEST_THROTTLE_TIME_MS = 5;
+    private StreamsHeartbeatRequestManager heartbeatRequestManager;
+
+    private Time time;
+
+    private StreamsAssignmentInterface streamsAssignmentInterface;
+
+    private ConsumerConfig config;
+
+    @Mock
+    private CoordinatorRequestManager coordinatorRequestManager;
+
+    @Mock
+    private StreamsInitializeRequestManager streamsInitializeRequestManager;
+
+    @Mock
+    private StreamsPrepareAssignmentRequestManager streamsPrepareAssignmentRequestManager;
+
+    @Mock
+    private MembershipManager membershipManager;
+
+    @Mock
+    private BackgroundEventHandler backgroundEventHandler;
+
+    @Mock
+    private Metrics metrics;
+
+    @Mock
+    private ConsumerMetadata metadata;
+
+    // Static data for testing
+    private final UUID processID = new UUID(1, 1);
+
+    private final HostInfo endPoint = new HostInfo("localhost", 9092);
+
+    private final String assignor = "test";
+
+    private final Map<String, Subtopology> subtopologyMap = new HashMap<>();
+
+    private final Map<String, Object> assignmentConfiguration = new HashMap<>();
+
+    private final Map<String, String> clientTags = new HashMap<>();
+
+    private final Node coordinatorNode = new Node(1, "localhost", 9092);
+
+    @BeforeEach
+    void setUp() {
+        config = config();
+
+        subtopologyMap.clear();
+        assignmentConfiguration.clear();
+        clientTags.clear();
+        streamsAssignmentInterface =
+            new StreamsAssignmentInterface(
+                processID,
+                endPoint,
+                assignor,
+                subtopologyMap,
+                assignmentConfiguration,
+                clientTags
+            );
+        LogContext logContext = new LogContext("test");
+        time = new MockTime();
+
+        MockitoAnnotations.openMocks(this);
+        when(metrics.sensor(anyString())).thenReturn(mock(Sensor.class));
+        heartbeatRequestManager = new StreamsHeartbeatRequestManager(
+            logContext,
+            time,
+            config,
+            coordinatorRequestManager,
+            streamsInitializeRequestManager,
+            streamsPrepareAssignmentRequestManager,
+            membershipManager,
+            backgroundEventHandler,
+            metrics,
+            streamsAssignmentInterface,
+            metadata
+        );
+
+        when(membershipManager.groupId()).thenReturn(TEST_GROUP_ID);
+        when(membershipManager.memberId()).thenReturn(TEST_MEMBER_ID);
+        when(membershipManager.memberEpoch()).thenReturn(TEST_MEMBER_EPOCH);
+        when(membershipManager.groupInstanceId()).thenReturn(Optional.of(TEST_INSTANCE_ID));
+    }
+
+
+    @Test
+    void testNoHeartbeatIfCoordinatorUnknown() {
+        when(membershipManager.shouldHeartbeatNow()).thenReturn(true);
+        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.empty());
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(0, result.unsentRequests.size());
+        verify(membershipManager).onHeartbeatRequestSkipped();
+    }
+
+    @Test
+    void testNoHeartbeatIfHeartbeatSkipped() {
+        when(membershipManager.shouldSkipHeartbeat()).thenReturn(true);
+        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(coordinatorNode));
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(0, result.unsentRequests.size());
+        verify(membershipManager).onHeartbeatRequestSkipped();
+    }
+
+    @Test
+    void testHeartbeatWhenCoordinatorKnown() {
+        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(coordinatorNode));
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(1, result.unsentRequests.size());
+        assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
+
+        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+
+        assertEquals(TEST_GROUP_ID, request.data().groupId());
+        assertEquals(TEST_MEMBER_ID, request.data().memberId());
+        assertEquals(TEST_MEMBER_EPOCH, request.data().memberEpoch());
+        assertEquals(TEST_INSTANCE_ID, request.data().instanceId());
+
+        // Static information is null
+        assertNull(request.data().processId());
+        assertNull(request.data().hostInfo());
+        assertNull(request.data().assignor());
+        assertNull(request.data().assignmentConfigs());
+        assertNull(request.data().clientTags());
+    }
+
+    @Test
+    void testFullStaticInformationWhenJoining() {
+        mockJoiningState();
+        assignmentConfiguration.put("config1", "value1");
+        clientTags.put("clientTag1", "value2");
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(1, result.unsentRequests.size());
+        assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
+
+        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+
+        assertEquals(processID.toString(), request.data().processId());
+        assertEquals(endPoint.host, request.data().hostInfo().host());
+        assertEquals(endPoint.port, request.data().hostInfo().port());
+        assertEquals(assignor, request.data().assignor());
+        assertEquals(1, request.data().assignmentConfigs().size());
+        assertEquals("config1", request.data().assignmentConfigs().get(0).key());
+        assertEquals("value1", request.data().assignmentConfigs().get(0).value());
+        assertEquals(1, request.data().clientTags().size());
+        assertEquals("clientTag1", request.data().clientTags().get(0).key());
+        assertEquals("value2", request.data().clientTags().get(0).value());
+    }
+
+    @Test
+    void testShutdownRequested() {
+        mockJoiningState();
+        streamsAssignmentInterface.requestShutdown();
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(1, result.unsentRequests.size());
+        assertEquals(Optional.of(coordinatorNode), result.unsentRequests.get(0).node());
+
+        StreamsHeartbeatRequest request = (StreamsHeartbeatRequest) result.unsentRequests.get(0).requestBuilder().build();
+
+        assertEquals(true, request.data().shutdownApplication());
+    }
+
+    @Test
+    void testSuccessfulResponse() {
+        mockJoiningState();
+
+        final Uuid uuid0 = Uuid.randomUuid();
+        final Uuid uuid1 = Uuid.randomUuid();
+
+        final TopicInfo emptyTopicInfo = new TopicInfo(Optional.empty(), Collections.emptyMap());
+
+        when(metadata.topicIds()).thenReturn(
+            mkMap(
+                mkEntry("source0", uuid0),
+                mkEntry("repartition0", uuid1)
+            ));
+
+        streamsAssignmentInterface.subtopologyMap().put("0",
+            new Subtopology(
+                Collections.singleton("source0"),
+                Collections.singleton("sink0"),
+                Collections.singletonMap("repartition0", emptyTopicInfo),
+                Collections.singletonMap("changelog0", emptyTopicInfo)
+            ));
+        streamsAssignmentInterface.subtopologyMap().put("1",
+            new Subtopology(
+                Collections.singleton("source1"),
+                Collections.singleton("sink1"),
+                Collections.singletonMap("repartition1", emptyTopicInfo),
+                Collections.singletonMap("changelog1", emptyTopicInfo)
+            ));
+        streamsAssignmentInterface.subtopologyMap().put("2",
+            new Subtopology(
+                Collections.singleton("source2"),
+                Collections.singleton("sink2"),
+                Collections.singletonMap("repartition2", emptyTopicInfo),
+                Collections.singletonMap("changelog2", emptyTopicInfo)
+            ));
+
+        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
+            .setErrorCode(Errors.NONE.code())
+            .setThrottleTimeMs(0)
+            .setMemberId(TEST_MEMBER_ID)
+            .setMemberEpoch(TEST_MEMBER_EPOCH)
+            .setThrottleTimeMs(TEST_THROTTLE_TIME_MS)
+            .setHeartbeatIntervalMs(1000)
+            .setActiveTasks(Collections.singletonList(
+                new StreamsHeartbeatResponseData.TaskId().setSubtopology("0").setPartitions(Collections.singletonList(0))))
+            .setStandbyTasks(Collections.singletonList(
+                new StreamsHeartbeatResponseData.TaskId().setSubtopology("1").setPartitions(Collections.singletonList(1))))
+            .setWarmupTasks(Collections.singletonList(
+                new StreamsHeartbeatResponseData.TaskId().setSubtopology("2").setPartitions(Collections.singletonList(2))));
+
+        mockResponse(data);
+
+        ArgumentCaptor<ConsumerGroupHeartbeatResponseData> captor = ArgumentCaptor.forClass(ConsumerGroupHeartbeatResponseData.class);
+        verify(membershipManager, times(1)).onHeartbeatSuccess(captor.capture());
+        ConsumerGroupHeartbeatResponseData response = captor.getValue();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertEquals(TEST_MEMBER_ID, response.memberId());
+        assertEquals(TEST_MEMBER_EPOCH, response.memberEpoch());
+        assertEquals(TEST_THROTTLE_TIME_MS, response.throttleTimeMs());
+        assertEquals(1000, response.heartbeatIntervalMs());
+        final List<TopicPartitions> tps = response.assignment().topicPartitions();
+        assertEquals(2, tps.size());
+        assertEquals(mkSet(uuid0, uuid1), tps.stream().map(TopicPartitions::topicId).collect(Collectors.toSet()));
+        assertEquals(Collections.singletonList(0), tps.get(0).partitions());
+        assertEquals(Collections.singletonList(0), tps.get(1).partitions());
+
+        final Assignment targetAssignment = streamsAssignmentInterface.targetAssignment.get();
+        assertEquals(1, targetAssignment.activeTasks.size());
+        final TaskId activeTaskId = targetAssignment.activeTasks.stream().findFirst().get();
+        assertEquals(activeTaskId.subtopologyId, "0");
+        assertEquals(activeTaskId.partitionId, 0);
+
+        assertEquals(1, targetAssignment.standbyTasks.size());
+        final TaskId standbyTaskId = targetAssignment.standbyTasks.stream().findFirst().get();
+        assertEquals(standbyTaskId.subtopologyId, "1");
+        assertEquals(standbyTaskId.partitionId, 1);
+
+        assertEquals(1, targetAssignment.warmupTasks.size());
+        final TaskId warmupTaskId = targetAssignment.warmupTasks.stream().findFirst().get();
+        assertEquals(warmupTaskId.subtopologyId, "2");
+        assertEquals(warmupTaskId.partitionId, 2);
+
+    }
+
+
+    @Test
+    void testPrepareAssignment() {
+        mockJoiningState();
+
+        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
+            .setErrorCode(Errors.NONE.code())
+            .setThrottleTimeMs(0)
+            .setMemberEpoch(TEST_MEMBER_EPOCH)
+            .setShouldComputeAssignment(true);
+
+        mockResponse(data);
+
+        verify(streamsPrepareAssignmentRequestManager).prepareAssignment();
+    }
+
+    @Test
+    void testInitializeTopology() {
+        mockJoiningState();
+
+        StreamsHeartbeatResponseData data = new StreamsHeartbeatResponseData()
+            .setErrorCode(Errors.NONE.code())
+            .setThrottleTimeMs(0)
+            .setMemberEpoch(TEST_MEMBER_EPOCH)
+            .setShouldInitializeTopology(true);
+
+        mockResponse(data);
+
+        verify(streamsInitializeRequestManager).initialize();
+    }
+
+    private void mockResponse(final StreamsHeartbeatResponseData data) {
+
+        NetworkClientDelegate.PollResult result = heartbeatRequestManager.poll(time.milliseconds());
+
+        assertEquals(1, result.unsentRequests.size());
+        final UnsentRequest unsentRequest = result.unsentRequests.get(0);
+        assertEquals(Optional.of(coordinatorNode), unsentRequest.node());
+
+        ClientResponse response = createHeartbeatResponse(unsentRequest, data);
+
+        unsentRequest.handler().onComplete(response);
+    }
+
+    private void mockJoiningState() {
+        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(coordinatorNode));
+        when(membershipManager.state()).thenReturn(MemberState.JOINING);
+    }
+
+    private ClientResponse createHeartbeatResponse(
+        final NetworkClientDelegate.UnsentRequest request,
+        final StreamsHeartbeatResponseData data
+    ) {
+        StreamsHeartbeatResponse response = new StreamsHeartbeatResponse(data);
+        return new ClientResponse(
+            new RequestHeader(ApiKeys.STREAMS_HEARTBEAT, ApiKeys.STREAMS_HEARTBEAT.latestVersion(), "client-id", 1),
+            request.handler(),
+            "0",
+            time.milliseconds(),
+            time.milliseconds(),
+            false,
+            null,
+            null,
+            response);
+    }
+
+    private ConsumerConfig config() {
+        Properties prop = new Properties();
+        prop.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
+        prop.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
+        prop.setProperty(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, String.valueOf(DEFAULT_MAX_POLL_INTERVAL_MS));
+        return new ConsumerConfig(prop);
+    }
+}
\ No newline at end of file
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
index 71ac9982d67..1ec2053b3ec 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
@@ -49,9 +49,9 @@ public class DefaultKafkaClientSupplier implements KafkaClientSupplier {
     }
 
     @Override
-    public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config, StreamsAssignmentInterface assignmentInterface) {
-        ByteArrayDeserializer keyDeserializer = new ByteArrayDeserializer();
-        ByteArrayDeserializer valueDeserializer = new ByteArrayDeserializer();
+    public Consumer<byte[], byte[]> getStreamsRebalanceProtocolConsumer(final Map<String, Object> config, final StreamsAssignmentInterface assignmentInterface) {
+        final ByteArrayDeserializer keyDeserializer = new ByteArrayDeserializer();
+        final ByteArrayDeserializer valueDeserializer = new ByteArrayDeserializer();
         return new AsyncKafkaConsumer<>(new ConsumerConfig(ConsumerConfig.appendDeserializerToConfig(config, keyDeserializer, valueDeserializer)),
             keyDeserializer, valueDeserializer, Optional.of(assignmentInterface));
     }
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index 7433896fab8..f0a27b913f7 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -27,11 +27,14 @@ import org.apache.kafka.clients.consumer.InvalidOffsetException;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.clients.consumer.OffsetResetStrategy;
 import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface;
-import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.SubTopology;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Assignment;
+import org.apache.kafka.clients.consumer.internals.StreamsAssignmentInterface.Subtopology;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.KafkaFuture;
 import org.apache.kafka.common.Metric;
 import org.apache.kafka.common.MetricName;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.PartitionInfo;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.TimeoutException;
@@ -57,7 +60,6 @@ import org.apache.kafka.streams.processor.StateRestoreListener;
 import org.apache.kafka.streams.processor.TaskId;
 import org.apache.kafka.streams.processor.assignment.ProcessId;
 import org.apache.kafka.streams.processor.internals.InternalTopologyBuilder.TopicsInfo;
-import org.apache.kafka.streams.processor.internals.TopologyMetadata.Subtopology;
 import org.apache.kafka.streams.processor.internals.assignment.AssignorError;
 import org.apache.kafka.streams.processor.internals.assignment.ReferenceContainer;
 import org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl;
@@ -67,6 +69,7 @@ import org.apache.kafka.streams.processor.internals.tasks.DefaultTaskManager.Def
 import org.apache.kafka.streams.state.HostInfo;
 import org.apache.kafka.streams.state.internals.ThreadCache;
 
+import java.util.List;
 import org.slf4j.Logger;
 
 import java.time.Duration;
@@ -85,12 +88,14 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.BiConsumer;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 
 import static org.apache.kafka.streams.internals.StreamsConfigUtils.eosEnabled;
 import static org.apache.kafka.streams.processor.internals.ClientUtils.adminClientId;
 import static org.apache.kafka.streams.processor.internals.ClientUtils.consumerClientId;
 import static org.apache.kafka.streams.processor.internals.ClientUtils.restoreConsumerClientId;
 
+@SuppressWarnings("ClassDataAbstractionCoupling")
 public class StreamThread extends Thread implements ProcessingThread {
 
     private static final String THREAD_ID_SUBSTRING = "-StreamThread-";
@@ -347,6 +352,10 @@ public class StreamThread extends Thread implements ProcessingThread {
     // handler for, eg MissingSourceTopicException with named topologies
     private final Queue<StreamsException> nonFatalExceptionsToHandle;
 
+    // These are used only with the Streams Rebalance Protocol client
+    private final StreamsAssignmentInterface streamsAssignmentInterface;
+    private final StreamsMetadataState streamsMetadataState;
+
     // These are used to signal from outside the stream thread, but the variables themselves are internal to the thread
     private final AtomicLong cacheResizeSize = new AtomicLong(-1L);
     private final AtomicBoolean leaveGroupRequested = new AtomicBoolean(false);
@@ -483,6 +492,7 @@ public class StreamThread extends Thread implements ProcessingThread {
         }
 
         final Consumer<byte[], byte[]> mainConsumer;
+        final StreamsAssignmentInterface streamsAssignmentInterface;
         if (consumerConfigs.containsKey(ConsumerConfig.GROUP_PROTOCOL_CONFIG) &&
             consumerConfigs.get(ConsumerConfig.GROUP_PROTOCOL_CONFIG).toString().equalsIgnoreCase(GroupProtocol.CONSUMER.name)) {
             if (topologyMetadata.hasNamedTopologies()) {
@@ -490,7 +500,7 @@ public class StreamThread extends Thread implements ProcessingThread {
             }
             log.info("Streams rebalance protocol enabled");
 
-            StreamsAssignmentInterface streamsAssignmentInterface =
+            streamsAssignmentInterface =
                 initAssignmentInterface(processId,
                 config,
                 parseHostInfo(config.getString(StreamsConfig.APPLICATION_SERVER_CONFIG)),
@@ -499,6 +509,7 @@ public class StreamThread extends Thread implements ProcessingThread {
             mainConsumer = clientSupplier.getStreamsRebalanceProtocolConsumer(consumerConfigs, streamsAssignmentInterface);
         } else {
             mainConsumer = clientSupplier.getConsumer(consumerConfigs);
+            streamsAssignmentInterface = null;
         }
 
         taskManager.setMainConsumer(mainConsumer);
@@ -526,8 +537,9 @@ public class StreamThread extends Thread implements ProcessingThread {
             referenceContainer.nonFatalExceptionsToHandle,
             shutdownErrorHook,
             streamsUncaughtExceptionHandler,
-            cache::resize
-        );
+            cache::resize,
+            streamsAssignmentInterface,
+            referenceContainer.streamsMetadataState);
 
         return streamThread.updateThreadMetadata(adminClientId(clientId));
     }
@@ -541,26 +553,27 @@ public class StreamThread extends Thread implements ProcessingThread {
         }
     }
 
-    private static StreamsAssignmentInterface initAssignmentInterface(UUID processId,
-                                                                      StreamsConfig config,
-                                                                      HostInfo hostInfo,
+    private static StreamsAssignmentInterface initAssignmentInterface(final UUID processId,
+                                                                      final StreamsConfig config,
+                                                                      final HostInfo hostInfo,
                                                                       final TopologyMetadata topologyMetadata) {
         final InternalTopologyBuilder internalTopologyBuilder = topologyMetadata.lookupBuilderForNamedTopology(null);
 
-        Map<String, SubTopology> subtopologyMap = new HashMap<>();
-        for (Map.Entry<Subtopology, TopicsInfo> topicsInfoEntry: internalTopologyBuilder.subtopologyToTopicsInfo().entrySet()) {
+        final Map<String, Subtopology> subtopologyMap = new HashMap<>();
+        for (final Map.Entry<TopologyMetadata.Subtopology, TopicsInfo> topicsInfoEntry : internalTopologyBuilder.subtopologyToTopicsInfo()
+            .entrySet()) {
             subtopologyMap.put(
                 String.valueOf(topicsInfoEntry.getKey().nodeGroupId),
-                new SubTopology(
+                new Subtopology(
                     topicsInfoEntry.getValue().sourceTopics,
                     topicsInfoEntry.getValue().sinkTopics,
                     topicsInfoEntry.getValue().repartitionSourceTopics.entrySet()
                         .stream()
-                        .collect(Collectors.toMap(Map.Entry::getKey , e->
+                        .collect(Collectors.toMap(Map.Entry::getKey, e ->
                             new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs))),
                     topicsInfoEntry.getValue().stateChangelogTopics.entrySet()
                         .stream()
-                        .collect(Collectors.toMap(Map.Entry::getKey , e->
+                        .collect(Collectors.toMap(Map.Entry::getKey, e ->
                             new StreamsAssignmentInterface.TopicInfo(e.getValue().numberOfPartitions(), e.getValue().topicConfigs)))
 
                 )
@@ -569,22 +582,28 @@ public class StreamThread extends Thread implements ProcessingThread {
 
         // TODO: Which of these are actually needed?
         // TODO: Maybe we want to split this into assignment properties and internal topic configuration properties
-        HashMap<String, Object> assignmentProperties = new HashMap<>();
+        final HashMap<String, Object> assignmentProperties = new HashMap<>();
         assignmentProperties.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, config.getInt(StreamsConfig.REPLICATION_FACTOR_CONFIG));
         assignmentProperties.put(StreamsConfig.APPLICATION_SERVER_CONFIG, config.getString(StreamsConfig.APPLICATION_SERVER_CONFIG));
         assignmentProperties.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, config.getInt(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG));
-        assignmentProperties.put(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG, config.getLong(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG));
+        assignmentProperties.put(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG,
+            config.getLong(StreamsConfig.ACCEPTABLE_RECOVERY_LAG_CONFIG));
         assignmentProperties.put(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG, config.getInt(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG));
-        assignmentProperties.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG, config.getLong(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG, config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG, config.getString(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG, config.getList(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG));
-        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG, config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG));
+        assignmentProperties.put(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG,
+            config.getLong(StreamsConfig.WINDOW_STORE_CHANGE_LOG_ADDITIONAL_RETENTION_MS_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG,
+            config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_NON_OVERLAP_COST_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG,
+            config.getString(StreamsConfig.RACK_AWARE_ASSIGNMENT_STRATEGY_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG,
+            config.getList(StreamsConfig.RACK_AWARE_ASSIGNMENT_TAGS_CONFIG));
+        assignmentProperties.put(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG,
+            config.getInt(StreamsConfig.RACK_AWARE_ASSIGNMENT_TRAFFIC_COST_CONFIG));
 
         return new StreamsAssignmentInterface(
             processId,
-            hostInfo.host(),
-            hostInfo.port(),
+            new StreamsAssignmentInterface.HostInfo(hostInfo.host(), hostInfo.port()),
+            null,
             subtopologyMap,
             assignmentProperties,
             config.getClientTags()
@@ -662,8 +681,9 @@ public class StreamThread extends Thread implements ProcessingThread {
                         final Queue<StreamsException> nonFatalExceptionsToHandle,
                         final Runnable shutdownErrorHook,
                         final BiConsumer<Throwable, Boolean> streamsUncaughtExceptionHandler,
-                        final java.util.function.Consumer<Long> cacheResizer
-                        ) {
+                        final java.util.function.Consumer<Long> cacheResizer,
+                        final StreamsAssignmentInterface streamsAssignmentInterface,
+                        final StreamsMetadataState streamsMetadataState) {
         super(threadId);
         this.stateLock = new Object();
         this.adminClient = adminClient;
@@ -684,6 +704,8 @@ public class StreamThread extends Thread implements ProcessingThread {
         this.shutdownErrorHook = shutdownErrorHook;
         this.streamsUncaughtExceptionHandler = streamsUncaughtExceptionHandler;
         this.cacheResizer = cacheResizer;
+        this.streamsAssignmentInterface = streamsAssignmentInterface;
+        this.streamsMetadataState = streamsMetadataState;
 
         // The following sensors are created here but their references are not stored in this object, since within
         // this object they are not recorded. The sensors are created here so that the stream threads starts with all
@@ -1350,6 +1372,86 @@ public class StreamThread extends Thread implements ProcessingThread {
         return pollLatency;
     }
 
+    public void maybeHandleAssignmentFromStreamsRebalanceProtocol() {
+        if (streamsAssignmentInterface != null) {
+
+            if (streamsAssignmentInterface.shutdownRequested()) {
+                assignmentErrorCode.set(AssignorError.SHUTDOWN_REQUESTED.code());
+            }
+
+            // Process metadata from Streams Rebalance Protocol
+            final Map<StreamsAssignmentInterface.HostInfo, List<TopicPartition>> hostInfoListMap = streamsAssignmentInterface.partitionsByHost.get();
+            final Map<HostInfo, Set<TopicPartition>> convertedHostInfoMap = new HashMap<>();
+            hostInfoListMap.forEach((hostInfo, topicPartitions) ->
+                convertedHostInfoMap.put(new HostInfo(hostInfo.host, hostInfo.port), new HashSet<>(topicPartitions)));
+            streamsMetadataState.onChange(
+                convertedHostInfoMap,
+                Collections.emptyMap(), // TODO: We cannot differentiate between standby and active tasks here?!
+                getTopicPartitionInfo(convertedHostInfoMap)
+            );
+
+            // Process assignment from Streams Rebalance Protocol
+            final Assignment newAssignment = streamsAssignmentInterface.targetAssignment.get();
+            if (!newAssignment.equals(streamsAssignmentInterface.reconciledAssignment.get())) {
+
+                final Map<TaskId, Set<TopicPartition>> activeTasksWithPartitions =
+                    pairWithTopicPartitions(newAssignment.activeTasks.stream());
+                final Map<TaskId, Set<TopicPartition>> standbyTasksWithPartitions =
+                    pairWithTopicPartitions(Stream.concat(newAssignment.standbyTasks.stream(), newAssignment.warmupTasks.stream()));
+
+                log.info("Processing new assignment {} from Streams Rebalance Protocol", newAssignment);
+
+                taskManager.handleAssignment(
+                    activeTasksWithPartitions,
+                    standbyTasksWithPartitions
+                );
+            }
+        }
+    }
+
+    static Map<TopicPartition, PartitionInfo> getTopicPartitionInfo(final Map<HostInfo, Set<TopicPartition>> partitionsByHost) {
+        final Map<TopicPartition, PartitionInfo> topicToPartitionInfo = new HashMap<>();
+        for (final Set<TopicPartition> value : partitionsByHost.values()) {
+            for (final TopicPartition topicPartition : value) {
+                topicToPartitionInfo.put(
+                    topicPartition,
+                    new PartitionInfo(
+                        topicPartition.topic(),
+                        topicPartition.partition(),
+                        null,
+                        new Node[0],
+                        new Node[0]
+                    )
+                );
+            }
+        }
+        return topicToPartitionInfo;
+    }
+
+
+    private Map<TaskId, Set<TopicPartition>> pairWithTopicPartitions(final Stream<StreamsAssignmentInterface.TaskId> taskIdStream) {
+        return taskIdStream
+            .collect(Collectors.toMap(
+                this::toTaskId,
+                task -> toTopicPartitions(task, streamsAssignmentInterface.subtopologyMap().get(task.subtopologyId))
+            ));
+    }
+
+    private TaskId toTaskId(final StreamsAssignmentInterface.TaskId task) {
+        return new TaskId(Integer.parseInt(task.subtopologyId), task.partitionId);
+    }
+
+    private Set<TopicPartition> toTopicPartitions(final StreamsAssignmentInterface.TaskId task,
+                                                  final Subtopology subTopology) {
+        return
+            Stream.concat(
+                subTopology.sourceTopics.stream(),
+                subTopology.repartitionSourceTopics.keySet().stream()
+            )
+            .map(t -> new TopicPartition(t, task.partitionId))
+            .collect(Collectors.toSet());
+    }
+
     /**
      * Get the next batch of records by polling.
      *
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
index 9ee34d8398b..49428724b1a 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamsRebalanceListener.java
@@ -51,6 +51,9 @@ public class StreamsRebalanceListener implements ConsumerRebalanceListener {
 
     @Override
     public void onPartitionsAssigned(final Collection<TopicPartition> partitions) {
+
+        streamThread.maybeHandleAssignmentFromStreamsRebalanceProtocol();
+
         // NB: all task management is already handled by:
         // org.apache.kafka.streams.processor.internals.StreamsPartitionAssignor.onAssignment
         if (assignmentErrorCode.get() == AssignorError.INCOMPLETE_SOURCE_TOPIC_METADATA.code()) {
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamThreadTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamThreadTest.java
index 8a3e6c17d8a..9efb5780732 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamThreadTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StreamThreadTest.java
@@ -1447,8 +1447,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ).updateThreadMetadata(adminClientId(CLIENT_ID));
+            null,
+            null,
+            null).updateThreadMetadata(adminClientId(CLIENT_ID));
 
         final StreamsException thrown = assertThrows(StreamsException.class, thread::run);
 
@@ -2673,8 +2674,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(State.PENDING_SHUTDOWN);
@@ -2731,8 +2733,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(State.PENDING_SHUTDOWN);
@@ -2798,8 +2801,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(State.PENDING_SHUTDOWN);
@@ -2861,8 +2865,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(State.PENDING_SHUTDOWN);
@@ -2921,8 +2926,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(State.PENDING_SHUTDOWN);
@@ -3154,8 +3160,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        );
+            null,
+            null,
+            null);
         final MetricName testMetricName = new MetricName("test_metric", "", "", new HashMap<>());
         final Metric testMetric = new KafkaMetric(
             new Object(),
@@ -3210,8 +3217,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             (e, b) -> { },
-            null
-        ) {
+            null,
+            null,
+            null) {
             @Override
             void runOnceWithProcessingThreads() {
                 setState(StreamThread.State.PENDING_SHUTDOWN);
@@ -3589,8 +3597,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             null,
-            null
-        );
+            null,
+            null,
+            null);
     }
 
     private TaskManager mockTaskManager(final Task runningTask) {
@@ -3710,8 +3719,9 @@ public class StreamThreadTest {
             new LinkedList<>(),
             null,
             HANDLER,
-            null
-        );
+            null,
+            null,
+            null);
     }
     
     private void runOnce(final boolean processingThreadsEnabled) {


(kafka) 18/42: Resolve conflicts for 11/25 trunk rebase - Rebased on AK trunk 2024-07-16

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 6c36a43fe9d6f9bc69a279ba418f094900e3321a
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Tue Jul 16 16:02:52 2024 +0200

    Resolve conflicts for 11/25 trunk rebase - Rebased on AK trunk 2024-07-16
---
 .../org/apache/kafka/common/protocol/ApiKeys.java  |  2 -
 .../requests/StreamsInstallAssignmentRequest.java  | 77 -----------------
 .../requests/StreamsInstallAssignmentResponse.java | 75 -----------------
 .../requests/StreamsPrepareAssignmentRequest.java  | 77 -----------------
 .../requests/StreamsPrepareAssignmentResponse.java | 75 -----------------
 .../message/StreamsGroupDescribeRequest.json       |  2 +-
 .../message/StreamsGroupDescribeResponse.json      |  2 +-
 .../common/message/StreamsHeartbeatRequest.json    |  2 +-
 .../common/message/StreamsHeartbeatResponse.json   |  2 +-
 .../common/message/StreamsInitializeRequest.json   |  2 +-
 .../common/message/StreamsInitializeResponse.json  |  2 +-
 .../message/StreamsInstallAssignmentRequest.json   | 39 ---------
 .../message/StreamsInstallAssignmentResponse.json  | 26 ------
 .../message/StreamsPrepareAssignmentRequest.json   | 16 ----
 .../message/StreamsPrepareAssignmentResponse.json  | 98 ----------------------
 .../kafka/common/requests/RequestResponseTest.java | 35 ++++----
 .../group/GroupCoordinatorRecordHelpers.java       | 73 ++++------------
 .../coordinator/group/GroupCoordinatorService.java |  4 +-
 .../coordinator/group/GroupCoordinatorShard.java   | 28 ++++---
 .../coordinator/group/GroupMetadataManager.java    | 64 ++++++++++++++
 .../coordinator/group/streams/StreamsGroup.java    |  3 +-
 .../StreamsGroupCurrentMemberAssignmentKey.json    |  6 +-
 .../message/StreamsGroupMemberMetadataKey.json     |  6 +-
 .../common/message/StreamsGroupMetadataKey.json    |  4 +-
 .../message/StreamsGroupPartitionMetadataKey.json  |  4 +-
 .../StreamsGroupTargetAssignmentMemberKey.json     |  6 +-
 .../StreamsGroupTargetAssignmentMetadataKey.json   |  4 +-
 .../common/message/StreamsGroupTopologyKey.json    |  4 +-
 .../group/GroupCoordinatorRecordHelpersTest.java   |  2 +-
 .../group/streams/StreamsGroupTest.java            | 17 ++--
 .../SmokeTestDriverIntegrationTest.java            |  3 +-
 31 files changed, 151 insertions(+), 609 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index 34ed496e1ec..35548b52ebf 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -133,8 +133,6 @@ public enum ApiKeys {
     READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
     STREAMS_HEARTBEAT(ApiMessageType.STREAMS_HEARTBEAT),
     STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE),
-    STREAMS_INSTALL_ASSIGNMENT(ApiMessageType.STREAMS_INSTALL_ASSIGNMENT),
-    STREAMS_PREPARE_ASSIGNMENT(ApiMessageType.STREAMS_PREPARE_ASSIGNMENT),
     STREAMS_GROUP_DESCRIBE(ApiMessageType.STREAMS_GROUP_DESCRIBE);
     
 
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
deleted file mode 100644
index 7063ec61676..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
-import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-
-public class StreamsInstallAssignmentRequest extends AbstractRequest  {
-
-    public static class Builder extends AbstractRequest.Builder<StreamsInstallAssignmentRequest> {
-        private final StreamsInstallAssignmentRequestData data;
-
-        public Builder(StreamsInstallAssignmentRequestData data) {
-            this(data, false);
-        }
-
-        public Builder(StreamsInstallAssignmentRequestData data, boolean enableUnstableLastVersion) {
-            super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT, enableUnstableLastVersion);
-            this.data = data;
-        }
-
-        @Override
-        public StreamsInstallAssignmentRequest build(short version) {
-            return new StreamsInstallAssignmentRequest(data, version);
-        }
-
-        @Override
-        public String toString() {
-            return data.toString();
-        }
-    }
-
-    private final StreamsInstallAssignmentRequestData data;
-
-    public StreamsInstallAssignmentRequest(StreamsInstallAssignmentRequestData data, short version) {
-        super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT, version);
-        this.data = data;
-    }
-
-    @Override
-    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
-        return new StreamsInstallAssignmentResponse(
-            new StreamsInstallAssignmentResponseData()
-                .setThrottleTimeMs(throttleTimeMs)
-                .setErrorCode(Errors.forException(e).code())
-        );
-    }
-
-    @Override
-    public StreamsInstallAssignmentRequestData data() {
-        return data;
-    }
-
-    public static StreamsInstallAssignmentRequest parse(ByteBuffer buffer, short version) {
-        return new StreamsInstallAssignmentRequest(new StreamsInstallAssignmentRequestData(
-            new ByteBufferAccessor(buffer), version), version);
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
deleted file mode 100644
index cc389760577..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-import java.util.Collections;
-import java.util.Map;
-
-/**
- * Possible error codes.
- *
- * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
- * - {@link Errors#NOT_COORDINATOR}
- * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
- * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
- * - {@link Errors#INVALID_REQUEST}
- * - {@link Errors#INVALID_GROUP_ID}
- * - {@link Errors#GROUP_ID_NOT_FOUND}
- * - {@link Errors#UNKNOWN_MEMBER_ID}
- * - {@link Errors#STALE_MEMBER_EPOCH}
- * - {@link Errors#STREAMS_INVALID_ASSIGNMENT}
- */
-public class StreamsInstallAssignmentResponse extends AbstractResponse {
-
-    private final StreamsInstallAssignmentResponseData data;
-
-    public StreamsInstallAssignmentResponse(StreamsInstallAssignmentResponseData data) {
-        super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT);
-        this.data = data;
-    }
-
-    @Override
-    public StreamsInstallAssignmentResponseData data() {
-        return data;
-    }
-
-    @Override
-    public Map<Errors, Integer> errorCounts() {
-        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
-    }
-
-    @Override
-    public int throttleTimeMs() {
-        return data.throttleTimeMs();
-    }
-
-    @Override
-    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
-        data.setThrottleTimeMs(throttleTimeMs);
-    }
-
-    public static StreamsInstallAssignmentResponse parse(ByteBuffer buffer, short version) {
-        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData(
-            new ByteBufferAccessor(buffer), version));
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
deleted file mode 100644
index adeef79393b..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
-import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-
-public class StreamsPrepareAssignmentRequest extends AbstractRequest  {
-
-    public static class Builder extends AbstractRequest.Builder<StreamsPrepareAssignmentRequest> {
-        private final StreamsPrepareAssignmentRequestData data;
-
-        public Builder(StreamsPrepareAssignmentRequestData data) {
-            this(data, false);
-        }
-
-        public Builder(StreamsPrepareAssignmentRequestData data, boolean enableUnstableLastVersion) {
-            super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT, enableUnstableLastVersion);
-            this.data = data;
-        }
-
-        @Override
-        public StreamsPrepareAssignmentRequest build(short version) {
-            return new StreamsPrepareAssignmentRequest(data, version);
-        }
-
-        @Override
-        public String toString() {
-            return data.toString();
-        }
-    }
-
-    private final StreamsPrepareAssignmentRequestData data;
-
-    public StreamsPrepareAssignmentRequest(StreamsPrepareAssignmentRequestData data, short version) {
-        super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT, version);
-        this.data = data;
-    }
-
-    @Override
-    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
-        return new StreamsPrepareAssignmentResponse(
-            new StreamsPrepareAssignmentResponseData()
-                .setThrottleTimeMs(throttleTimeMs)
-                .setErrorCode(Errors.forException(e).code())
-        );
-    }
-
-    @Override
-    public StreamsPrepareAssignmentRequestData data() {
-        return data;
-    }
-
-    public static StreamsPrepareAssignmentRequest parse(ByteBuffer buffer, short version) {
-        return new StreamsPrepareAssignmentRequest(new StreamsPrepareAssignmentRequestData(
-            new ByteBufferAccessor(buffer), version), version);
-    }
-}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
deleted file mode 100644
index f0c478ec81b..00000000000
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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 org.apache.kafka.common.requests;
-
-import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
-import org.apache.kafka.common.protocol.ApiKeys;
-import org.apache.kafka.common.protocol.ByteBufferAccessor;
-import org.apache.kafka.common.protocol.Errors;
-
-import java.nio.ByteBuffer;
-import java.util.Collections;
-import java.util.Map;
-
-/**
- * Possible error codes.
- *
- * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
- * - {@link Errors#NOT_COORDINATOR}
- * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
- * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
- * - {@link Errors#INVALID_REQUEST}
- * - {@link Errors#INVALID_GROUP_ID}
- * - {@link Errors#GROUP_ID_NOT_FOUND}
- * - {@link Errors#UNKNOWN_MEMBER_ID}
- * - {@link Errors#STALE_MEMBER_EPOCH}
- */
-public class StreamsPrepareAssignmentResponse extends AbstractResponse {
-
-    private final StreamsPrepareAssignmentResponseData data;
-
-    public StreamsPrepareAssignmentResponse(StreamsPrepareAssignmentResponseData data) {
-        super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT);
-        this.data = data;
-    }
-
-    @Override
-    public StreamsPrepareAssignmentResponseData data() {
-        return data;
-    }
-
-    @Override
-    public Map<Errors, Integer> errorCounts() {
-        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
-    }
-
-    @Override
-    public int throttleTimeMs() {
-        return data.throttleTimeMs();
-    }
-
-    @Override
-    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
-        data.setThrottleTimeMs(throttleTimeMs);
-    }
-
-    public static StreamsPrepareAssignmentResponse parse(ByteBuffer buffer, short version) {
-        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData(
-            new ByteBufferAccessor(buffer), version));
-    }
-    
-}
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
index 426e9dd81ed..2c828455a67 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeRequest.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 80,
+  "apiKey": 90,
   "type": "request",
   "listeners": ["zkBroker", "broker"],
   "name": "StreamsGroupDescribeRequest",
diff --git a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
index 3080631d66d..ae4b3f8ea35 100644
--- a/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsGroupDescribeResponse.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 80,
+  "apiKey": 90,
   "type": "response",
   "name": "StreamsGroupDescribeResponse",
   "validVersions": "0",
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
index 2ac6ce2e6e9..4121133c73c 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 76,
+  "apiKey": 89,
   "type": "request",
   "listeners": ["zkBroker", "broker"],
   "name": "StreamsHeartbeatRequest",
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
index 2a3e7f1ea80..9cbbdee2a58 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 76,
+  "apiKey": 89,
   "type": "response",
   "name": "StreamsHeartbeatResponse",
   "validVersions": "0",
diff --git a/clients/src/main/resources/common/message/StreamsInitializeRequest.json b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
index 5acc772321c..b93fd3d7a7f 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsInitializeRequest.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 77,
+  "apiKey": 88,
   "type": "request",
   "listeners": ["zkBroker", "broker"],
   "name": "StreamsInitializeRequest",
diff --git a/clients/src/main/resources/common/message/StreamsInitializeResponse.json b/clients/src/main/resources/common/message/StreamsInitializeResponse.json
index ff73577303e..2b4be5f778d 100644
--- a/clients/src/main/resources/common/message/StreamsInitializeResponse.json
+++ b/clients/src/main/resources/common/message/StreamsInitializeResponse.json
@@ -14,7 +14,7 @@
 // limitations under the License.
 
 {
-  "apiKey": 77,
+  "apiKey": 88,
   "type": "response",
   "name": "StreamsInitializeResponse",
   "validVersions": "0",
diff --git a/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json b/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
deleted file mode 100644
index 847bb9bb215..00000000000
--- a/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
-  "apiKey": 78,
-  "type": "request",
-  "listeners": ["zkBroker", "broker"],
-  "name": "StreamsInstallAssignmentRequest",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  "fields": [
-    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
-      "about": "The group identifier." },
-    { "name": "MemberId", "type": "string", "versions": "0+",
-      "about": "The member id assigned by the group coordinator." },
-    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
-      "about": "The member epoch." },
-    { "name": "GroupEpoch", "type": "int32", "versions": "0+",
-      "about": "The group epoch." },
-    { "name": "Error", "type": "int8", "versions": "0+",
-      "about": "The assignment error; or zero if the assignment is successful." },
-    { "name": "Members", "type": "[]Member", "versions": "0+",
-      "about": "The members.", "fields": [
-      { "name": "MemberId", "type": "string", "versions": "0+",
-        "about": "The member ID." },
-      { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Local assignment for this consumer." },
-      { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Local standby tasks for this consumer." },
-      { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Local warming up tasks for this consumer." }
-    ]}
-  ],
-  "commonStructs": [
-    { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "subtopology ID" },
-      { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "partitions" }
-    ]}
-  ]
-}
\ No newline at end of file
diff --git a/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json b/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json
deleted file mode 100644
index b1fe8e00644..00000000000
--- a/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
-  "apiKey": 78,
-  "type": "response",
-  "name": "StreamsInstallAssignmentResponse",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  // Supported errors:
-  // - GROUP_AUTHORIZATION_FAILED
-  // - NOT_COORDINATOR
-  // - COORDINATOR_NOT_AVAILABLE
-  // - COORDINATOR_LOAD_IN_PROGRESS
-  // - INVALID_REQUEST
-  // - INVALID_GROUP_ID
-  // - GROUP_ID_NOT_FOUND
-  // - UNKNOWN_MEMBER_ID
-  // - STALE_MEMBER_EPOCH
-  // - STREAMS_INVALID_ASSIGNMENT
-  "fields": [
-    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
-      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
-    { "name": "ErrorCode", "type": "int16", "versions": "0+",
-      "about": "The top-level error code, or 0 if there was no error" },
-    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "The top-level error message, or null if there was no error." }
-  ]
-}
diff --git a/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json b/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json
deleted file mode 100644
index 12b9098940c..00000000000
--- a/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
-  "apiKey": 79,
-  "type": "request",
-  "listeners": ["zkBroker", "broker"],
-  "name": "StreamsPrepareAssignmentRequest",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  "fields": [
-    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
-      "about": "The group identifier." },
-    { "name": "MemberId", "type": "string", "versions": "0+",
-      "about": "The member id assigned by the group coordinator." },
-    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
-      "about": "The member epoch." }
-  ]
-}
\ No newline at end of file
diff --git a/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json b/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
deleted file mode 100644
index 1d9622caa9e..00000000000
--- a/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
+++ /dev/null
@@ -1,98 +0,0 @@
-{
-  "apiKey": 79,
-  "type": "response",
-  "name": "StreamsPrepareAssignmentResponse",
-  "validVersions": "0",
-  "flexibleVersions": "0+",
-  // Supported errors:
-  // - GROUP_AUTHORIZATION_FAILED
-  // - NOT_COORDINATOR
-  // - COORDINATOR_NOT_AVAILABLE
-  // - COORDINATOR_LOAD_IN_PROGRESS
-  // - INVALID_REQUEST
-  // - INVALID_GROUP_ID
-  // - GROUP_ID_NOT_FOUND
-  // - UNKNOWN_MEMBER_ID
-  // - STALE_MEMBER_EPOCH
-  "fields": [
-    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
-      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
-    { "name": "ErrorCode", "type": "int16", "versions": "0+",
-      "about": "The top-level error code, or 0 if there was no error" },
-    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "The top-level error message, or null if there was no error." },
-    { "name": "GroupEpoch", "type": "int32", "versions": "0+",
-      "about": "The group epoch." },
-    { "name": "AssignorName", "type": "string", "versions": "0+",
-      "about": "The selected assignor." },
-    { "name": "Members", "type": "[]Member", "versions": "0+",
-      "about": "The members.", "fields": [
-      { "name": "MemberId", "type": "string", "versions": "0+",
-        "about": "The member ID." },
-      { "name": "MemberEpoch", "type": "int32", "versions": "0+",
-        "about": "The member epoch." },
-      { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-        "about": "The member instance ID." },
-      { "name": "RackId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
-        "about": "The rack ID." },
-
-      { "name": "TopologyHash", "type": "bytes", "versions": "0+",
-        "about": "The hash of the topology." },
-
-      { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Target active tasks for this consumer." },
-      { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Target standby tasks for this consumer." },
-      { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
-        "about": "Target warming up tasks for this consumer. " },
-
-      { "name": "ProcessId", "type": "uuid", "versions": "0+",
-        "about": "Identity of the streams instance that may have multiple consumers. " },
-      { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
-        "about": "Used for rack-aware assignment algorithm." },
-      { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
-        "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
-      { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
-        "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
-        "fields": [
-          { "name": "Subtopology", "type": "string", "versions": "0+",
-            "about": "A unique identifier of the subtopology." },
-          { "name": "Partition", "type": "int32", "versions": "0+",
-            "about": "The partition of the input topics." },
-          { "name": "Offset", "type": "int64", "versions": "0+",
-            "about": "The cumulative offset for the task" }
-        ]
-      },
-      { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
-        "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
-      { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
-        "about": "Generic array of assignment configuration strings."}
-    ]},
-    { "name": "Topics", "type": "[]TopicMetadata", "versions": "0+",
-      "about": "The topic-partition metadata.",
-      "fields": [
-        { "name": "TopicId", "type": "uuid", "versions": "0+",
-          "about": "The topic ID." },
-        { "name": "TopicName", "type": "string", "versions": "0+",
-          "about": "The topic name." },
-        { "name": "NumPartitions", "type": "int32", "versions": "0+",
-          "about": "The number of partitions." }
-      ]}
-  ],
-  "commonStructs": [
-    { "name": "TaskIds", "versions": "0+", "fields": [
-      { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "subtopology ID" },
-      { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "partitions" }
-    ]},
-    { "name": "KeyValue", "versions": "0+",
-      "fields": [
-        { "name": "Key", "type": "string", "versions": "0+",
-          "about": "key of the config" },
-        { "name": "Value", "type": "string", "versions": "0+",
-          "about": "value of the config" }
-      ]
-    }
-  ]
-}
\ No newline at end of file
diff --git a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
index da4ae96af47..1772de05e85 100644
--- a/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
+++ b/clients/src/test/java/org/apache/kafka/common/requests/RequestResponseTest.java
@@ -238,10 +238,6 @@ import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
 import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsInitializeRequestData;
 import org.apache.kafka.common.message.StreamsInitializeResponseData;
-import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
-import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
-import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
-import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -4027,13 +4023,13 @@ public class RequestResponseTest {
         return new ReadShareGroupStateSummaryResponse(data);
     }
 
-    private AbstractRequest createStreamsPrepareAssignmentRequest(final short version) {
-        return new StreamsPrepareAssignmentRequest.Builder(new StreamsPrepareAssignmentRequestData()).build(version);
-    }
-
-    private AbstractRequest createStreamsInstallAssignmentRequest(final short version) {
-        return new StreamsInstallAssignmentRequest.Builder(new StreamsInstallAssignmentRequestData()).build(version);
-    }
+//    private AbstractRequest createStreamsPrepareAssignmentRequest(final short version) {
+//        return new StreamsPrepareAssignmentRequest.Builder(new StreamsPrepareAssignmentRequestData()).build(version);
+//    }
+//
+//    private AbstractRequest createStreamsInstallAssignmentRequest(final short version) {
+//        return new StreamsInstallAssignmentRequest.Builder(new StreamsInstallAssignmentRequestData()).build(version);
+//    }
 
     private AbstractRequest createStreamsInitializeRequest(final short version) {
         return new StreamsInitializeRequest.Builder(new StreamsInitializeRequestData()).build(version);
@@ -4043,20 +4039,21 @@ public class RequestResponseTest {
         return new StreamsHeartbeatRequest.Builder(new StreamsHeartbeatRequestData()).build(version);
     }
 
-    private AbstractResponse createStreamsPrepareAssignmentResponse() {
-        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData());
-    }
-
-    private AbstractResponse createStreamsInstallAssignmentResponse() {
-        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData());
-    }
-
+//    private AbstractResponse createStreamsPrepareAssignmentResponse() {
+//        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData());
+//    }
+//
+//    private AbstractResponse createStreamsInstallAssignmentResponse() {
+//        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData());
+//    }
+//
     private AbstractResponse createStreamsInitializeResponse() {
         return new StreamsInitializeResponse(new StreamsInitializeResponseData());
     }
 
     private AbstractResponse createStreamsHeartbeatResponse() {
         return new StreamsHeartbeatResponse(new StreamsHeartbeatResponseData());
+    }
 
     @Test
     public void testInvalidSaslHandShakeRequest() {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
index 842df9d7cbb..78c17bb0863 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpers.java
@@ -155,7 +155,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 11
+                (short) 14
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMemberMetadataValue()
@@ -200,7 +200,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupMemberMetadataKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 11
+                (short) 14
             ),
             null // Tombstone.
         );
@@ -293,7 +293,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 10
+                (short) 13
             ),
             new ApiMessageAndVersion(
                 value,
@@ -315,7 +315,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupPartitionMetadataKey()
                     .setGroupId(groupId),
-                (short) 10
+                (short) 13
             ),
             null // Tombstone.
         );
@@ -346,25 +346,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    /**
-     * Creates a ConsumerGroupMetadata tombstone.
-     *
-     * @param groupId The consumer group id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newGroupEpochTombstoneRecord(
-        String groupId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new ConsumerGroupMetadataKey()
-                    .setGroupId(groupId),
-                (short) 3
-            ),
-            null // Tombstone.
-        );
-    }
-
     public static CoordinatorRecord newStreamsGroupEpochRecord(
         String groupId,
         int newGroupEpoch
@@ -373,7 +354,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 9
+                (short) 12
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataValue()
@@ -396,16 +377,16 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupMetadataKey()
                     .setGroupId(groupId),
-                (short) 9
+                (short) 12
             ),
             null // Tombstone.
         );
     }
 
     /**
-     * Creates a StreamsGroupMetadata tombstone.
+     * Creates a ConsumerGroupMetadata tombstone.
      *
-     * @param groupId The streams group id.
+     * @param groupId The consumer group id.
      * @return The record.
      */
     public static CoordinatorRecord newConsumerGroupEpochTombstoneRecord(
@@ -519,7 +500,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 13
+                (short) 16
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMemberValue()
@@ -547,7 +528,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupTargetAssignmentMemberKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 13
+                (short) 16
             ),
             null // Tombstone.
         );
@@ -606,7 +587,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 12
+                (short) 15
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataValue()
@@ -629,7 +610,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTargetAssignmentMetadataKey()
                     .setGroupId(groupId),
-                (short) 12
+                (short) 15
             ),
             null // Tombstone.
         );
@@ -665,28 +646,6 @@ public class GroupCoordinatorRecordHelpers {
         );
     }
 
-    /**
-     * Creates a ConsumerGroupCurrentMemberAssignment tombstone.
-     *
-     * @param groupId  The consumer group id.
-     * @param memberId The consumer group member id.
-     * @return The record.
-     */
-    public static CoordinatorRecord newCurrentAssignmentTombstoneRecord(
-        String groupId,
-        String memberId
-    ) {
-        return new CoordinatorRecord(
-            new ApiMessageAndVersion(
-                new ConsumerGroupCurrentMemberAssignmentKey()
-                    .setGroupId(groupId)
-                    .setMemberId(memberId),
-                (short) 8
-            ),
-            null // Tombstone
-        );
-    }
-
     public static CoordinatorRecord newStreamsCurrentAssignmentRecord(
         String groupId,
         StreamsGroupMember member
@@ -696,7 +655,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(member.memberId()),
-                (short) 14
+                (short) 17
             ),
             new ApiMessageAndVersion(
                 new StreamsGroupCurrentMemberAssignmentValue()
@@ -783,7 +742,7 @@ public class GroupCoordinatorRecordHelpers {
                 new StreamsGroupCurrentMemberAssignmentKey()
                     .setGroupId(groupId)
                     .setMemberId(memberId),
-                (short) 14
+                (short) 17
             ),
             null // Tombstone
         );
@@ -1356,7 +1315,7 @@ public class GroupCoordinatorRecordHelpers {
                 .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
         });
 
-        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 15),
+        return new CoordinatorRecord(new ApiMessageAndVersion(new StreamsGroupTopologyKey().setGroupId(groupId), (short) 18),
             new ApiMessageAndVersion(value, (short) 0));
     }
 
@@ -1373,7 +1332,7 @@ public class GroupCoordinatorRecordHelpers {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId(groupId),
-                (short) 15
+                (short) 18
             ),
             null // Tombstone
         );
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index 9f180c5798a..20042ebfb06 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -365,7 +365,7 @@ public class GroupCoordinatorService implements GroupCoordinator {
         return runtime.scheduleWriteOperation(
             "streams-group-initialize",
             topicPartitionFor(request.groupId()),
-            Duration.ofMillis(config.offsetCommitTimeoutMs),
+            Duration.ofMillis(config.offsetCommitTimeoutMs()),
             coordinator -> coordinator.streamsInitialize(context, request)
         ).exceptionally(exception -> handleOperationException(
             "streams-group-initialize",
@@ -394,7 +394,7 @@ public class GroupCoordinatorService implements GroupCoordinator {
         return runtime.scheduleWriteOperation(
             "streams-heartbeat",
             topicPartitionFor(request.groupId()),
-            Duration.ofMillis(config.offsetCommitTimeoutMs),
+            Duration.ofMillis(config.offsetCommitTimeoutMs()),
             coordinator -> coordinator.streamsHeartbeat(context, request)
         ).exceptionally(exception -> handleOperationException(
             "streams-heartbeat",
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
index 2d8e5229230..aa0a18d0bff 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorShard.java
@@ -122,6 +122,8 @@ import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.TimeUnit;
 
+import static org.apache.kafka.coordinator.group.Utils.messageOrNull;
+
 /**
  * The group coordinator shard is a replicated state machine that manages the metadata of all
  * classic and consumer groups. It holds the hard and the soft state of the groups. This class
@@ -254,9 +256,9 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                 .withShareGroupHeartbeatInterval(config.shareGroupHeartbeatIntervalMs())
                // TODO: Do we need separate configs for streams groups?
                 .withStreamsGroupAssignors(Collections.singletonList(new MockAssignor()))
-                .withStreamsGroupMaxSize(config.consumerGroupMaxSize)
-                .withStreamsGroupSessionTimeout(config.consumerGroupSessionTimeoutMs)
-                .withStreamsGroupHeartbeatInterval(config.consumerGroupHeartbeatIntervalMs)
+                .withStreamsGroupMaxSize(config.consumerGroupMaxSize())
+                .withStreamsGroupSessionTimeout(config.consumerGroupSessionTimeoutMs())
+                .withStreamsGroupHeartbeatInterval(config.consumerGroupHeartbeatIntervalMs())
                 .withGroupCoordinatorMetricsShard(metricsShard)
                 .build();
 
@@ -851,56 +853,56 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
                     offset,
                     producerId,
                     (OffsetCommitKey) key.message(),
-                    (OffsetCommitValue) Utils.messageOrNull(value)
+                    (OffsetCommitValue) messageOrNull(value)
                 );
                 break;
 
             case 2:
                 groupMetadataManager.replay(
                     (GroupMetadataKey) key.message(),
-                    (GroupMetadataValue) Utils.messageOrNull(value)
+                    (GroupMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 3:
                 groupMetadataManager.replay(
                     (ConsumerGroupMetadataKey) key.message(),
-                    (ConsumerGroupMetadataValue) Utils.messageOrNull(value)
+                    (ConsumerGroupMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 4:
                 groupMetadataManager.replay(
                     (ConsumerGroupPartitionMetadataKey) key.message(),
-                    (ConsumerGroupPartitionMetadataValue) Utils.messageOrNull(value)
+                    (ConsumerGroupPartitionMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 5:
                 groupMetadataManager.replay(
                     (ConsumerGroupMemberMetadataKey) key.message(),
-                    (ConsumerGroupMemberMetadataValue) Utils.messageOrNull(value)
+                    (ConsumerGroupMemberMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 6:
                 groupMetadataManager.replay(
                     (ConsumerGroupTargetAssignmentMetadataKey) key.message(),
-                    (ConsumerGroupTargetAssignmentMetadataValue) Utils.messageOrNull(value)
+                    (ConsumerGroupTargetAssignmentMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 7:
                 groupMetadataManager.replay(
                     (ConsumerGroupTargetAssignmentMemberKey) key.message(),
-                    (ConsumerGroupTargetAssignmentMemberValue) Utils.messageOrNull(value)
+                    (ConsumerGroupTargetAssignmentMemberValue) messageOrNull(value)
                 );
                 break;
 
             case 8:
                 groupMetadataManager.replay(
                     (ConsumerGroupCurrentMemberAssignmentKey) key.message(),
-                    (ConsumerGroupCurrentMemberAssignmentValue) Utils.messageOrNull(value)
+                    (ConsumerGroupCurrentMemberAssignmentValue) messageOrNull(value)
                 );
                 break;
 
@@ -914,14 +916,14 @@ public class GroupCoordinatorShard implements CoordinatorShard<CoordinatorRecord
             case 10:
                 groupMetadataManager.replay(
                     (ShareGroupMemberMetadataKey) key.message(),
-                    (ShareGroupMemberMetadataValue) Utils.messageOrNull(value)
+                    (ShareGroupMemberMetadataValue) messageOrNull(value)
                 );
                 break;
 
             case 11:
                 groupMetadataManager.replay(
                     (ShareGroupMetadataKey) key.message(),
-                    (ShareGroupMetadataValue) Utils.messageOrNull(value)
+                    (ShareGroupMetadataValue) messageOrNull(value)
                 );
                 break;
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 5997591b812..09dd21913e6 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -5238,6 +5238,69 @@ public class GroupMetadataManager {
         }
     }
 
+    /**
+     * Replays StreamsGroupMetadataKey/Value to update the hard state of
+     * the Streams group. It updates the group epoch of the Streams
+     * group or deletes the Streams group.
+     *
+     * @param key   A StreamsGroupMetadataKey key.
+     * @param value A StreamsGroupMetadataValue record.
+     */
+    public void replay(
+        StreamsGroupMetadataKey key,
+        StreamsGroupMetadataValue value
+    ) {
+        String groupId = key.groupId();
+
+        if (value != null) {
+            StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, true);
+            streamsGroup.setGroupEpoch(value.epoch());
+        } else {
+            StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
+            if (!streamsGroup.members().isEmpty()) {
+                throw new IllegalStateException("Received a tombstone record to delete group " + groupId
+                    + " but the group still has " + streamsGroup.members().size() + " members.");
+            }
+            if (!streamsGroup.targetAssignment().isEmpty()) {
+                throw new IllegalStateException("Received a tombstone record to delete group " + groupId
+                    + " but the target assignment still has " + streamsGroup.targetAssignment().size()
+                    + " members.");
+            }
+            if (streamsGroup.assignmentEpoch() != -1) {
+                throw new IllegalStateException("Received a tombstone record to delete group " + groupId
+                    + " but did not receive StreamsGroupTargetAssignmentMetadataValue tombstone.");
+            }
+            removeGroup(groupId);
+        }
+
+    }
+
+    /**
+     * Replays StreamsGroupPartitionMetadataKey/Value to update the hard state of
+     * the streams group. It updates the subscription metadata of the streams
+     * group.
+     *
+     * @param key   A StreamsGroupPartitionMetadataKey key.
+     * @param value A StreamsGroupPartitionMetadataValue record.
+     */
+    public void replay(
+        StreamsGroupPartitionMetadataKey key,
+        StreamsGroupPartitionMetadataValue value
+    ) {
+        String groupId = key.groupId();
+        StreamsGroup streamsGroup = getOrMaybeCreatePersistedStreamsGroup(groupId, false);
+
+        if (value != null) {
+            Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata = new HashMap<>();
+            value.topics().forEach(topicMetadata -> {
+                subscriptionMetadata.put(topicMetadata.topicName(), org.apache.kafka.coordinator.group.streams.TopicMetadata.fromRecord(topicMetadata));
+            });
+            streamsGroup.setSubscriptionMetadata(subscriptionMetadata);
+        } else {
+            streamsGroup.setSubscriptionMetadata(Collections.emptyMap());
+        }
+    }
+
     /**
      * Replays ShareGroupMemberMetadataKey/Value to update the hard state of
      * the share group. It updates the subscription part of the member or
@@ -5299,6 +5362,7 @@ public class GroupMetadataManager {
             if (!shareGroup.members().isEmpty()) {
                 throw new IllegalStateException("Received a tombstone record to delete group " + groupId
                     + " but the group still has " + shareGroup.members().size() + " members.");
+            }
             if (!shareGroup.targetAssignment().isEmpty()) {
                 throw new IllegalStateException("Received a tombstone record to delete group " + groupId
                     + " but the target assignment still has " + shareGroup.targetAssignment().size()
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index f83305e3e1a..7d3465c7ad2 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -811,7 +811,8 @@ public class StreamsGroup implements Group {
         String memberId,
         String groupInstanceId,
         int memberEpoch,
-        boolean isTransactional
+        boolean isTransactional,
+        short apiVersion
     ) throws UnknownMemberIdException, StaleMemberEpochException {
         // When the member epoch is -1, the request comes from either the admin client
         // or a consumer which does not use the group management facility. In this case,
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
index 30f775fa1f8..771f7324a9e 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupCurrentMemberAssignmentKey",
-  "validVersions": "14",
+  "validVersions": "17",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "14",
+    { "name": "GroupId", "type": "string", "versions": "17",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "14",
+    { "name": "MemberId", "type": "string", "versions": "17",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
index 0834b3e41ee..bac9ac247cf 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMemberMetadataKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupMemberMetadataKey",
-  "validVersions": "11",
+  "validVersions": "14",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "11",
+    { "name": "GroupId", "type": "string", "versions": "14",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "11",
+    { "name": "MemberId", "type": "string", "versions": "14",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
index 8f287c05652..26121bf2ba2 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupMetadataKey",
-  "validVersions": "9",
+  "validVersions": "12",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "9",
+    { "name": "GroupId", "type": "string", "versions": "12",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
index 954e5fd1182..546a8f80535 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupPartitionMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupPartitionMetadataKey",
-  "validVersions": "10",
+  "validVersions": "13",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "10",
+    { "name": "GroupId", "type": "string", "versions": "13",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
index 128bf44bba7..4fc8231ec3d 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberKey.json
@@ -17,12 +17,12 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMemberKey",
-  "validVersions": "13",
+  "validVersions": "16",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "13",
+    { "name": "GroupId", "type": "string", "versions": "16",
       "about": "The group id." },
-    { "name": "MemberId", "type": "string", "versions": "13",
+    { "name": "MemberId", "type": "string", "versions": "16",
       "about": "The member id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
index b583b3224b4..02b40f727c4 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMetadataKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTargetAssignmentMetadataKey",
-  "validVersions": "12",
+  "validVersions": "15",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "12",
+    { "name": "GroupId", "type": "string", "versions": "15",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
index 11873d4403c..261b755cd51 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTopologyKey.json
@@ -17,10 +17,10 @@
 {
   "type": "data",
   "name": "StreamsGroupTopologyKey",
-  "validVersions": "15",
+  "validVersions": "18",
   "flexibleVersions": "none",
   "fields": [
-    { "name": "GroupId", "type": "string", "versions": "15",
+    { "name": "GroupId", "type": "string", "versions": "18",
       "about": "The group id." }
   ]
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
index 480c1576440..d6258e13db0 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordHelpersTest.java
@@ -284,7 +284,7 @@ public class GroupCoordinatorRecordHelpersTest {
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyKey()
                     .setGroupId("group-id"),
-                (short) 15),
+                (short) 18),
             new ApiMessageAndVersion(
                 new StreamsGroupTopologyValue()
                     .setTopology(expectedTopology),
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 4dd727b8050..68fddc0654f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -20,8 +20,10 @@ import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.errors.GroupNotEmptyException;
 import org.apache.kafka.common.errors.StaleMemberEpochException;
 import org.apache.kafka.common.errors.UnknownMemberIdException;
+import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.annotation.ApiKeyVersionsSource;
 import org.apache.kafka.coordinator.group.OffsetAndMetadata;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
@@ -605,31 +607,32 @@ public class StreamsGroupTest {
     }
 
     @ParameterizedTest
-    @ValueSource(booleans = {false, true})
-    public void testValidateOffsetCommit(boolean isTransactional) {
+    @ApiKeyVersionsSource(apiKey = ApiKeys.OFFSET_COMMIT)
+    public void testValidateOffsetCommit(short version) {
+        boolean isTransactional = false;
         StreamsGroup group = createStreamsGroup("group-foo");
 
         // Simulate a call from the admin client without member id and member epoch.
         // This should pass only if the group is empty.
-        group.validateOffsetCommit("", "", -1, isTransactional);
+        group.validateOffsetCommit("", "", -1, isTransactional, version);
 
         // The member does not exist.
         assertThrows(UnknownMemberIdException.class, () ->
-            group.validateOffsetCommit("member-id", null, 0, isTransactional));
+            group.validateOffsetCommit("member-id", null, 0, isTransactional, version));
 
         // Create a member.
         group.updateMember(new StreamsGroupMember.Builder("member-id").build());
 
         // A call from the admin client should fail as the group is not empty.
         assertThrows(UnknownMemberIdException.class, () ->
-            group.validateOffsetCommit("", "", -1, isTransactional));
+            group.validateOffsetCommit("", "", -1, isTransactional, version));
 
         // The member epoch is stale.
         assertThrows(StaleMemberEpochException.class, () ->
-            group.validateOffsetCommit("member-id", "", 10, isTransactional));
+            group.validateOffsetCommit("member-id", "", 10, isTransactional, version));
 
         // This should succeed.
-        group.validateOffsetCommit("member-id", "", 0, isTransactional);
+        group.validateOffsetCommit("member-id", "", 0, isTransactional, version);
     }
 
     @Test
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index a747f0aa2a8..a2cb052e7f2 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -105,7 +105,8 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
     // We set 2 timeout condition to fail the test before passing the verification:
     // (1) 10 min timeout, (2) 30 tries of polling without getting any data
     @ParameterizedTest
-    @CsvSource({"false, false", "true, false", "true, true"})
+    @CsvSource({"false, false, true"})
+//    @CsvSource({"false, false", "true, false", "true, true"})
     public void shouldWorkWithRebalance(
         final boolean stateUpdaterEnabled,
         final boolean processingThreadsEnabled,


(kafka) 28/42: Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-09-25

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit d1794f477ba791275c1e1342c8d9ca5d6da92746
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Wed Sep 25 16:02:39 2024 +0200

    Resolve conflict from 11/25 trunk rebase - Rebase on AK trunk 2024-09-25
---
 .../consumer/internals/RequestManagers.java        |  2 +-
 .../internals/StreamsAssignmentInterface.java      | 25 ++++++-------
 .../StreamsGroupHeartbeatRequestManager.java       |  7 ++--
 .../StreamsGroupInitializeRequestManager.java      |  2 +-
 .../events/ApplicationEventProcessor.java          |  6 +--
 .../StreamsGroupHeartbeatRequestManagerTest.java   |  3 +-
 .../kafka/api/IntegrationTestHarness.scala         |  4 ++
 .../src/test/scala/kafka/utils/TestInfoUtils.scala |  4 ++
 .../scala/unit/kafka/server/KafkaApisTest.scala    | 20 +++++-----
 .../coordinator/group/GroupCoordinatorService.java |  9 +++--
 .../group/metrics/GroupCoordinatorMetrics.java     |  2 +
 .../streams/CoordinatorStreamsRecordHelpers.java   |  2 +-
 .../coordinator/group/streams/StreamsGroup.java    |  2 +-
 .../group/streams/TargetAssignmentBuilder.java     |  2 +-
 .../CoordinatorStreamsRecordHelpersTest.java       |  2 +-
 .../group/streams/StreamsGroupBuilder.java         |  2 +-
 .../group/streams/TargetAssignmentBuilderTest.java |  2 +-
 .../SmokeTestDriverIntegrationTest.java            | 10 ++---
 .../org/apache/kafka/streams/GroupProtocol.java    | 43 ++++++++++++++++++++++
 .../org/apache/kafka/streams/StreamsConfig.java    | 17 +++++++++
 .../streams/processor/internals/StreamThread.java  |  5 +--
 21 files changed, 121 insertions(+), 50 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 4f3ec1b2398..9128ee7889b 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -263,7 +263,7 @@ public class RequestManagers implements Closeable {
                             metadata
                             );
                     } else {
-                        heartbeatRequestManager = new HeartbeatRequestManager(
+                        heartbeatRequestManager = new ConsumerHeartbeatRequestManager(
                             logContext,
                             time,
                             config,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index 567fcb5f776..1e23233f4e6 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -37,7 +37,7 @@ import java.util.concurrent.atomic.AtomicReference;
  */
 public class StreamsAssignmentInterface {
 
-    private UUID processID;
+    private UUID processId;
 
     private Optional<HostInfo> endpoint;
 
@@ -53,8 +53,13 @@ public class StreamsAssignmentInterface {
 
     private Map<String, String> clientTags;
 
-    public UUID processID() {
-        return processID;
+    public UUID processId() {
+        return processId;
+    }
+
+    public String topologyId() {
+        // ToDo: As long as we do not compute the topology ID, let's use a constant one
+        return "topology-id";
     }
 
     public Optional<HostInfo> endpoint() {
@@ -73,19 +78,11 @@ public class StreamsAssignmentInterface {
         return assignmentConfiguration;
     }
 
-    // ToDo: As long as we do not compute the topology ID, let's use a constant one
-    public final String topologyId = "topology-id";
-
     // TODO: This needs to be used somewhere
     public Map<TaskId, Long> taskLags() {
         return taskLags;
     }
 
-    public byte[] computeTopologyHash() {
-        // TODO
-        return new byte[0];
-    }
-
     public Map<String, String> clientTags() {
         return clientTags;
     }
@@ -266,14 +263,14 @@ public class StreamsAssignmentInterface {
         }
     }
 
-    public StreamsAssignmentInterface(UUID processID,
+    public StreamsAssignmentInterface(UUID processId,
                                       Optional<HostInfo> endpoint,
                                       String assignor,
                                       Map<String, Subtopology> subtopologyMap,
                                       Map<String, Object> assignmentConfiguration,
                                       Map<String, String> clientTags
     ) {
-        this.processID = processID;
+        this.processId = processId;
         this.endpoint = endpoint;
         this.assignor = assignor;
         this.subtopologyMap = subtopologyMap;
@@ -286,7 +283,7 @@ public class StreamsAssignmentInterface {
     @Override
     public String toString() {
         return "StreamsAssignmentMetadata{" +
-            "processID=" + processID +
+            "processID=" + processId +
             ", endpoint='" + endpoint + '\'' +
             ", assignor='" + assignor + '\'' +
             ", subtopologyMap=" + subtopologyMap +
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index e93b0e51c10..f41ed9d0998 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -34,6 +34,7 @@ import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData.Endpoint;
 import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.ConsumerGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.utils.LogContext;
@@ -264,7 +265,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             }
         }
 
-        membershipManager.onHeartbeatSuccess(cgData);
+        membershipManager.onHeartbeatSuccess(new ConsumerGroupHeartbeatResponse(cgData));
     }
 
     private void setTargetAssignmentForConsumerGroup(final StreamsGroupHeartbeatResponseData data, final ConsumerGroupHeartbeatResponseData cgData) {
@@ -534,7 +535,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             data.setGroupId(membershipManager.groupId());
 
             // TopologyId - always sent
-            data.setTopologyId(streamsInterface.topologyId);
+            data.setTopologyId(streamsInterface.topologyId());
 
             // MemberId - always sent, empty until it has been received from the coordinator
             data.setMemberId(membershipManager.memberId());
@@ -555,7 +556,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
 
             // Immutable -- only sent when joining
             if (joining) {
-                data.setProcessId(streamsInterface.processID().toString());
+                data.setProcessId(streamsInterface.processId().toString());
                 data.setActiveTasks(Collections.emptyList());
                 data.setStandbyTasks(Collections.emptyList());
                 data.setWarmupTasks(Collections.emptyList());
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
index 0a6a67594c1..64565f347b1 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
@@ -68,7 +68,7 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
     private NetworkClientDelegate.UnsentRequest makeRequest() {
         final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = new StreamsGroupInitializeRequestData();
         streamsGroupInitializeRequestData.setGroupId(groupId);
-        streamsGroupInitializeRequestData.setTopologyId(streamsAssignmentInterface.topologyId);
+        streamsGroupInitializeRequestData.setTopologyId(streamsAssignmentInterface.topologyId());
         final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
         streamsGroupInitializeRequestData.setTopology(topology);
         final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
index 2a84c18e234..52aee8f20e0 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/events/ApplicationEventProcessor.java
@@ -367,8 +367,8 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
      *              the group is sent out.
      */
     private void process(final UnsubscribeEvent event) {
-        if (requestManagers.consumerHeartbeatRequestManager.isPresent()) {
-            CompletableFuture<Void> future = requestManagers.consumerHeartbeatRequestManager.get().membershipManager().leaveGroup();
+        if (requestManagers.consumerMembershipManager.isPresent()) {
+            CompletableFuture<Void> future = requestManagers.consumerMembershipManager.get().leaveGroup();
             future.whenComplete(complete(event.future()));
         } else {
             // If the consumer is not using the group management capabilities, we still need to clear all assignments it may have.
@@ -417,7 +417,7 @@ public class ApplicationEventProcessor implements EventProcessor<ApplicationEven
             );
             return;
         }
-        requestManagers.consumerHeartbeatRequestManager.get().membershipManager().consumerRebalanceListenerCallbackCompleted(event);
+        requestManagers.consumerMembershipManager.get().consumerRebalanceListenerCallbackCompleted(event);
     }
 
     private void process(@SuppressWarnings("unused") final CommitOnCloseEvent event) {
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index b9fdb4c7722..503576d8fd5 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -32,6 +32,7 @@ import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
 import org.apache.kafka.common.metrics.Sensor;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.requests.ConsumerGroupHeartbeatResponse;
 import org.apache.kafka.common.requests.RequestHeader;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
@@ -290,7 +291,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
         mockResponse(data);
 
         ArgumentCaptor<ConsumerGroupHeartbeatResponseData> captor = ArgumentCaptor.forClass(ConsumerGroupHeartbeatResponseData.class);
-        verify(membershipManager, times(1)).onHeartbeatSuccess(captor.capture());
+        verify(membershipManager, times(1)).onHeartbeatSuccess(new ConsumerGroupHeartbeatResponse(captor.capture()));
         ConsumerGroupHeartbeatResponseData response = captor.getValue();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertEquals(TEST_MEMBER_ID, response.memberId());
diff --git a/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala b/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
index b7efed1d495..a66752c30f3 100644
--- a/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
+++ b/core/src/test/scala/integration/kafka/api/IntegrationTestHarness.scala
@@ -74,6 +74,10 @@ abstract class IntegrationTestHarness extends KafkaServerTestHarness {
       cfgs.foreach(_.setProperty(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,consumer,share"))
       cfgs.foreach(_.setProperty(ServerConfigs.UNSTABLE_API_VERSIONS_ENABLE_CONFIG, "true"))
     }
+    if (isStreamsGroupTest()) {
+      cfgs.foreach(_.setProperty(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG, "classic,consumer,streams"))
+      cfgs.foreach(_.setProperty(ServerConfigs.UNSTABLE_API_VERSIONS_ENABLE_CONFIG, "true"))
+    }
 
     if(isKRaftTest()) {
       cfgs.foreach(_.setProperty(KRaftConfigs.METADATA_LOG_DIR_CONFIG, TestUtils.tempDir().getAbsolutePath))
diff --git a/core/src/test/scala/kafka/utils/TestInfoUtils.scala b/core/src/test/scala/kafka/utils/TestInfoUtils.scala
index cd22727839e..c6b05d9254c 100644
--- a/core/src/test/scala/kafka/utils/TestInfoUtils.scala
+++ b/core/src/test/scala/kafka/utils/TestInfoUtils.scala
@@ -51,6 +51,10 @@ object TestInfoUtils {
     testInfo.getDisplayName.contains("kraft+kip932")
   }
 
+  def isStreamsGroupTest(testInfo: TestInfo): Boolean = {
+    testInfo.getDisplayName.contains("kraft+kip1071")
+  }
+
   def maybeGroupProtocolSpecified(testInfo: TestInfo): Option[GroupProtocol] = {
     if (testInfo.getDisplayName.contains("groupProtocol=classic"))
       Some(GroupProtocol.CLASSIC)
diff --git a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
index 1241287965f..8d62dadd642 100644
--- a/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
+++ b/core/src/test/scala/unit/kafka/server/KafkaApisTest.scala
@@ -11251,7 +11251,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     val streamsGroupInitializeResponse = new StreamsGroupInitializeResponseData()
 
@@ -11277,7 +11277,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
     val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
@@ -11300,7 +11300,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     val response = verifyNoThrottling[StreamsGroupInitializeResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
@@ -11324,7 +11324,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     val streamsGroupHeartbeatResponse = new StreamsGroupHeartbeatResponseData()
       .setMemberId("member")
@@ -11351,7 +11351,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
@@ -11374,7 +11374,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     val response = verifyNoThrottling[StreamsGroupHeartbeatResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.errorCode)
@@ -11521,7 +11521,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     future.complete(List(
       new StreamsGroupDescribeResponseData.DescribedGroup().setGroupId(groupIds.get(0)),
@@ -11564,7 +11564,7 @@ class KafkaApisTest extends Logging {
     val expectedResponse = new StreamsGroupDescribeResponseData()
     expectedResponse.groups.add(expectedDescribedGroup)
     kafkaApis = createKafkaApis()
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
     val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
 
     assertEquals(expectedResponse, response.data)
@@ -11593,7 +11593,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
     assertEquals(Errors.GROUP_AUTHORIZATION_FAILED.code, response.data.groups.get(0).errorCode)
@@ -11616,7 +11616,7 @@ class KafkaApisTest extends Logging {
       overrideProperties = Map(GroupCoordinatorConfig.GROUP_COORDINATOR_REBALANCE_PROTOCOLS_CONFIG -> "classic,streams"),
       raftSupport = true
     )
-    kafkaApis.handle(requestChannelRequest, RequestLocal.NoCaching)
+    kafkaApis.handle(requestChannelRequest, RequestLocal.noCaching)
 
     future.completeExceptionally(Errors.FENCED_MEMBER_EPOCH.exception)
     val response = verifyNoThrottling[StreamsGroupDescribeResponse](requestChannelRequest)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
index c6631945add..007e991ad16 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorService.java
@@ -375,7 +375,8 @@ public class GroupCoordinatorService implements GroupCoordinator {
             exception,
             (error, message) -> new StreamsGroupInitializeResponseData()
                 .setErrorCode(error.code())
-                .setErrorMessage(message)
+                .setErrorMessage(message),
+            log
         ));
     }
 
@@ -404,7 +405,8 @@ public class GroupCoordinatorService implements GroupCoordinator {
             exception,
             (error, message) -> new StreamsGroupHeartbeatResponseData()
                 .setErrorCode(error.code())
-                .setErrorMessage(message)
+                .setErrorMessage(message),
+            log
         ));
     }
 
@@ -767,7 +769,8 @@ public class GroupCoordinatorService implements GroupCoordinator {
                     "streams-group-describe",
                     groupList,
                     exception,
-                    (error, __) -> StreamsGroupDescribeRequest.getErrorDescribedGroupList(groupList, error)
+                    (error, __) -> StreamsGroupDescribeRequest.getErrorDescribedGroupList(groupList, error),
+                    log
                 ));
 
             futures.add(future);
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
index bf595347273..1a543490b53 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/metrics/GroupCoordinatorMetrics.java
@@ -116,6 +116,7 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
         this(KafkaYammerMetrics.defaultRegistry(), new Metrics());
     }
 
+    @SuppressWarnings("MethodLength")
     public GroupCoordinatorMetrics(MetricsRegistry registry, Metrics metrics) {
         this.registry = Objects.requireNonNull(registry);
         this.metrics = Objects.requireNonNull(metrics);
@@ -198,6 +199,7 @@ public class GroupCoordinatorMetrics extends CoordinatorMetrics implements AutoC
             "The number of share groups in dead state.",
             SHARE_GROUP_PROTOCOL_TAG, Group.GroupType.SHARE.toString(),
             SHARE_GROUP_COUNT_STATE_TAG, ShareGroup.ShareGroupState.DEAD.toString()
+        );
 
         streamsGroupCountMetricName = metrics.metricName(
             GROUP_COUNT_METRIC_NAME,
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 679e987f407..48a31fdd4c7 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -17,7 +17,7 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataKey;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 11f0cc198fd..f9891e62953 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -25,7 +25,7 @@ import org.apache.kafka.common.errors.UnknownMemberIdException;
 import org.apache.kafka.common.message.ListGroupsResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.protocol.Errors;
-import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index d4cb0b85275..fcb2e99ff55 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -16,7 +16,7 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.taskassignor.AssignmentMemberSpec;
 import org.apache.kafka.coordinator.group.taskassignor.GroupAssignment;
 import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index b9298dab3f3..0b291bd098e 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -17,7 +17,7 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
-import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
index 8e39ae949da..e05365dbac8 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
@@ -20,7 +20,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import org.apache.kafka.coordinator.group.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 
 public class StreamsGroupBuilder {
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index dfc263c8710..1679336815f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -39,7 +39,7 @@ import java.util.Set;
 import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.Assertions.assertUnorderedListEquals;
-import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
+import static org.apache.kafka.coordinator.group.GroupCoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index 7de099c4ede..78c23184f4f 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -20,8 +20,8 @@ import java.util.Locale;
 
 import kafka.api.IntegrationTestHarness;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
-import org.apache.kafka.clients.consumer.GroupProtocol;
 import org.apache.kafka.common.utils.Exit;
+import org.apache.kafka.streams.GroupProtocol;
 import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.StreamsConfig.InternalConfig;
 import org.apache.kafka.streams.tests.SmokeTestClient;
@@ -86,7 +86,7 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
     }
 
     @Override
-    public boolean isNewGroupCoordinatorEnabled() {
+    public boolean isStreamsGroupTest() {
         return true;
     }
 
@@ -110,7 +110,7 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
     public void shouldWorkWithRebalance(
         final boolean stateUpdaterEnabled,
         final boolean processingThreadsEnabled,
-        final boolean consumerProtocolEnabled
+        final boolean streamsProtocolEnabled
     ) throws InterruptedException {
         Exit.setExitProcedure((statusCode, message) -> {
             throw new AssertionError("Test called exit(). code:" + statusCode + " message:" + message);
@@ -166,8 +166,8 @@ public class SmokeTestDriverIntegrationTest extends IntegrationTestHarness {
         props.put(InternalConfig.PROCESSING_THREADS_ENABLED, processingThreadsEnabled);
         // decrease the session timeout so that we can trigger the rebalance soon after old client left closed
         props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 10000);
-        if (consumerProtocolEnabled) {
-            props.put(StreamsConfig.consumerPrefix(ConsumerConfig.GROUP_PROTOCOL_CONFIG), GroupProtocol.CONSUMER.name().toLowerCase(Locale.getDefault()));
+        if (streamsProtocolEnabled) {
+            props.put(StreamsConfig.GROUP_PROTOCOL_CONFIG, GroupProtocol.STREAMS.name().toLowerCase(Locale.getDefault()));
         }
 
         // cycle out Streams instances as long as the test is running.
diff --git a/streams/src/main/java/org/apache/kafka/streams/GroupProtocol.java b/streams/src/main/java/org/apache/kafka/streams/GroupProtocol.java
new file mode 100644
index 00000000000..146a5e6e9de
--- /dev/null
+++ b/streams/src/main/java/org/apache/kafka/streams/GroupProtocol.java
@@ -0,0 +1,43 @@
+/*
+ * 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 org.apache.kafka.streams;
+
+import java.util.Locale;
+
+public enum GroupProtocol {
+    /** Classic group protocol.  */
+    CLASSIC("CLASSIC"),
+
+    /** Streams group protocol */
+    STREAMS("STREAMS");
+
+    /**
+     * String representation of the group protocol.
+     */
+    public final String name;
+
+    GroupProtocol(final String name) {
+        this.name = name;
+    }
+
+    /**
+     * Case-insensitive group protocol lookup by string name.
+     */
+    public static GroupProtocol of(final String name) {
+        return GroupProtocol.valueOf(name.toUpperCase(Locale.ROOT));
+    }
+}
diff --git a/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java b/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
index 36acc2b2049..6e171e022b5 100644
--- a/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
+++ b/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
@@ -16,6 +16,7 @@
  */
 package org.apache.kafka.streams;
 
+import java.util.Locale;
 import org.apache.kafka.clients.CommonClientConfigs;
 import org.apache.kafka.clients.MetadataRecoveryStrategy;
 import org.apache.kafka.clients.admin.Admin;
@@ -588,6 +589,16 @@ public class StreamsConfig extends AbstractConfig {
     public static final String ENABLE_METRICS_PUSH_DOC = "Whether to enable pushing of internal client metrics for (main, restore, and global) consumers, producers, and admin clients." +
         " The cluster must have a client metrics subscription which corresponds to a client.";
 
+    /**
+     * <code>group.protocol</code>
+     */
+    public static final String GROUP_PROTOCOL_CONFIG = "group.protocol";
+    public static final String DEFAULT_GROUP_PROTOCOL = GroupProtocol.CLASSIC.name().toLowerCase(
+        Locale.ROOT);
+    public static final String GROUP_PROTOCOL_DOC = "The group protocol streams should use. We currently " +
+        "support \"classic\" or \"streams\". If \"streams\" is specified, then the streams rebalance protocol will be " +
+        "used. Otherwise, the classic group protocol will be used.";
+
     /** {@code log.summary.interval.ms} */
     public static final String LOG_SUMMARY_INTERVAL_MS_CONFIG = "log.summary.interval.ms";
     private static final String LOG_SUMMARY_INTERVAL_MS_DOC = "The output interval in milliseconds for logging summary information.\n" +
@@ -1026,6 +1037,12 @@ public class StreamsConfig extends AbstractConfig {
                         TOPOLOGY_OPTIMIZATION_CONFIGS::toString),
                     Importance.MEDIUM,
                     TOPOLOGY_OPTIMIZATION_DOC)
+            .define(GROUP_PROTOCOL_CONFIG,
+                    Type.STRING,
+                    DEFAULT_GROUP_PROTOCOL,
+                    ConfigDef.CaseInsensitiveValidString.in(Utils.enumOptions(GroupProtocol.class)),
+                    Importance.MEDIUM,
+                    GROUP_PROTOCOL_DOC)
 
             // LOW
 
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index b87ba61b51d..f26f9d55089 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -22,7 +22,6 @@ import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
-import org.apache.kafka.clients.consumer.GroupProtocol;
 import org.apache.kafka.clients.consumer.InvalidOffsetException;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.clients.consumer.OffsetResetStrategy;
@@ -45,6 +44,7 @@ import org.apache.kafka.common.serialization.ByteArrayDeserializer;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
 import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.streams.GroupProtocol;
 import org.apache.kafka.streams.KafkaClientSupplier;
 import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.StreamsConfig.InternalConfig;
@@ -493,8 +493,7 @@ public class StreamThread extends Thread implements ProcessingThread {
 
         final Consumer<byte[], byte[]> mainConsumer;
         final StreamsAssignmentInterface streamsAssignmentInterface;
-        if (consumerConfigs.containsKey(ConsumerConfig.GROUP_PROTOCOL_CONFIG) &&
-            consumerConfigs.get(ConsumerConfig.GROUP_PROTOCOL_CONFIG).toString().equalsIgnoreCase(GroupProtocol.CONSUMER.name)) {
+        if (config.getString(StreamsConfig.GROUP_PROTOCOL_CONFIG).equalsIgnoreCase(GroupProtocol.STREAMS.name)) {
             if (topologyMetadata.hasNamedTopologies()) {
                 throw new IllegalStateException("Named topologies and the CONSUMER protocol cannot be used at the same time.");
             }


(kafka) 05/42: Implement StreamsInitialize request manager

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit a19bc7d97b77edaacbfafe56b69256214b5c648b
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Mon May 27 10:51:54 2024 +0200

    Implement StreamsInitialize request manager
    
    See https://github.com/lucasbru/kafka/pull/11
---
 .../consumer/internals/RequestManagers.java        |  16 +++
 .../internals/StreamsInitializeRequestManager.java |  98 ++++++++++++++-
 .../StreamsInitializeRequestManagerTest.java       | 131 +++++++++++++++++++++
 3 files changed, 241 insertions(+), 4 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index 5045743848d..65dec12140b 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -251,6 +251,22 @@ public class RequestManagers implements Closeable {
                     membershipManager.registerStateListener(commitRequestManager);
                     membershipManager.registerStateListener(applicationThreadMemberStateListener);
 
+                    if (streamsInstanceMetadata.isPresent()) {
+                        streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+                            logContext,
+                            groupRebalanceConfig.groupId,
+                            streamsInstanceMetadata.get(),
+                            coordinator);
+                        streamsPrepareAssignmentRequestManager = new StreamsPrepareAssignmentRequestManager(
+                            streamsInstanceMetadata.get());
+                        streamsInstallAssignmentRequestManager = new StreamsInstallAssignmentRequestManager(
+                            streamsInstanceMetadata.get());
+                        streamsHeartbeatRequestManager = new StreamsHeartbeatRequestManager(
+                            streamsInitializeRequestManager,
+                            streamsPrepareAssignmentRequestManager,
+                            streamsInstanceMetadata.get());
+                    } else {
+                        heartbeatRequestManager = new HeartbeatRequestManager(
                             logContext,
                             time,
                             config,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
index 73d2955ef2f..34f9fee96f7 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManager.java
@@ -16,23 +16,113 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
+import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.requests.StreamsInitializeRequest;
+import org.apache.kafka.common.utils.LogContext;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 
 public class StreamsInitializeRequestManager implements RequestManager {
 
+    private final Logger logger;
+    private final String groupId;
     private final StreamsAssignmentInterface streamsAssignmentInterface;
+    private final CoordinatorRequestManager coordinatorRequestManager;
+
+    private Optional<NetworkClientDelegate.UnsentRequest> unsentRequest = Optional.empty();
 
-    StreamsInitializeRequestManager(final StreamsAssignmentInterface streamsAssignmentInterface) {
+
+    StreamsInitializeRequestManager(final LogContext logContext,
+                                    final String groupId,
+                                    final StreamsAssignmentInterface streamsAssignmentInterface,
+                                    final CoordinatorRequestManager coordinatorRequestManager) {
+        this.logger = logContext.logger(getClass());
+        this.groupId = groupId;
         this.streamsAssignmentInterface = streamsAssignmentInterface;
+        this.coordinatorRequestManager = coordinatorRequestManager;
     }
 
     @Override
     public PollResult poll(final long currentTimeMs) {
-        // TODO: Return an initalize request
-        return PollResult.EMPTY;
+        return unsentRequest.map(PollResult::new).orElse(PollResult.EMPTY);
     }
 
     public void initialize() {
-        // TODO: Create a `StreamsInitializeRequest`
+        final NetworkClientDelegate.UnsentRequest unsentRequest = makeRequest();
+
+        unsentRequest.whenComplete(this::onResponse);
+
+        this.unsentRequest = Optional.of(unsentRequest);
+    }
+
+    private NetworkClientDelegate.UnsentRequest makeRequest() {
+        final StreamsInitializeRequestData streamsInitializeRequestData = new StreamsInitializeRequestData();
+        streamsInitializeRequestData.setGroupId(groupId);
+        final List<StreamsInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
+        streamsInitializeRequestData.setTopology(topology);
+        final StreamsInitializeRequest.Builder streamsInitializeRequestBuilder = new StreamsInitializeRequest.Builder(
+            streamsInitializeRequestData
+        );
+        return new NetworkClientDelegate.UnsentRequest(
+            streamsInitializeRequestBuilder,
+            coordinatorRequestManager.coordinator()
+        );
+    }
+
+    private List<StreamsInitializeRequestData.Subtopology> getTopologyFromStreams() {
+        final Map<String, StreamsAssignmentInterface.SubTopology> subTopologyMap = streamsAssignmentInterface.subtopologyMap();
+        final List<StreamsInitializeRequestData.Subtopology> topology = new ArrayList<>(subTopologyMap.size());
+        for (final Map.Entry<String, StreamsAssignmentInterface.SubTopology> subtopology : subTopologyMap.entrySet()) {
+            topology.add(getSubtopologyFromStreams(subtopology.getKey(), subtopology.getValue()));
+        }
+        return topology;
+    }
+
+    private static StreamsInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
+                                                                                      final StreamsAssignmentInterface.SubTopology subtopology) {
+        final StreamsInitializeRequestData.Subtopology subtopologyData = new StreamsInitializeRequestData.Subtopology();
+        subtopologyData.setSubtopology(subtopologyName);
+        subtopologyData.setSourceTopics(new ArrayList<>(subtopology.sourceTopics));
+        subtopologyData.setSinkTopics(new ArrayList<>(subtopology.sinkTopics));
+        subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
+        subtopologyData.setStateChangelogTopics(getChangelogTopicsInfoFromStreams(subtopology));
+        return subtopologyData;
+    }
+
+    private static List<StreamsInitializeRequestData.TopicInfo> getRepartitionTopicsInfoFromStreams(final StreamsAssignmentInterface.SubTopology subtopologyDataFromStreams) {
+        final List<StreamsInitializeRequestData.TopicInfo> repartitionTopicsInfo = new ArrayList<>();
+        for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> repartitionTopic : subtopologyDataFromStreams.repartitionSourceTopics.entrySet()) {
+            final StreamsInitializeRequestData.TopicInfo repartitionTopicInfo = new StreamsInitializeRequestData.TopicInfo();
+            repartitionTopicInfo.setName(repartitionTopic.getKey());
+            repartitionTopic.getValue().numPartitions.ifPresent(repartitionTopicInfo::setPartitions);
+            repartitionTopicsInfo.add(repartitionTopicInfo);
+        }
+        return repartitionTopicsInfo;
+    }
+
+    private static List<StreamsInitializeRequestData.TopicInfo> getChangelogTopicsInfoFromStreams(final StreamsAssignmentInterface.SubTopology subtopologyDataFromStreams) {
+        final List<StreamsInitializeRequestData.TopicInfo> changelogTopicsInfo = new ArrayList<>();
+        for (final Map.Entry<String, StreamsAssignmentInterface.TopicInfo> changelogTopic : subtopologyDataFromStreams.stateChangelogTopics.entrySet()) {
+            final StreamsInitializeRequestData.TopicInfo changelogTopicInfo = new StreamsInitializeRequestData.TopicInfo();
+            changelogTopicInfo.setName(changelogTopic.getKey());
+            changelogTopicsInfo.add(changelogTopicInfo);
+        }
+        return changelogTopicsInfo;
+    }
+    
+    private void onResponse(final ClientResponse response, final Throwable exception) {
+        if (exception != null) {
+            // todo: handle error
+            logger.error("Error during Streams initialization: ", exception);
+        } else {
+            // todo: handle success
+            logger.info("Streams initialization successful", exception);
+        }
     }
 }
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
new file mode 100644
index 00000000000..bb734a7b1f5
--- /dev/null
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsInitializeRequestManagerTest.java
@@ -0,0 +1,131 @@
+/*
+ * 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 org.apache.kafka.clients.consumer.internals;
+
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.message.StreamsInitializeRequestData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.requests.StreamsInitializeRequest;
+import org.apache.kafka.common.utils.LogContext;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class StreamsInitializeRequestManagerTest {
+
+    final private String groupId = "groupId";
+    final private LogContext logContext = new LogContext("test");
+
+    @Test
+    public void shouldPollEmptyResult() {
+        final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
+        final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
+        final StreamsInitializeRequestManager streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+            logContext,
+            groupId,
+            streamsAssignmentInterface,
+            coordinatorRequestManager
+        );
+
+        final NetworkClientDelegate.PollResult pollResult = streamsInitializeRequestManager.poll(0);
+
+        assertEquals(NetworkClientDelegate.PollResult.EMPTY, pollResult);
+    }
+
+    @Test
+    public void shouldPollStreamsInitializeRequest() {
+        final Node node = mock(Node.class);
+        final CoordinatorRequestManager coordinatorRequestManager = mock(CoordinatorRequestManager.class);
+        when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(node));
+        final StreamsAssignmentInterface streamsAssignmentInterface = mock(StreamsAssignmentInterface.class);
+        final Set<String> sourceTopics = mkSet("sourceTopic1", "sourceTopic2");
+        final Set<String> sinkTopics = mkSet("sinkTopic1", "sinkTopic2", "sinkTopic3");
+        final Map<String, StreamsAssignmentInterface.TopicInfo> repartitionTopics = mkMap(
+            mkEntry("repartitionTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.of(2), Collections.emptyMap())),
+            mkEntry("repartitionTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.of(3), Collections.emptyMap()))
+        );
+        final Map<String, StreamsAssignmentInterface.TopicInfo> changelogTopics = mkMap(
+            mkEntry("changelogTopic1", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap())),
+            mkEntry("changelogTopic2", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap())),
+            mkEntry("changelogTopic3", new StreamsAssignmentInterface.TopicInfo(Optional.empty(), Collections.emptyMap()))
+        );
+        final StreamsAssignmentInterface.SubTopology subtopology1 = new StreamsAssignmentInterface.SubTopology(
+            sinkTopics,
+            sourceTopics,
+            repartitionTopics,
+            changelogTopics
+        );
+        final String subtopologyName1 = "subtopology1";
+        when(streamsAssignmentInterface.subtopologyMap()).thenReturn(
+            mkMap(mkEntry(subtopologyName1, subtopology1))
+        );
+        final StreamsInitializeRequestManager streamsInitializeRequestManager = new StreamsInitializeRequestManager(
+            logContext,
+            groupId,
+            streamsAssignmentInterface,
+            coordinatorRequestManager
+        );
+
+        streamsInitializeRequestManager.initialize();
+        final NetworkClientDelegate.PollResult pollResult = streamsInitializeRequestManager.poll(0);
+
+        assertEquals(1, pollResult.unsentRequests.size());
+        final NetworkClientDelegate.UnsentRequest unsentRequest = pollResult.unsentRequests.get(0);
+        assertTrue(unsentRequest.node().isPresent());
+        assertEquals(node, unsentRequest.node().get());
+        assertEquals(ApiKeys.STREAMS_INITIALIZE, unsentRequest.requestBuilder().apiKey());
+        final StreamsInitializeRequest.Builder streamsInitializeRequestBuilder = (StreamsInitializeRequest.Builder) unsentRequest.requestBuilder();
+        final StreamsInitializeRequest streamsInitializeRequest = streamsInitializeRequestBuilder.build();
+        final StreamsInitializeRequestData streamsInitializeRequestData = streamsInitializeRequest.data();
+        assertEquals(ApiKeys.STREAMS_INITIALIZE.id, streamsInitializeRequestData.apiKey());
+        assertEquals(groupId, streamsInitializeRequestData.groupId());
+        assertNotNull(streamsInitializeRequestData.topology());
+        final List<StreamsInitializeRequestData.Subtopology> subtopologies = streamsInitializeRequestData.topology();
+        assertEquals(1, subtopologies.size());
+        final StreamsInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
+        assertEquals(subtopologyName1, subtopology.subtopology());
+        assertEquals(new ArrayList<>(sourceTopics), subtopology.sourceTopics());
+        assertEquals(new ArrayList<>(sinkTopics), subtopology.sinkTopics());
+        assertEquals(repartitionTopics.size(), subtopology.repartitionSourceTopics().size());
+        subtopology.repartitionSourceTopics().forEach(topicInfo -> {
+            final StreamsAssignmentInterface.TopicInfo repartitionTopic = repartitionTopics.get(topicInfo.name());
+            assertEquals(repartitionTopic.numPartitions.get(), topicInfo.partitions());
+        });
+        assertEquals(changelogTopics.size(), subtopology.stateChangelogTopics().size());
+        subtopology.stateChangelogTopics().forEach(topicInfo -> {
+            assertTrue(changelogTopics.containsKey(topicInfo.name()));
+            assertEquals(0, topicInfo.partitions());
+        });
+    }
+}
\ No newline at end of file


(kafka) 25/42: Improve the Streams group initialization handler

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 7a9105b93fc6bfc829e52dfd24eb5ea1302c99b6
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Mon Sep 2 11:18:19 2024 +0200

    Improve the Streams group initialization handler
    
    This commit:
    - schedules a timeout for the initialization call
    - requests the initialization only from the one member
    - intializations of unknown topologies or already initialized topologies
    are silently dropped
---
 .../internals/StreamsAssignmentInterface.java      |   3 +
 .../StreamsGroupHeartbeatRequestManager.java       |   4 +
 .../StreamsGroupInitializeRequestManager.java      |   3 +-
 .../message/StreamsGroupInitializeRequest.json     |   4 +-
 .../StreamsGroupInitializeRequestManagerTest.java  |   2 +-
 .../common/runtime/CoordinatorRuntime.java         |   5 +
 .../common/runtime/CoordinatorTimer.java           |   9 +
 .../common/runtime/MockCoordinatorTimer.java       |   3 +-
 .../coordinator/group/GroupMetadataManager.java    | 141 ++++-
 .../streams/CoordinatorStreamsRecordHelpers.java   |  14 +-
 .../coordinator/group/streams/StreamsGroup.java    |  54 +-
 .../coordinator/group/streams/StreamsTopology.java |  38 +-
 .../group/streams/TargetAssignmentBuilder.java     |   6 +-
 .../group/GroupCoordinatorShardTest.java           |  10 +-
 .../group/GroupMetadataManagerTest.java            | 590 ++++++++++++++++-----
 .../group/GroupMetadataManagerTestContext.java     |   9 +
 .../CoordinatorStreamsRecordHelpersTest.java       |   2 +-
 .../group/streams/StreamsGroupBuilder.java         |   6 +-
 .../group/streams/StreamsGroupTest.java            |  31 +-
 .../group/streams/TargetAssignmentBuilderTest.java |  46 +-
 20 files changed, 743 insertions(+), 237 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
index 5793ffec2aa..567fcb5f776 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsAssignmentInterface.java
@@ -73,6 +73,9 @@ public class StreamsAssignmentInterface {
         return assignmentConfiguration;
     }
 
+    // ToDo: As long as we do not compute the topology ID, let's use a constant one
+    public final String topologyId = "topology-id";
+
     // TODO: This needs to be used somewhere
     public Map<TaskId, Long> taskLags() {
         return taskLags;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index ba0a289f187..e93b0e51c10 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -516,6 +516,7 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             final StreamsAssignmentInterface streamsInterface,
             final ConsumerMembershipManager membershipManager,
             final int rebalanceTimeoutMs) {
+
             this.membershipManager = membershipManager;
             this.rebalanceTimeoutMs = rebalanceTimeoutMs;
             this.sentFields = new StreamsGroupHeartbeatRequestManager.HeartbeatState.SentFields();
@@ -532,6 +533,9 @@ public class StreamsGroupHeartbeatRequestManager implements RequestManager {
             // GroupId - always sent
             data.setGroupId(membershipManager.groupId());
 
+            // TopologyId - always sent
+            data.setTopologyId(streamsInterface.topologyId);
+
             // MemberId - always sent, empty until it has been received from the coordinator
             data.setMemberId(membershipManager.memberId());
 
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
index e7f763bd969..0a6a67594c1 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
@@ -68,6 +68,7 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
     private NetworkClientDelegate.UnsentRequest makeRequest() {
         final StreamsGroupInitializeRequestData streamsGroupInitializeRequestData = new StreamsGroupInitializeRequestData();
         streamsGroupInitializeRequestData.setGroupId(groupId);
+        streamsGroupInitializeRequestData.setTopologyId(streamsAssignmentInterface.topologyId);
         final List<StreamsGroupInitializeRequestData.Subtopology> topology = getTopologyFromStreams();
         streamsGroupInitializeRequestData.setTopology(topology);
         final StreamsGroupInitializeRequest.Builder streamsGroupInitializeRequestBuilder = new StreamsGroupInitializeRequest.Builder(
@@ -91,7 +92,7 @@ public class StreamsGroupInitializeRequestManager implements RequestManager {
     private static StreamsGroupInitializeRequestData.Subtopology getSubtopologyFromStreams(final String subtopologyName,
                                                                                            final StreamsAssignmentInterface.Subtopology subtopology) {
         final StreamsGroupInitializeRequestData.Subtopology subtopologyData = new StreamsGroupInitializeRequestData.Subtopology();
-        subtopologyData.setSubtopology(subtopologyName);
+        subtopologyData.setSubtopologyId(subtopologyName);
         subtopologyData.setSourceTopics(new ArrayList<>(subtopology.sourceTopics));
         subtopologyData.setRepartitionSinkTopics(new ArrayList<>(subtopology.sinkTopics));
         subtopologyData.setRepartitionSourceTopics(getRepartitionTopicsInfoFromStreams(subtopology));
diff --git a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
index 602b557e3e9..3223d1e8d9e 100644
--- a/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
+++ b/clients/src/main/resources/common/message/StreamsGroupInitializeRequest.json
@@ -23,10 +23,12 @@
   "fields": [
     { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
       "about": "The group identifier." },
+    { "name": "TopologyId", "type": "string", "versions": "0+",
+      "about": "The ID of the topology." },
     { "name":  "Topology", "type": "[]Subtopology", "versions": "0+",
       "about": "The sub-topologies of the streams application.",
       "fields": [
-        { "name": "Subtopology", "type": "string", "versions": "0+",
+        { "name": "SubtopologyId", "type": "string", "versions": "0+",
           "about": "String to uniquely identify the sub-topology. Deterministically generated from the topology" },
         { "name": "SourceTopics", "type": "[]string", "versions": "0+",
           "about": "The topics the topology reads from." },
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index 48108204474..ebba584b0db 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -114,7 +114,7 @@ class StreamsGroupInitializeRequestManagerTest {
         final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = streamsGroupInitializeRequestData.topology();
         assertEquals(1, subtopologies.size());
         final StreamsGroupInitializeRequestData.Subtopology subtopology = subtopologies.get(0);
-        assertEquals(subtopologyName1, subtopology.subtopology());
+        assertEquals(subtopologyName1, subtopology.subtopologyId());
         assertEquals(new ArrayList<>(sourceTopics), subtopology.sourceTopics());
         assertEquals(new ArrayList<>(sinkTopics), subtopology.repartitionSinkTopics());
         assertEquals(repartitionTopics.size(), subtopology.repartitionSourceTopics().size());
diff --git a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java
index bef30a113df..d47bd967368 100644
--- a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java
+++ b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorRuntime.java
@@ -453,6 +453,11 @@ public class CoordinatorRuntime<S extends CoordinatorShard<U>, U> implements Aut
         public int size() {
             return tasks.size();
         }
+
+        @Override
+        public boolean isScheduled(String key) {
+            return tasks.containsKey(key);
+        }
     }
 
     /**
diff --git a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorTimer.java b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorTimer.java
index d10e38a7d82..c6e8456bf2b 100644
--- a/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorTimer.java
+++ b/coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorTimer.java
@@ -84,4 +84,13 @@ public interface CoordinatorTimer<T, U> {
      * @param key The key.
      */
     void cancel(String key);
+
+    /**
+     * Verifies whether an operation corresponding to a given key is scheduled.
+     *
+     * @param key The key.
+     *
+     * @return {@code true} if the operation is scheduled, {@code false} otherwise.
+     */
+    boolean isScheduled(String key);
 }
diff --git a/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/MockCoordinatorTimer.java b/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/MockCoordinatorTimer.java
index 5c55f59d608..6a17254abe9 100644
--- a/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/MockCoordinatorTimer.java
+++ b/coordinator-common/src/test/java/org/apache/kafka/coordinator/common/runtime/MockCoordinatorTimer.java
@@ -155,7 +155,8 @@ public class MockCoordinatorTimer<T, U> implements CoordinatorTimer<T, U> {
     /**
      * @return True if a timeout with the key exists; false otherwise.
      */
-    public boolean contains(String key) {
+    @Override
+    public boolean isScheduled(String key) {
         return timeoutMap.containsKey(key);
     }
 
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 40c9e652a1b..bc551a1d89f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -216,14 +216,14 @@ import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.CONSUMER_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics.STREAMS_GROUP_REBALANCES_SENSOR_NAME;
 import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMember.hasAssignedPartitionsChanged;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedActiveTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedStandbyTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedWarmupTasksChanged;
@@ -1158,7 +1158,7 @@ public class GroupMetadataManager {
         }
 
         if (group == null) {
-            log.info("Reading persisted streams group {}", groupId);
+            log.info("Creating persisted streams group {}", groupId);
             StreamsGroup streamsGroup = new StreamsGroup(snapshotRegistry, groupId, metrics);
             groups.put(groupId, streamsGroup);
             metrics.onStreamsGroupStateTransition(null, streamsGroup.state());
@@ -2402,7 +2402,10 @@ public class GroupMetadataManager {
 
         scheduleStreamsGroupSessionTimeout(groupId, memberId);
 
-        if (group.topology() == null) {
+        boolean requestTopologyInitialization = false;
+        if (group.topology() == null && !isTopologyInitializationScheduled(groupId, topologyId)) {
+            requestTopologyInitialization = true;
+            scheduleStreamsGroupTopologyInitializationTimeout(groupId, topologyId, memberId, rebalanceTimeoutMs);
             log.info("Asking member {} at {} to initialize the topology", memberId, clientHost);
         }
 
@@ -2410,7 +2413,7 @@ public class GroupMetadataManager {
         StreamsGroupHeartbeatResponseData response = new StreamsGroupHeartbeatResponseData()
             .setMemberId(updatedMember.memberId())
             .setMemberEpoch(updatedMember.memberEpoch())
-            .setShouldInitializeTopology(group.topology() == null)
+            .setShouldInitializeTopology(requestTopologyInitialization)
             .setHeartbeatIntervalMs(streamsGroupHeartbeatIntervalMs);
 
         // The assignment is only provided in the following cases:
@@ -2654,19 +2657,28 @@ public class GroupMetadataManager {
      * Handles the initialization of the topology information on the broker side, that will be reused by all members of the group.
      *
      * @param groupId       The group id from the request.
-     * @param subtopologies The list of subtopologies
+     * @param topologyId    The topology ID.
+     * @param subtopologies The list of subtopologies.
      * @return A Result containing the StreamsGroupInitialize response and a list of records to update the state machine.
      */
     private CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> streamsGroupInitialize(String groupId,
+                                                                                                       String topologyId,
                                                                                                             List<StreamsGroupInitializeRequestData.Subtopology> subtopologies)
         throws ApiException {
+
         final List<CoordinatorRecord> records = new ArrayList<>();
 
-        log.info("Initializing topology for group {} to {}", groupId, subtopologies);
+        log.info("Initializing topology {} for group {} to {}", topologyId, groupId, subtopologies);
 
         final StreamsGroup group = getOrMaybeCreateStreamsGroup(groupId, false, records);
         throwIfNull(group, "group does not exist");
 
+        if (!isTopologyInitializationScheduled(groupId, topologyId)) {
+            log.warn("No topology to initialize for group ID {} and topology ID {} found.", groupId, topologyId);
+            StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
+            return new CoordinatorResult<>(records, response);
+        }
+
         // TODO: For the POC, only check if internal topics exist
         Set<String> missingTopics = new HashSet<>();
         for (StreamsGroupInitializeRequestData.Subtopology subtopology : subtopologies) {
@@ -2681,6 +2693,9 @@ public class GroupMetadataManager {
                 }
             }
         }
+
+        cancelStreamsGroupTopologyInitializationTimeout(groupId, topologyId);
+
         if (!missingTopics.isEmpty()) {
             StreamsGroupInitializeResponseData response =
                 new StreamsGroupInitializeResponseData()
@@ -2691,6 +2706,10 @@ public class GroupMetadataManager {
         } else {
             records.add(newStreamsGroupTopologyRecord(groupId, subtopologies));
 
+            final StreamsTopology topology = new StreamsTopology(topologyId, subtopologies);
+
+            computeFirstTargetAssignmentAfterTopologyInitialization(group, records, topology);
+
             StreamsGroupInitializeResponseData response = new StreamsGroupInitializeResponseData();
 
             return new CoordinatorResult<>(records, response);
@@ -2698,6 +2717,56 @@ public class GroupMetadataManager {
 
     }
 
+    // ToDo: verify how much code we can share with Streams heartbeat handler
+    private void computeFirstTargetAssignmentAfterTopologyInitialization(StreamsGroup group,
+                                                                         List<CoordinatorRecord> records,
+                                                                         StreamsTopology topology) {
+        String groupId = group.groupId();
+        final long currentTimeMs = time.milliseconds();
+        int groupEpoch = group.groupEpoch();
+
+        Map<String, org.apache.kafka.coordinator.group.streams.TopicMetadata> subscriptionMetadata =
+            group.computeSubscriptionMetadata(
+                metadataImage.topics(),
+                metadataImage.cluster(),
+                topology
+            );
+        if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
+            log.info("[GroupId {}] Computed new partition metadata: {}.", groupId, subscriptionMetadata);
+            records.add(newStreamsGroupPartitionMetadataRecord(groupId, subscriptionMetadata));
+        }
+        groupEpoch += 1;
+        records.add(newStreamsGroupEpochRecord(groupId, groupEpoch));
+        log.info("[GroupId {}] Bumped streams group epoch to {}.", groupId, groupEpoch);
+        metrics.record(STREAMS_GROUP_REBALANCES_SENSOR_NAME);
+        group.setMetadataRefreshDeadline(currentTimeMs + streamsGroupMetadataRefreshIntervalMs, groupEpoch);
+
+        // TODO: Read the preferred server assignor from the group configuration
+        String preferredServerAssignor = defaultTaskAssignor.name();
+        try {
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder assignmentResultBuilder =
+                new org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder(group.groupId(), groupEpoch, taskAssignors.get(preferredServerAssignor))
+                    .withMembers(group.members())
+                    .withTopology(topology)
+                    .withStaticMembers(group.staticMembers())
+                    .withSubscriptionMetadata(subscriptionMetadata)
+                    .withTargetAssignment(group.targetAssignment());
+            org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
+                assignmentResultBuilder
+                    .build();
+
+            log.info("[GroupId {}] Computed a new target assignment for epoch {} with '{}' assignor: {}.",
+                group.groupId(), groupEpoch, preferredServerAssignor, assignmentResult.targetAssignment());
+
+            records.addAll(assignmentResult.records());
+        } catch (PartitionAssignorException ex) {
+            String msg = String.format("Failed to compute a new target assignment for epoch %d: %s",
+                groupEpoch, ex.getMessage());
+            log.error("[GroupId {}] {}.", group.groupId(), msg);
+            throw new UnknownServerException(msg, ex);
+        }
+    }
+
     /**
      * Handle a JoinGroupRequest to a ConsumerGroup.
      *
@@ -3692,7 +3761,7 @@ public class GroupMetadataManager {
             .build();
 
         if (!updatedMember.equals(member)) {
-            records.add(newStreamsCurrentAssignmentRecord(groupId, updatedMember));
+            records.add(newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember));
 
             log.info("[GroupId {}] Member {} new assignment state: epoch={}, previousEpoch={}, state={}, "
                     + "assignedActiveTasks={}, assignedStandbyTasks={}, assignedWarmupTasks={} and revokedPartitions={}.",
@@ -4062,7 +4131,7 @@ public class GroupMetadataManager {
             .build();
 
         return new CoordinatorResult<>(
-            Collections.singletonList(newStreamsCurrentAssignmentRecord(group.groupId(), leavingStaticMember)),
+            Collections.singletonList(newStreamsGroupCurrentAssignmentRecord(group.groupId(), leavingStaticMember)),
             new StreamsGroupHeartbeatResponseData()
                 .setMemberId(member.memberId())
                 .setMemberEpoch(LEAVE_GROUP_STATIC_MEMBER_EPOCH)
@@ -4224,8 +4293,8 @@ public class GroupMetadataManager {
      * @param memberId      The member id.
      */
     private void removeStreamsMember(List<CoordinatorRecord> records, String groupId, String memberId) {
-        records.add(newStreamsCurrentAssignmentTombstoneRecord(groupId, memberId));
-        records.add(newStreamsTargetAssignmentTombstoneRecord(groupId, memberId));
+        records.add(newStreamsGroupCurrentAssignmentTombstoneRecord(groupId, memberId));
+        records.add(newStreamsGroupTargetAssignmentTombstoneRecord(groupId, memberId));
         records.add(newStreamsGroupMemberTombstoneRecord(groupId, memberId));
     }
 
@@ -4459,6 +4528,49 @@ public class GroupMetadataManager {
     }
     
     /**
+     * Schedules (or reschedules) the topology initialisation timeout for the member.
+     *
+     * @param groupId                      The group id.
+     * @param topologyId                   The topology id.
+     * @param memberId                     The member id.
+     * @param topologyIntializationTimeout The topology initialization timeout.
+     */
+    private void scheduleStreamsGroupTopologyInitializationTimeout(
+        String groupId,
+        String topologyId,
+        String memberId,
+        int topologyIntializationTimeout
+    ) {
+        timer.schedule(
+            streamsTopologyInitializationTimeoutKey(groupId, topologyId),
+            topologyIntializationTimeout,
+            TimeUnit.MILLISECONDS,
+            true,
+            () -> streamsGroupFenceMemberOperation(groupId, memberId, "the timeout for the topology intialization expired.")
+        );
+    }
+
+    /**
+     * Verifies if the topology initialization timeout is scheduled.
+     *
+     * @param groupId       The group id.
+     * @param topologyId    The topology id.
+     * @return              {@code true} if the topology initialization timeout is scheduled, {@code false} otherwise.
+     */
+    private boolean isTopologyInitializationScheduled(String groupId, String topologyId) {
+        return timer.isScheduled(streamsTopologyInitializationTimeoutKey(groupId, topologyId));
+    }
+
+    /**
+     * Cancels the topology initialization timeout.
+     *
+     * @param groupId       The group id.
+     * @param topologyId     The topology id.
+     */
+    private void cancelStreamsGroupTopologyInitializationTimeout(String groupId, String topologyId) {
+        timer.cancel(streamsTopologyInitializationTimeoutKey(groupId, topologyId));
+    }
+
     /**
      * Cancels the session timeout of the member.
      *
@@ -4793,6 +4905,7 @@ public class GroupMetadataManager {
 
         return streamsGroupInitialize(
             request.groupId(),
+            request.topologyId(),
             request.topology()
         );
     }
@@ -5824,6 +5937,10 @@ public class GroupMetadataManager {
         return "rebalance-timeout-" + groupId + "-" + memberId;
     }
 
+    public static String streamsTopologyInitializationTimeoutKey(String groupId, String topologyId) {
+        return "topology-initialization-timeout-" + groupId + "-" + topologyId;
+    }
+
     /**
      * Replays GroupMetadataKey/Value to update the soft state of
      * the classic group.
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
index 2f48151e137..0e615db1c14 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpers.java
@@ -202,7 +202,7 @@ public class CoordinatorStreamsRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsTargetAssignmentRecord(
+    public static CoordinatorRecord newStreamsGroupTargetAssignmentRecord(
         String groupId,
         String memberId,
         Map<String, Set<Integer>> activeTasks,
@@ -258,7 +258,7 @@ public class CoordinatorStreamsRecordHelpers {
      * @param memberId The streams group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsTargetAssignmentTombstoneRecord(
+    public static CoordinatorRecord newStreamsGroupTargetAssignmentTombstoneRecord(
         String groupId,
         String memberId
     ) {
@@ -274,7 +274,7 @@ public class CoordinatorStreamsRecordHelpers {
     }
 
 
-    public static CoordinatorRecord newStreamsTargetAssignmentEpochRecord(
+    public static CoordinatorRecord newStreamsGroupTargetAssignmentEpochRecord(
         String groupId,
         int assignmentEpoch
     ) {
@@ -298,7 +298,7 @@ public class CoordinatorStreamsRecordHelpers {
      * @param groupId The streams group id.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsTargetAssignmentEpochTombstoneRecord(
+    public static CoordinatorRecord newStreamsGroupTargetAssignmentEpochTombstoneRecord(
         String groupId
     ) {
         return new CoordinatorRecord(
@@ -311,7 +311,7 @@ public class CoordinatorStreamsRecordHelpers {
         );
     }
 
-    public static CoordinatorRecord newStreamsCurrentAssignmentRecord(
+    public static CoordinatorRecord newStreamsGroupCurrentAssignmentRecord(
         String groupId,
         StreamsGroupMember member
     ) {
@@ -343,7 +343,7 @@ public class CoordinatorStreamsRecordHelpers {
      * @param memberId The streams group member id.
      * @return The record.
      */
-    public static CoordinatorRecord newStreamsCurrentAssignmentTombstoneRecord(
+    public static CoordinatorRecord newStreamsGroupCurrentAssignmentTombstoneRecord(
         String groupId,
         String memberId
     ) {
@@ -397,7 +397,7 @@ public class CoordinatorStreamsRecordHelpers {
                 return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
             }).collect(Collectors.toList());
 
-            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopology())
+            value.topology().add(new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopologyId())
                 .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
                 .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
         });
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
index 1d4c2ace5e1..4003b9a1125 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java
@@ -29,8 +29,6 @@ import org.apache.kafka.coordinator.group.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.Group;
 import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.image.ClusterImage;
 import org.apache.kafka.image.TopicImage;
@@ -49,11 +47,11 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
-import java.util.stream.Collectors;
 
 import static java.util.Collections.emptyMap;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.ASSIGNING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.EMPTY;
+import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.INITIALIZING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.RECONCILING;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroup.StreamsGroupState.STABLE;
 
@@ -64,6 +62,7 @@ public class StreamsGroup implements Group {
 
     public enum StreamsGroupState {
         EMPTY("Empty"),
+        INITIALIZING("Initializing"),
         ASSIGNING("Assigning"),
         RECONCILING("Reconciling"),
         STABLE("Stable"),
@@ -189,7 +188,7 @@ public class StreamsGroup implements Group {
     ) {
         this.snapshotRegistry = Objects.requireNonNull(snapshotRegistry);
         this.groupId = Objects.requireNonNull(groupId);
-        this.state = new TimelineObject<>(snapshotRegistry, EMPTY);
+        this.state = new TimelineObject<>(snapshotRegistry, INITIALIZING);
         this.groupEpoch = new TimelineInteger(snapshotRegistry);
         this.members = new TimelineHashMap<>(snapshotRegistry, 0);
         this.staticMembers = new TimelineHashMap<>(snapshotRegistry, 0);
@@ -246,6 +245,7 @@ public class StreamsGroup implements Group {
 
     public void setTopology(StreamsTopology topology) {
         this.topology.set(Optional.of(topology));
+        maybeUpdateGroupState();
     }
 
     /**
@@ -648,9 +648,10 @@ public class StreamsGroup implements Group {
      */
     public Map<String, TopicMetadata> computeSubscriptionMetadata(
         TopicsImage topicsImage,
-        ClusterImage clusterImage
+        ClusterImage clusterImage,
+        StreamsTopology topology
     ) {
-        Set<String> subscribedTopicNames = topology.get().map(StreamsTopology::topicSubscription).orElse(Collections.emptySet());
+        Set<String> subscribedTopicNames = topology.topicSubscription();
 
         // Create the topic metadata for each subscribed topic.
         Map<String, TopicMetadata> newSubscriptionMetadata = new HashMap<>(subscribedTopicNames.size());
@@ -685,6 +686,24 @@ public class StreamsGroup implements Group {
         return Collections.unmodifiableMap(newSubscriptionMetadata);
     }
 
+    /**
+     * Computes the subscription metadata based on the current subscription info.
+     *
+     * @param topicsImage          The current metadata for all available topics.
+     * @param clusterImage         The current metadata for the Kafka cluster.
+     * @return An immutable map of subscription metadata for each topic that the consumer group is subscribed to.
+     */
+    public Map<String, TopicMetadata> computeSubscriptionMetadata(
+        TopicsImage topicsImage,
+        ClusterImage clusterImage
+    ) {
+        Optional<StreamsTopology> topology = this.topology.get();
+        if (topology.isPresent()) {
+            return computeSubscriptionMetadata(topicsImage, clusterImage, topology.get());
+        }
+        return Collections.emptyMap();
+    }
+
     /**
      * Updates the metadata refresh deadline.
      *
@@ -791,7 +810,7 @@ public class StreamsGroup implements Group {
      */
     @Override
     public void validateDeleteGroup() throws ApiException {
-        if (state() != StreamsGroupState.EMPTY) {
+        if (state() != StreamsGroupState.EMPTY && state() != StreamsGroupState.INITIALIZING) {
             throw Errors.NON_EMPTY_GROUP.exception();
         }
     }
@@ -809,13 +828,13 @@ public class StreamsGroup implements Group {
     @Override
     public void createGroupTombstoneRecords(List<CoordinatorRecord> records) {
         members().forEach((memberId, member) ->
-            records.add(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentTombstoneRecord(groupId(), memberId))
         );
 
         members().forEach((memberId, member) ->
-            records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentTombstoneRecord(groupId(), memberId))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentTombstoneRecord(groupId(), memberId))
         );
-        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochTombstoneRecord(groupId()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochTombstoneRecord(groupId()));
 
         members().forEach((memberId, member) ->
             records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberTombstoneRecord(groupId(), memberId))
@@ -865,7 +884,9 @@ public class StreamsGroup implements Group {
     private void maybeUpdateGroupState() {
         StreamsGroupState previousState = state.get();
         StreamsGroupState newState = STABLE;
-        if (members.isEmpty()) {
+        if (topology() == null) {
+            newState = INITIALIZING;
+        } else if (members.isEmpty()) {
             newState = EMPTY;
         } else if (groupEpoch.get() > targetAssignmentEpoch.get()) {
             newState = ASSIGNING;
@@ -1058,7 +1079,7 @@ public class StreamsGroup implements Group {
         records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId(), groupEpoch()));
 
         members().forEach((streamsGroupMemberId, streamsGroupMember) ->
-            records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
                 groupId(),
                 streamsGroupMemberId,
                 targetAssignment(streamsGroupMemberId).activeTasks(),
@@ -1067,11 +1088,11 @@ public class StreamsGroup implements Group {
             ))
         );
 
-        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId(), groupEpoch()));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId(), groupEpoch()));
         records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId(), subscriptionMetadata()));
 
         members().forEach((__, streamsGroupMember) ->
-            records.add(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(groupId(), streamsGroupMember))
+            records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId(), streamsGroupMember))
         );
     }
 
@@ -1115,9 +1136,4 @@ public class StreamsGroup implements Group {
         }
         return false;
     }
-
-    public void setTopology(final StreamsGroupTopologyValue topology) {
-        this.topology.set(Optional.of(new StreamsTopology(topology.topologyId(), topology.topology().stream().collect(Collectors.toMap(
-            Subtopology::subtopology, x -> x)))));
-    }
 }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 5f09941fae9..ca2fd9a6da0 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -16,8 +16,10 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
+import java.util.HashMap;
 import java.util.List;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
@@ -37,11 +39,41 @@ public class StreamsTopology {
 
     private final Map<String, Subtopology> subtopologies;
 
-    public StreamsTopology(final String topologyId, final Map<String, Subtopology> subtopologies) {
+    public StreamsTopology(final String topologyId,
+                           final Map<String, Subtopology> subtopologies) {
         this.topologyId = topologyId;
         this.subtopologies = subtopologies;
     }
 
+    public StreamsTopology(final String topologyId,
+                           final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies) {
+        this.topologyId = topologyId;
+        this.subtopologies = new HashMap<>();
+        subtopologies.forEach(subtopology -> {
+            List<StreamsGroupTopologyValue.TopicInfo> repartitionSourceTopics = subtopology.repartitionSourceTopics().stream()
+                .map(topicInfo -> {
+                    List<StreamsGroupTopologyValue.TopicConfig> topicConfigs =  topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+                        .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                        .collect(Collectors.toList()) : null;
+                    return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs)
+                        .setPartitions(topicInfo.partitions());
+                }).collect(Collectors.toList());
+
+            List<StreamsGroupTopologyValue.TopicInfo> stateChangelogTopics = subtopology.stateChangelogTopics().stream().map(topicInfo -> {
+                List<StreamsGroupTopologyValue.TopicConfig> topicConfigs = topicInfo.topicConfigs() != null ? topicInfo.topicConfigs().stream()
+                    .map(config -> new StreamsGroupTopologyValue.TopicConfig().setKey(config.key()).setValue(config.value()))
+                    .collect(Collectors.toList()) : null;
+                return new StreamsGroupTopologyValue.TopicInfo().setName(topicInfo.name()).setTopicConfigs(topicConfigs);
+            }).collect(Collectors.toList());
+
+            this.subtopologies.put(
+                subtopology.subtopologyId(),
+                new StreamsGroupTopologyValue.Subtopology().setSubtopology(subtopology.subtopologyId())
+                    .setSourceTopics(subtopology.sourceTopics()).setRepartitionSinkTopics(subtopology.repartitionSinkTopics())
+                    .setRepartitionSourceTopics(repartitionSourceTopics).setStateChangelogTopics(stateChangelogTopics));
+        });
+    }
+
     public String topologyId() {
         return topologyId;
     }
@@ -57,9 +89,7 @@ public class StreamsTopology {
                 Collectors.toSet());
     }
 
-    public static StreamsTopology fromRecord(
-        StreamsGroupTopologyValue record
-    ) {
+    public static StreamsTopology fromRecord(StreamsGroupTopologyValue record) {
         return new StreamsTopology(
             record.topologyId(),
             record.topology().stream().collect(Collectors.toMap(Subtopology::subtopology, x -> x))
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
index a09919e2157..d4cb0b85275 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilder.java
@@ -306,7 +306,7 @@ public class TargetAssignmentBuilder {
 
             if (oldMemberAssignment == null) {
                 // If the member had no assignment, we always create a record for it.
-                records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
+                records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
                     groupId,
                     memberId,
                     newMemberAssignment.activeTasks(),
@@ -317,7 +317,7 @@ public class TargetAssignmentBuilder {
                 // If the member had an assignment, we only create a record if the
                 // new assignment is different.
                 if (!newMemberAssignment.equals(oldMemberAssignment)) {
-                    records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(
+                    records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
                         groupId,
                         memberId,
                         newMemberAssignment.activeTasks(),
@@ -329,7 +329,7 @@ public class TargetAssignmentBuilder {
         });
 
         // Bump the target assignment epoch.
-        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId, groupEpoch));
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, groupEpoch));
 
         return new TargetAssignmentResult(records, newTargetAssignment);
     }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
index 263b2ab76ea..03966c07ea8 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorShardTest.java
@@ -1009,16 +1009,16 @@ public class GroupCoordinatorShardTest {
 
         // Confirm the cleanup is scheduled when the coordinator is initially loaded.
         coordinator.onLoaded(image);
-        assertTrue(timer.contains(GROUP_EXPIRATION_KEY));
+        assertTrue(timer.isScheduled(GROUP_EXPIRATION_KEY));
 
         // Confirm that it is rescheduled after completion.
         mockTime.sleep(1000L);
         List<MockCoordinatorTimer.ExpiredTimeout<Void, CoordinatorRecord>> tasks = timer.poll();
         assertEquals(1, tasks.size());
-        assertTrue(timer.contains(GROUP_EXPIRATION_KEY));
+        assertTrue(timer.isScheduled(GROUP_EXPIRATION_KEY));
 
         coordinator.onUnloaded();
-        assertFalse(timer.contains(GROUP_EXPIRATION_KEY));
+        assertFalse(timer.isScheduled(GROUP_EXPIRATION_KEY));
     }
 
     @Test
@@ -1058,9 +1058,9 @@ public class GroupCoordinatorShardTest {
             return null;
         }).when(groupMetadataManager).maybeDeleteGroup(eq("group-id"), recordsCapture.capture());
 
-        assertFalse(timer.contains(GROUP_EXPIRATION_KEY));
+        assertFalse(timer.isScheduled(GROUP_EXPIRATION_KEY));
         CoordinatorResult<Void, CoordinatorRecord> result = coordinator.cleanupGroupMetadata();
-        assertTrue(timer.contains(GROUP_EXPIRATION_KEY));
+        assertTrue(timer.isScheduled(GROUP_EXPIRATION_KEY));
 
         List<CoordinatorRecord> expectedRecords = Arrays.asList(offsetCommitTombstone, groupMetadataTombstone);
         assertEquals(expectedRecords, result.records());
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
index 05a94ea49a6..58d3a4e5ecc 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTest.java
@@ -56,6 +56,9 @@ import org.apache.kafka.common.message.ShareGroupHeartbeatRequestData;
 import org.apache.kafka.common.message.ShareGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
+import org.apache.kafka.common.message.StreamsGroupInitializeResponseData;
 import org.apache.kafka.common.message.SyncGroupRequestData;
 import org.apache.kafka.common.message.SyncGroupRequestData.SyncGroupRequestAssignment;
 import org.apache.kafka.common.message.SyncGroupResponseData;
@@ -95,6 +98,7 @@ import org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelper
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
+import org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.image.MetadataProvenance;
@@ -125,6 +129,8 @@ import static org.apache.kafka.common.protocol.Errors.NOT_COORDINATOR;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH;
 import static org.apache.kafka.common.requests.ConsumerGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH;
 import static org.apache.kafka.common.requests.JoinGroupRequest.UNKNOWN_MEMBER_ID;
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.Assertions.assertRecordEquals;
 import static org.apache.kafka.coordinator.group.Assertions.assertRecordsEquals;
 import static org.apache.kafka.coordinator.group.Assertions.assertResponseEquals;
@@ -410,6 +416,440 @@ public class GroupMetadataManagerTest {
         assertEquals(2, result.response().memberEpoch());
     }
 
+    @Test
+    public void testJoiningNonExistingStreamsGroup() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeat = buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+
+        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
+
+        assertNotNull(result.response());
+        StreamsGroupHeartbeatResponseData response = result.response();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertFalse(response.memberId().isEmpty());
+        assertEquals(1, response.memberEpoch());
+        assertTrue(response.shouldInitializeTopology());
+        assertTrue(response.activeTasks().isEmpty());
+        assertTrue(response.standbyTasks().isEmpty());
+        assertTrue(response.warmupTasks().isEmpty());
+        List<CoordinatorRecord> coordinatorRecords = result.records();
+        assertEquals(5, coordinatorRecords.size());
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 1)));
+        StreamsGroupMember member = new StreamsGroupMember.Builder(response.memberId())
+            .setClientId("client")
+            .setClientHost("localhost/127.0.0.1")
+            .setRebalanceTimeoutMs(rebalanceTimeoutMs)
+            .setTopologyId(topologyId)
+            .setProcessId(processId)
+            .build();
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId, member)));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 1)));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
+                groupId,
+                member.memberId(),
+                Collections.emptyMap(),
+                Collections.emptyMap(),
+                Collections.emptyMap()
+            )
+        ));
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(
+                1,
+                new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())
+            )
+            .withCurrentActiveTaskEpoch((a, b) -> 1)
+            .withOwnedActiveTasks(Collections.emptyList())
+            .withOwnedStandbyTasks(Collections.emptyList())
+            .withOwnedWarmupTasks(Collections.emptyList())
+            .build();
+        CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember);
+        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, context.streamsGroupState("group-id"));
+        assertTrue(context.timer.isScheduled("topology-initialization-timeout-group-id-topology-id"));
+        assertEquals(rebalanceTimeoutMs, context.timer.timeout("topology-initialization-timeout-group-id-topology-id").deadlineMs - context.time.milliseconds());
+    }
+
+    @Test
+    public void testJoiningExistingInitializingStreamsGroup() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        StreamsGroupHeartbeatRequestData heartbeat =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+
+        CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> result = context.streamsGroupHeartbeat(heartbeat);
+
+        assertNotNull(result.response());
+        StreamsGroupHeartbeatResponseData response = result.response();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertFalse(response.memberId().isEmpty());
+        assertEquals(2, response.memberEpoch());
+        assertFalse(response.shouldInitializeTopology());
+        assertTrue(response.activeTasks().isEmpty());
+        assertTrue(response.standbyTasks().isEmpty());
+        assertTrue(response.warmupTasks().isEmpty());
+        List<CoordinatorRecord> coordinatorRecords = result.records();
+        assertEquals(5, coordinatorRecords.size());
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
+        StreamsGroupMember member = new StreamsGroupMember.Builder(response.memberId())
+            .setClientId("client")
+            .setClientHost("localhost/127.0.0.1")
+            .setRebalanceTimeoutMs(rebalanceTimeoutMs)
+            .setTopologyId(topologyId)
+            .setProcessId(processId)
+            .build();
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(groupId, member)));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 2)));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
+                groupId,
+                member.memberId(),
+                Collections.emptyMap(),
+                Collections.emptyMap(),
+                Collections.emptyMap()
+            )
+        ));
+        StreamsGroupMember updatedMember = new org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder(member)
+            .withTargetAssignment(
+                1,
+                new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())
+            )
+            .withCurrentActiveTaskEpoch((a, b) -> 1)
+            .withOwnedActiveTasks(Collections.emptyList())
+            .withOwnedStandbyTasks(Collections.emptyList())
+            .withOwnedWarmupTasks(Collections.emptyList())
+            .build();
+        CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, updatedMember);
+        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, context.streamsGroupState("group-id"));
+    }
+
+    @Test
+    public void testInitTopologyExistingInitializingStreamsGroup() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        String inputTopicName = "input-topic";
+        String subtopologyId = "subtopology-id";
+        Uuid inputTopicId = Uuid.randomUuid();
+        MetadataImage metadataImage = new MetadataImageBuilder()
+            .addTopic(inputTopicId, inputTopicName, 3)
+            .addRacks()
+            .build();
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(metadataImage)
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
+            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
+        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+        );
+        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
+        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
+            .setGroupId(groupId)
+            .setTopologyId(topologyId)
+            .setTopology(subtopologies);
+
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+
+        assertNotNull(result.response());
+        StreamsGroupInitializeResponseData response = result.response();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        List<CoordinatorRecord> coordinatorRecords = result.records();
+        assertEquals(5, coordinatorRecords.size());
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(groupId, 2)));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord(groupId, subtopologies)));
+        org.apache.kafka.coordinator.group.streams.TopicMetadata topicMetadata = new org.apache.kafka.coordinator.group.streams.TopicMetadata(
+            inputTopicId,
+            inputTopicName,
+            3,
+            mkMap(
+                mkEntry(0, mkSet("rack0", "rack1")),
+                mkEntry(1, mkSet("rack1", "rack2")),
+                mkEntry(2, mkSet("rack2", "rack3"))
+            )
+        );
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord(groupId, mkMap(mkEntry(inputTopicName, topicMetadata)))
+        ));
+        assertTrue(coordinatorRecords.contains(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId, 2)));
+        assertTrue(coordinatorRecords.contains(
+            CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(
+                groupId,
+                heartbeatResult.response().memberId(),
+                TaskAssignmentTestUtil.mkAssignment(TaskAssignmentTestUtil.mkTaskAssignment(subtopologyId, 0, 1, 2)),
+                Collections.emptyMap(),
+                Collections.emptyMap()
+            )
+        ));
+        assertFalse(context.timer.isScheduled("topology-initialization-timeout-group-id-topology-id"));
+        assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, context.streamsGroupState("group-id"));
+    }
+
+    @Test
+    public void testInitTopologyWithWrongGroupId() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        String inputTopicName = "input-topic";
+        String subtopologyId = "subtopology-id";
+        Uuid inputTopicId = Uuid.randomUuid();
+        MetadataImage metadataImage = new MetadataImageBuilder()
+            .addTopic(inputTopicId, inputTopicName, 3)
+            .addRacks()
+            .build();
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(metadataImage)
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
+            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
+        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+        );
+        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
+        final String wrongGroupId = "wrong-" + groupId;
+        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
+            .setGroupId(wrongGroupId)
+            .setTopologyId(topologyId)
+            .setTopology(subtopologies);
+
+        final GroupIdNotFoundException groupIdNotFoundException =
+            assertThrows(GroupIdNotFoundException.class, () -> context.streamsGroupInitialize(initialize));
+
+        assertEquals(
+            "Streams group " + wrongGroupId + " not found.",
+            groupIdNotFoundException.getMessage()
+        );
+    }
+
+    @Test
+    public void testInitTopologyWithWrongTopologyId() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        String inputTopicName = "input-topic";
+        String subtopologyId = "subtopology-id";
+        Uuid inputTopicId = Uuid.randomUuid();
+        MetadataImage metadataImage = new MetadataImageBuilder()
+            .addTopic(inputTopicId, inputTopicName, 3)
+            .addRacks()
+            .build();
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(metadataImage)
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
+            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
+        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+        );
+        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
+        final String wrongTopologyId = "wrong-" + topologyId;
+        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
+            .setGroupId(groupId)
+            .setTopologyId(wrongTopologyId)
+            .setTopology(subtopologies);
+
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+
+        assertNotNull(result.response());
+        StreamsGroupInitializeResponseData response = result.response();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertTrue(result.records().isEmpty());
+    }
+
+    @Test
+    public void testInitTopologyForInitializedStreamsGroup() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        String inputTopicName = "input-topic";
+        String subtopologyId = "subtopology-id";
+        Uuid inputTopicId = Uuid.randomUuid();
+        MetadataImage metadataImage = new MetadataImageBuilder()
+            .addTopic(inputTopicId, inputTopicName, 3)
+            .addRacks()
+            .build();
+        MockTaskAssignor assignor = new MockTaskAssignor("mock");
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(metadataImage)
+            .withTaskAssignors(Collections.singletonList(assignor))
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        final CoordinatorResult<StreamsGroupHeartbeatResponseData, CoordinatorRecord> heartbeatResult =
+            context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        final List<StreamsGroupInitializeRequestData.Subtopology> subtopologies = new ArrayList<>();
+        subtopologies.add(new StreamsGroupInitializeRequestData.Subtopology()
+            .setSubtopologyId(subtopologyId)
+            .setRepartitionSinkTopics(Collections.emptyList())
+            .setRepartitionSourceTopics(Collections.emptyList())
+            .setSourceTopics(Collections.singletonList("input-topic"))
+        );
+        prepareStreamsGroupAssignment(assignor, heartbeatResult.response().memberId(), subtopologyId);
+        StreamsGroupInitializeRequestData initialize = new StreamsGroupInitializeRequestData()
+            .setGroupId(groupId)
+            .setTopologyId(topologyId)
+            .setTopology(subtopologies);
+
+        context.streamsGroupInitialize(initialize);
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result = context.streamsGroupInitialize(initialize);
+
+        assertNotNull(result.response());
+        StreamsGroupInitializeResponseData response = result.response();
+        assertEquals(Errors.NONE.code(), response.errorCode());
+        assertTrue(result.records().isEmpty());
+    }
+
+    @Test
+    public void testTopologyInitializationMissingInternalTopics() {
+        String groupId = "group-id";
+        int rebalanceTimeoutMs = 300000;
+        String topologyId = "topology-id";
+        String processId = "process-id";
+        Uuid fooTopicId = Uuid.randomUuid();
+        String fooTopicName = "repartition";
+        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
+            .withMetadataImage(new MetadataImageBuilder()
+                .addTopic(fooTopicId, fooTopicName, 6)
+                .addRacks()
+                .build())
+            .build();
+        StreamsGroupHeartbeatRequestData heartbeatToCreateAndRequestInitGroup =
+            buildFirstStreamsGroupHeartbeatRequest(groupId, topologyId, processId, rebalanceTimeoutMs);
+        context.streamsGroupHeartbeat(heartbeatToCreateAndRequestInitGroup);
+        assertThrows(GroupIdNotFoundException.class, () ->
+            context.groupMetadataManager.consumerGroup(groupId));
+        final List<StreamsGroupInitializeRequestData.Subtopology> topology = Collections.singletonList(
+            new StreamsGroupInitializeRequestData.Subtopology()
+                .setSubtopologyId("subtopology-id")
+                .setSourceTopics(Collections.singletonList("bar"))
+                .setRepartitionSourceTopics(
+                    Collections.singletonList(
+                        new StreamsGroupInitializeRequestData.TopicInfo()
+                            .setName("repartition")
+                            .setPartitions(4)
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                    .setKey("config-name1")
+                                    .setValue("config-value1")
+                            ))
+                    )
+                )
+                .setStateChangelogTopics(
+                    Collections.singletonList(
+                        new StreamsGroupInitializeRequestData.TopicInfo()
+                            .setName("changelog")
+                            .setTopicConfigs(Collections.singletonList(
+                                new StreamsGroupInitializeRequestData.TopicConfig()
+                                    .setKey("config-name2")
+                                    .setValue("config-value2")
+                            ))
+                    )
+                )
+        );
+        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
+            context.streamsGroupInitialize(
+                new StreamsGroupInitializeRequestData()
+                    .setGroupId(groupId)
+                    .setTopologyId(topologyId)
+                    .setTopology(topology)
+            );
+
+        assertEquals(
+            new StreamsGroupInitializeResponseData()
+                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
+                .setErrorMessage("Internal topics changelog do not exist."),
+            result.response()
+        );
+        
+        assertTrue(result.records().isEmpty());
+    }
+
+    private StreamsGroupHeartbeatRequestData buildFirstStreamsGroupHeartbeatRequest(
+        final String groupId,
+        final String topologyId,
+        final String processId,
+        final int rebalanceTimeoutMs) {
+
+        return new StreamsGroupHeartbeatRequestData()
+            .setGroupId(groupId)
+            .setMemberId("")
+            .setMemberEpoch(0)
+            .setInstanceId(null)
+            .setRackId(null)
+            .setRebalanceTimeoutMs(rebalanceTimeoutMs)
+            .setTopologyId(topologyId)
+            .setActiveTasks(Collections.emptyList())
+            .setStandbyTasks(Collections.emptyList())
+            .setWarmupTasks(Collections.emptyList())
+            .setProcessId(processId)
+            .setUserEndpoint(null)
+            .setClientTags(null)
+            .setTaskOffsets(null)
+            .setTaskEndOffsets(null)
+            .setShutdownApplication(false);
+    }
+
+    private void prepareStreamsGroupAssignment(final MockTaskAssignor assignor,
+                                               final String memberId,
+                                               final String subtopologyId) {
+        assignor.prepareGroupAssignment(new org.apache.kafka.coordinator.group.taskassignor.GroupAssignment(
+            mkMap(
+                mkEntry(
+                    memberId,
+                    new org.apache.kafka.coordinator.group.taskassignor.MemberAssignment(
+                        mkMap(
+                            mkEntry(
+                                subtopologyId,
+                                mkSet(0, 1, 2)
+                            )
+                        ),
+                        Collections.emptyMap(),
+                        Collections.emptyMap()
+                    )
+                )
+            )
+        ));
+    }
+
     @Test
     public void testMemberIdGeneration() {
         MockPartitionAssignor assignor = new MockPartitionAssignor("range");
@@ -8865,7 +9305,7 @@ public class GroupMetadataManagerTest {
             new StreamsGroupDescribeResponseData.DescribedGroup()
                 .setGroupEpoch(epoch)
                 .setGroupId(streamsGroupIds.get(0))
-                .setGroupState(StreamsGroup.StreamsGroupState.EMPTY.toString())
+                .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
                 .setAssignmentEpoch(0),
             new StreamsGroupDescribeResponseData.DescribedGroup()
                 .setGroupEpoch(epoch)
@@ -8875,7 +9315,7 @@ public class GroupMetadataManagerTest {
                         new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())
                     )
                 ))
-                .setGroupState(StreamsGroup.StreamsGroupState.ASSIGNING.toString())
+                .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
         );
         List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.sendStreamsGroupDescribe(streamsGroupIds);
 
@@ -8924,8 +9364,8 @@ public class GroupMetadataManagerTest {
 
         StreamsGroupMember.Builder memberBuilder2 = new StreamsGroupMember.Builder(memberId2);
         context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord(streamsGroupId, memberBuilder2.build()));
-        context.replay(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(streamsGroupId, memberId2, assignmentMap, assignmentMap, assignmentMap));
-        context.replay(CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(streamsGroupId, memberBuilder2.build()));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(streamsGroupId, memberId2, assignmentMap, assignmentMap, assignmentMap));
+        context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(streamsGroupId, memberBuilder2.build()));
         context.replay(CoordinatorStreamsRecordHelpers.newStreamsGroupEpochRecord(streamsGroupId, epoch + 2));
 
         List<StreamsGroupDescribeResponseData.DescribedGroup> actual = context.groupMetadataManager.streamsGroupDescribe(Collections.singletonList(streamsGroupId), context.lastCommittedOffset);
@@ -8945,7 +9385,7 @@ public class GroupMetadataManagerTest {
                 memberBuilder1.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(Collections.emptyMap())),
                 memberBuilder2.build().asStreamsGroupDescribeMember(new org.apache.kafka.coordinator.group.streams.Assignment(assignmentMap, assignmentMap, assignmentMap))
             ))
-            .setGroupState(StreamsGroup.StreamsGroupState.ASSIGNING.toString())
+            .setGroupState(StreamsGroup.StreamsGroupState.INITIALIZING.toString())
             .setGroupEpoch(epoch + 2);
         assertEquals(1, actual.size());
         assertEquals(describedGroup, actual.get(0));
@@ -15963,144 +16403,4 @@ public class GroupMetadataManagerTest {
         assertEquals(expectedSuccessCount, successCount);
         return memberIds;
     }
-
-    // TODO: bring back topology initialization unit tests
-//    @Test
-//    public void testTopologyInitialization() {
-//        String groupId = "fooup";
-//
-//        Uuid fooTopicId = Uuid.randomUuid();
-//        String fooTopicName = "repartition";
-//        Uuid barTopicId = Uuid.randomUuid();
-//        String barTopicName = "changelog";
-//
-//        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-//            .withMetadataImage(new MetadataImageBuilder()
-//                .addTopic(fooTopicId, fooTopicName, 6)
-//                .addTopic(barTopicId, barTopicName, 3)
-//                .addRacks()
-//                .build())
-//            .build();
-//
-//        context.createStreamsGroup(groupId);
-//
-//        assertThrows(GroupIdNotFoundException.class, () ->
-//            context.groupMetadataManager.consumerGroup(groupId));
-//
-//        final List<Subtopology> topology = Collections.singletonList(
-//            new Subtopology()
-//                .setSubtopology("subtopology-id")
-//                .setSinkTopics(Collections.singletonList("foo"))
-//                .setSourceTopics(Collections.singletonList("bar"))
-//                .setRepartitionSourceTopics(
-//                    Collections.singletonList(
-//                        new TopicInfo()
-//                            .setName("repartition")
-//                            .setPartitions(4)
-//                            .setTopicConfigs(Collections.singletonList(
-//                                new TopicConfig()
-//                                    .setKey("config-name1")
-//                                    .setValue("config-value1")
-//                            ))
-//                    )
-//                )
-//                .setStateChangelogTopics(
-//                    Collections.singletonList(
-//                        new TopicInfo()
-//                            .setName("changelog")
-//                            .setTopicConfigs(Collections.singletonList(
-//                                new TopicConfig()
-//                                    .setKey("config-name2")
-//                                    .setValue("config-value2")
-//                            ))
-//                    )
-//                )
-//        );
-//        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
-//            context.streamsGroupInitialize(
-//                new streamsGroupInitializeRequestData()
-//                    .setGroupId(groupId)
-//                    .setTopology(topology)
-//            );
-//
-//        assertEquals(
-//            new StreamsGroupInitializeResponseData(),
-//            result.response()
-//        );
-//
-//        List<CoordinatorRecord> expectedRecords = Arrays.asList(
-//            CoordinatorRecordHelpers.newStreamsGroupTopologyRecord(
-//                groupId,
-//                topology
-//            )
-//        );
-//
-//        assertRecordsEquals(expectedRecords, result.records());
-//    }
-//
-//    @Test
-//    public void testTopologyInitializationMissingInternalTopics() {
-//        String groupId = "fooup";
-//
-//        Uuid fooTopicId = Uuid.randomUuid();
-//        String fooTopicName = "repartition";
-//
-//        GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
-//            .withMetadataImage(new MetadataImageBuilder()
-//                .addTopic(fooTopicId, fooTopicName, 6)
-//                .addRacks()
-//                .build())
-//            .build();
-//
-//        context.createStreamsGroup(groupId);
-//
-//        assertThrows(GroupIdNotFoundException.class, () ->
-//            context.groupMetadataManager.consumerGroup(groupId));
-//
-//        final List<Subtopology> topology = Collections.singletonList(
-//            new Subtopology()
-//                .setSubtopology("subtopology-id")
-//                .setSinkTopics(Collections.singletonList("foo"))
-//                .setSourceTopics(Collections.singletonList("bar"))
-//                .setRepartitionSourceTopics(
-//                    Collections.singletonList(
-//                        new TopicInfo()
-//                            .setName("repartition")
-//                            .setPartitions(4)
-//                            .setTopicConfigs(Collections.singletonList(
-//                                new TopicConfig()
-//                                    .setKey("config-name1")
-//                                    .setValue("config-value1")
-//                            ))
-//                    )
-//                )
-//                .setStateChangelogTopics(
-//                    Collections.singletonList(
-//                        new TopicInfo()
-//                            .setName("changelog")
-//                            .setTopicConfigs(Collections.singletonList(
-//                                new TopicConfig()
-//                                    .setKey("config-name2")
-//                                    .setValue("config-value2")
-//                            ))
-//                    )
-//                )
-//        );
-//        CoordinatorResult<StreamsGroupInitializeResponseData, CoordinatorRecord> result =
-//            context.streamsGroupInitialize(
-//                new streamsGroupInitializeRequestData()
-//                    .setGroupId(groupId)
-//                    .setTopology(topology)
-//            );
-//
-//        assertEquals(
-//            new StreamsGroupInitializeResponseData()
-//                .setErrorCode(Errors.STREAMS_INVALID_TOPOLOGY.code())
-//                .setErrorMessage("Internal topics changelog do not exist."),
-//            result.response()
-//        );
-//
-//        assertTrue(result.records().isEmpty());
-//
-//    }
 }
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
index d77f5414ee9..96fd18344c0 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupMetadataManagerTestContext.java
@@ -109,6 +109,7 @@ import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroup;
 import org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupBuilder;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroup;
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupBuilder;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupBuilder;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataImage;
@@ -651,6 +652,14 @@ public class GroupMetadataManagerTestContext {
             .state();
     }
 
+    public StreamsGroup.StreamsGroupState streamsGroupState(
+        String groupId
+    ) {
+        return groupMetadataManager
+            .streamsGroup(groupId)
+            .state();
+    }
+
     public MemberState consumerGroupMemberState(
         String groupId,
         String memberId
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index cf1a003cd84..b9298dab3f3 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -34,7 +34,7 @@ class CoordinatorStreamsRecordHelpersTest {
     public void testNewStreamsGroupTopologyRecord() {
         List<StreamsGroupInitializeRequestData.Subtopology> topology =
             Collections.singletonList(new StreamsGroupInitializeRequestData.Subtopology()
-                .setSubtopology("subtopology-id")
+                .setSubtopologyId("subtopology-id")
                 .setRepartitionSinkTopics(Collections.singletonList("foo"))
                 .setSourceTopics(Collections.singletonList("bar"))
                 .setRepartitionSourceTopics(
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
index b07dabc05e1..ed5c93d4b86 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
@@ -82,18 +82,18 @@ public class StreamsGroupBuilder {
         // Add target assignment records.
         assignments.forEach((memberId, assignment) ->
             records.add(
-                CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord(groupId, memberId,
+                CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord(groupId, memberId,
                     assignment.activeTasks(), assignment.standbyTasks(), assignment.warmupTasks()))
         );
 
         // Add target assignment epoch.
-        records.add(CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord(groupId,
+        records.add(CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord(groupId,
             assignmentEpoch));
 
         // Add current assignment records for members.
         members.forEach((memberId, member) ->
             records.add(
-                CoordinatorStreamsRecordHelpers.newStreamsCurrentAssignmentRecord(groupId, member))
+                CoordinatorStreamsRecordHelpers.newStreamsGroupCurrentAssignmentRecord(groupId, member))
         );
 
         return records;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index 2fd5d461c99..8d2a0bfa418 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -396,7 +396,7 @@ public class StreamsGroupTest {
     @Test
     public void testGroupState() {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
-        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
 
         StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
             .setState(MemberState.STABLE)
@@ -407,6 +407,11 @@ public class StreamsGroupTest {
         streamsGroup.updateMember(member1);
         streamsGroup.setGroupEpoch(1);
 
+        assertEquals(MemberState.STABLE, member1.state());
+        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
+
+        streamsGroup.setTopology(new StreamsTopology("topology-id", Collections.emptyMap()));
+
         assertEquals(MemberState.STABLE, member1.state());
         assertEquals(StreamsGroup.StreamsGroupState.ASSIGNING, streamsGroup.state());
 
@@ -668,7 +673,7 @@ public class StreamsGroupTest {
     public void testValidateDeleteGroup() {
         StreamsGroup streamsGroup = createStreamsGroup("foo");
 
-        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+        assertEquals(StreamsGroup.StreamsGroupState.INITIALIZING, streamsGroup.state());
         assertDoesNotThrow(streamsGroup::validateDeleteGroup);
 
         StreamsGroupMember member1 = new StreamsGroupMember.Builder("member1")
@@ -676,6 +681,7 @@ public class StreamsGroupTest {
             .setPreviousMemberEpoch(0)
             .build();
         streamsGroup.updateMember(member1);
+        streamsGroup.setTopology(new StreamsTopology("topology-id", Collections.emptyMap()));
 
         assertEquals(StreamsGroup.StreamsGroupState.RECONCILING, streamsGroup.state());
         assertThrows(GroupNotEmptyException.class, streamsGroup::validateDeleteGroup);
@@ -689,6 +695,10 @@ public class StreamsGroupTest {
 
         assertEquals(StreamsGroup.StreamsGroupState.STABLE, streamsGroup.state());
         assertThrows(GroupNotEmptyException.class, streamsGroup::validateDeleteGroup);
+
+        streamsGroup.removeMember("member1");
+        assertEquals(StreamsGroup.StreamsGroupState.EMPTY, streamsGroup.state());
+        assertDoesNotThrow(streamsGroup::validateDeleteGroup);
     }
 
     @Test
@@ -717,14 +727,13 @@ public class StreamsGroupTest {
         );
         StreamsGroup group = new StreamsGroup(snapshotRegistry, "group-foo", metricsShard);
         snapshotRegistry.idempotentCreateSnapshot(0);
-        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
-        assertFalse(group.isInStates(Collections.singleton("Empty"), 0));
-
-        group.updateMember(new StreamsGroupMember.Builder("member1")
-            .build());
-        snapshotRegistry.idempotentCreateSnapshot((1));
-        assertTrue(group.isInStates(Collections.singleton("empty"), 0));
-        assertTrue(group.isInStates(Collections.singleton("stable"), 1));
-        assertFalse(group.isInStates(Collections.singleton("empty"), 1));
+        assertTrue(group.isInStates(Collections.singleton("initializing"), 0));
+        assertFalse(group.isInStates(Collections.singleton("Initializing"), 0));
+
+        group.setTopology(new StreamsTopology("topology-id", Collections.emptyMap()));
+        snapshotRegistry.idempotentCreateSnapshot(1);
+        assertTrue(group.isInStates(Collections.singleton("initializing"), 0));
+        assertTrue(group.isInStates(Collections.singleton("empty"), 1));
+        assertFalse(group.isInStates(Collections.singleton("initializing"), 1));
     }
 }
\ No newline at end of file
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index c6b135eeebf..230e63b9058 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -40,8 +40,8 @@ import static org.apache.kafka.common.utils.Utils.mkEntry;
 import static org.apache.kafka.common.utils.Utils.mkMap;
 import static org.apache.kafka.coordinator.group.Assertions.assertUnorderedListEquals;
 import static org.apache.kafka.coordinator.group.CoordinatorRecordHelpersTest.mkMapOfPartitionRacks;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentEpochRecord;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsTargetAssignmentRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentRecord;
 import static org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.createAssignmentMemberSpec;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkAssignment;
 import static org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.mkTaskAssignment;
@@ -299,7 +299,7 @@ public class TargetAssignmentBuilderTest {
         );
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
-        assertEquals(Collections.singletonList(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(Collections.singletonList(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         )), result.records());
@@ -338,7 +338,7 @@ public class TargetAssignmentBuilderTest {
 
         org.apache.kafka.coordinator.group.streams.TargetAssignmentBuilder.TargetAssignmentResult result = context.build();
 
-        assertEquals(Collections.singletonList(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(Collections.singletonList(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         )), result.records());
@@ -391,17 +391,17 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
                 mkTaskAssignment(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -461,21 +461,21 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2),
                 mkTaskAssignment(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4),
                 mkTaskAssignment(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(3));
@@ -547,21 +547,21 @@ public class TargetAssignmentBuilderTest {
         assertEquals(4, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2),
                 mkTaskAssignment(barSubtopologyId, 1, 2)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4),
                 mkTaskAssignment(barSubtopologyId, 3, 4)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 3));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(3));
@@ -629,17 +629,17 @@ public class TargetAssignmentBuilderTest {
 
         // Member 1 has no record because its assignment did not change.
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 3, 4, 5),
                 mkTaskAssignment(barSubtopologyId, 3, 4, 5)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-3", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 6),
                 mkTaskAssignment(barSubtopologyId, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -703,17 +703,17 @@ public class TargetAssignmentBuilderTest {
         assertEquals(3, result.records().size());
 
         assertUnorderedListEquals(Arrays.asList(
-            newStreamsTargetAssignmentRecord("my-group", "member-1", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-1", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 1, 2, 3),
                 mkTaskAssignment(barSubtopologyId, 1, 2, 3)
             ), Collections.emptyMap(), Collections.emptyMap()),
-            newStreamsTargetAssignmentRecord("my-group", "member-2", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-2", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 4, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 4, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 2));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(2));
@@ -783,13 +783,13 @@ public class TargetAssignmentBuilderTest {
         assertEquals(2, result.records().size());
 
         assertUnorderedListEquals(Collections.singletonList(
-            newStreamsTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
+            newStreamsGroupTargetAssignmentRecord("my-group", "member-3-a", mkAssignment(
                 mkTaskAssignment(fooSubtopologyId, 5, 6),
                 mkTaskAssignment(barSubtopologyId, 5, 6)
             ), Collections.emptyMap(), Collections.emptyMap())
         ), result.records().subList(0, 1));
 
-        assertEquals(newStreamsTargetAssignmentEpochRecord(
+        assertEquals(newStreamsGroupTargetAssignmentEpochRecord(
             "my-group",
             20
         ), result.records().get(1));


(kafka) 14/42: Define the assignor interface for streams and implement a simple assignor

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit d06afbd4a96d5ad0ba73b5e32f65b5eeeea5d66b
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Thu Jun 13 21:09:19 2024 +0200

    Define the assignor interface for streams and implement a simple assignor
    
    - interfaces in assignor package ported to a streams-specific package on dev branch
    - implementation of a simple working assingor with unit tests
    
    See https://github.com/lucasbru/kafka/pull/20
---
 core/src/main/scala/kafka/server/KafkaApis.scala   |   2 +-
 .../group/GroupCoordinatorAdapterTest.scala        |   2 +-
 .../coordinator/group/GroupMetadataManager.java    |   1 +
 .../coordinator/group/streams/Assignment.java      |  15 +-
 .../group/taskassignor/AssignmentMemberSpec.java   | 196 +++++++++++++++++++++
 .../group/taskassignor/GroupAssignment.java        |  67 +++++++
 .../coordinator/group/taskassignor/GroupSpec.java  |  37 ++++
 .../group/taskassignor/GroupSpecImpl.java          |  86 +++++++++
 .../group/taskassignor/MemberAssignment.java       |  86 +++++++++
 .../group/taskassignor/MockAssignor.java           | 115 ++++++++++++
 .../group/taskassignor/TaskAssignor.java           |  45 +++++
 .../group/taskassignor/TaskAssignorException.java  |  33 ++++
 .../coordinator/group/taskassignor/TaskId.java     |  66 +++++++
 .../group/taskassignor/TopologyDescriber.java      |  37 ++++
 .../group/taskassignor/GroupSpecImplTest.java      |  72 ++++++++
 .../group/taskassignor/MockAssignorTest.java       | 195 ++++++++++++++++++++
 16 files changed, 1048 insertions(+), 7 deletions(-)

diff --git a/core/src/main/scala/kafka/server/KafkaApis.scala b/core/src/main/scala/kafka/server/KafkaApis.scala
index 3bd368bf1e5..f47a67e5104 100644
--- a/core/src/main/scala/kafka/server/KafkaApis.scala
+++ b/core/src/main/scala/kafka/server/KafkaApis.scala
@@ -3912,7 +3912,7 @@ class KafkaApis(val requestChannel: RequestChannel,
     }
   }
 
-  def handleStreamsGroupHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
+  def handleStreamsHeartbeat(request: RequestChannel.Request): CompletableFuture[Unit] = {
     val streamsHeartbeatRequest = request.body[StreamsHeartbeatRequest]
 
     if (!config.isNewGroupCoordinatorEnabled) {
diff --git a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
index 03fcf3ff21d..1c6c66b9bcd 100644
--- a/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
+++ b/core/src/test/scala/unit/kafka/coordinator/group/GroupCoordinatorAdapterTest.scala
@@ -100,7 +100,7 @@ class GroupCoordinatorAdapterTest {
     val adapter = new GroupCoordinatorAdapter(groupCoordinator, Time.SYSTEM)
 
     val ctx = makeContext(ApiKeys.STREAMS_HEARTBEAT, ApiKeys.STREAMS_HEARTBEAT.latestVersion)
-    val request = new StreamsHeartbeatRequestData()()
+    val request = new StreamsHeartbeatRequestData()
       .setGroupId("group")
 
     val future = adapter.streamsHeartbeat(ctx, request)
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index f95b9693ca8..716d42e6701 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -203,6 +203,7 @@ import static org.apache.kafka.coordinator.group.modern.consumer.ConsumerGroupMe
  * 2) The replay methods which apply records to the hard state. Those are used in the request
  *    handling as well as during the initial loading of the records from the partitions.
  */
+@SuppressWarnings("JavaNCSS")
 public class GroupMetadataManager {
 
     public static class Builder {
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
index 54e4cbc63a4..b80e34cbfe5 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -29,6 +29,7 @@ import java.util.stream.Collectors;
  * An immutable assignment for a member.
  */
 public class Assignment {
+
     public static final Assignment EMPTY = new Assignment(
         Collections.emptyMap(),
         Collections.emptyMap(),
@@ -70,8 +71,12 @@ public class Assignment {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
         Assignment that = (Assignment) o;
         return Objects.equals(activeTasks, that.activeTasks)
             && Objects.equals(standbyTasks, that.standbyTasks)
@@ -87,7 +92,7 @@ public class Assignment {
     public String toString() {
         return "Assignment(active tasks=" + activeTasks +
             ", standby tasks=" + standbyTasks +
-            ", warm-up tasks=" + warmupTasks +')';
+            ", warm-up tasks=" + warmupTasks + ')';
     }
 
     /**
@@ -103,8 +108,8 @@ public class Assignment {
         return new Assignment(
             record.activeTasks().stream()
                 .collect(Collectors.toMap(
-                    StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
-                    taskId -> new HashSet<>(taskId.partitions())
+                        StreamsGroupTargetAssignmentMemberValue.TaskIds::subtopology,
+                        taskId -> new HashSet<>(taskId.partitions())
                     )
                 ),
             record.standbyTasks().stream()
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java
new file mode 100644
index 00000000000..64ab7ece4e9
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/AssignmentMemberSpec.java
@@ -0,0 +1,196 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * The assignment specification for a Streams group member.
+ */
+public class AssignmentMemberSpec {
+
+    /**
+     * The instance ID if provided.
+     */
+    private final Optional<String> instanceId;
+
+    /**
+     * The rack ID if provided.
+     */
+    private final Optional<String> rackId;
+
+    /**
+     * Reconciled active tasks
+     */
+    private final Map<String, Set<Integer>> activeTasks;
+
+    /**
+     * Reconciled standby tasks
+     */
+    private final Map<String, Set<Integer>> standbyTasks;
+
+    /**
+     * Reconciled warm-up tasks
+     */
+    private final Map<String, Set<Integer>> warmupTasks;
+
+    /**
+     * The process ID.
+     */
+    private final String processId;
+
+    /**
+     * The client tags for a rack-aware assignment.
+     */
+    private final Map<String, String> clientTags;
+
+    /**
+     * The assignment configs for customizing the assignment.
+     */
+    private final Map<String, String> assignmentConfigs;
+
+    /**
+     * The last received cumulative task offsets of assigned tasks or dormant tasks.
+     */
+    private final Map<TaskId, Long> taskOffsets;
+
+    /**
+     * @return The instance ID as an Optional.
+     */
+    public Optional<String> instanceId() {
+        return instanceId;
+    }
+
+    /**
+     * @return The rack ID as an Optional.
+     */
+    public Optional<String> rackId() {
+        return rackId;
+    }
+
+    /**
+     * @return The assigned active tasks.
+     */
+    public Map<String, Set<Integer>> activeTasks() {
+        return activeTasks;
+    }
+
+    /**
+     * @return The assigned standby tasks.
+     */
+    public Map<String, Set<Integer>> standbyTasks() {
+        return standbyTasks;
+    }
+
+    /**
+     * @return The assigned warm-up tasks.
+     */
+    public Map<String, Set<Integer>> warmupTasks() {
+        return warmupTasks;
+    }
+
+    public Map<TaskId, Long> taskOffsets() {
+        return taskOffsets;
+    }
+
+    public Map<String, String> clientTags() {
+        return clientTags;
+    }
+
+    public Map<String, String> assignmentConfigs() {
+        return assignmentConfigs;
+    }
+
+    public String processId() {
+        return processId;
+    }
+
+    public AssignmentMemberSpec(final Optional<String> instanceId,
+                                final Optional<String> rackId,
+                                final Map<String, Set<Integer>> activeTasks,
+                                final Map<String, Set<Integer>> standbyTasks,
+                                final Map<String, Set<Integer>> warmupTasks,
+                                final String processId,
+                                final Map<String, String> clientTags,
+                                final Map<String, String> assignmentConfigs,
+                                final Map<TaskId, Long> taskOffsets) {
+        this.instanceId = Objects.requireNonNull(instanceId);
+        this.rackId = Objects.requireNonNull(rackId);
+        this.activeTasks = Collections.unmodifiableMap(Objects.requireNonNull(activeTasks));
+        this.standbyTasks = Collections.unmodifiableMap(Objects.requireNonNull(standbyTasks));
+        this.warmupTasks = Collections.unmodifiableMap(Objects.requireNonNull(warmupTasks));
+        this.processId = Objects.requireNonNull(processId);
+        this.clientTags = Collections.unmodifiableMap(Objects.requireNonNull(clientTags));
+        this.assignmentConfigs = Collections.unmodifiableMap(Objects.requireNonNull(assignmentConfigs));
+        this.taskOffsets = Collections.unmodifiableMap(Objects.requireNonNull(taskOffsets));
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final AssignmentMemberSpec that = (AssignmentMemberSpec) o;
+        return Objects.equals(instanceId, that.instanceId)
+            && Objects.equals(rackId, that.rackId)
+            && Objects.equals(activeTasks, that.activeTasks)
+            && Objects.equals(standbyTasks, that.standbyTasks)
+            && Objects.equals(warmupTasks, that.warmupTasks)
+            && Objects.equals(processId, that.processId)
+            && Objects.equals(clientTags, that.clientTags)
+            && Objects.equals(assignmentConfigs, that.assignmentConfigs)
+            && Objects.equals(taskOffsets, that.taskOffsets);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(
+            instanceId,
+            rackId,
+            activeTasks,
+            standbyTasks,
+            warmupTasks,
+            processId,
+            clientTags,
+            assignmentConfigs,
+            taskOffsets
+        );
+    }
+
+    @Override
+    public String toString() {
+        return "AssignmentMemberSpec{" +
+            "instanceId=" + instanceId +
+            ", rackId=" + rackId +
+            ", activeTasks=" + activeTasks +
+            ", standbyTasks=" + standbyTasks +
+            ", warmupTasks=" + warmupTasks +
+            ", processId='" + processId + '\'' +
+            ", clientTags=" + clientTags +
+            ", assignmentConfigs=" + assignmentConfigs +
+            ", taskOffsets=" + taskOffsets +
+            '}';
+    }
+
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupAssignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupAssignment.java
new file mode 100644
index 00000000000..313e1d72bf1
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupAssignment.java
@@ -0,0 +1,67 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * The task assignment for a streams group.
+ */
+public class GroupAssignment {
+
+    /**
+     * The member assignments keyed by member id.
+     */
+    private final Map<String, MemberAssignment> members;
+
+    public GroupAssignment(
+        Map<String, MemberAssignment> members
+    ) {
+        Objects.requireNonNull(members);
+        this.members = members;
+    }
+
+    /**
+     * @return Member assignments keyed by member Ids.
+     */
+    public Map<String, MemberAssignment> members() {
+        return members;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        GroupAssignment that = (GroupAssignment) o;
+        return members.equals(that.members);
+    }
+
+    @Override
+    public int hashCode() {
+        return members.hashCode();
+    }
+
+    @Override
+    public String toString() {
+        return "GroupAssignment(members=" + members + ')';
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java
new file mode 100644
index 00000000000..cb9c5f3e398
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpec.java
@@ -0,0 +1,37 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The group metadata specifications required to compute the target assignment.
+ */
+public interface GroupSpec {
+
+    /**
+     * @return Member metadata keyed by member Id.
+     */
+    Map<String, AssignmentMemberSpec> members();
+
+    /**
+     * @return The list of subtopologies.
+     */
+    List<String> subtopologies();
+
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java
new file mode 100644
index 00000000000..e08acaa468e
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImpl.java
@@ -0,0 +1,86 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * The assignment specification for a Streams group.
+ */
+public class GroupSpecImpl implements GroupSpec {
+
+    /**
+     * The member metadata keyed by member Id.
+     */
+    private final Map<String, AssignmentMemberSpec> members;
+
+    /**
+     * The subtopologies.
+     */
+    private final List<String> subtopologies;
+
+    public GroupSpecImpl(
+        Map<String, AssignmentMemberSpec> members,
+        List<String> subtopologies
+    ) {
+        Objects.requireNonNull(members);
+        Objects.requireNonNull(subtopologies);
+        this.members = members;
+        this.subtopologies = subtopologies;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public Map<String, AssignmentMemberSpec> members() {
+        return members;
+    }
+
+    @Override
+    public List<String> subtopologies() {
+        return subtopologies;
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final GroupSpecImpl groupSpec = (GroupSpecImpl) o;
+        return Objects.equals(members, groupSpec.members)
+            && Objects.equals(subtopologies, groupSpec.subtopologies);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(members, subtopologies);
+    }
+
+    @Override
+    public String toString() {
+        return "GroupSpecImpl{" +
+            "members=" + members +
+            ", partitionsPerSubtopology=" + subtopologies +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java
new file mode 100644
index 00000000000..42e5446b778
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MemberAssignment.java
@@ -0,0 +1,86 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * The task assignment for a Streams group member.
+ */
+public class MemberAssignment {
+
+    /**
+     * The target tasks assigned to this member keyed by subtopologyId.
+     */
+    private final Map<String, Set<Integer>> activeTasks;
+    private final Map<String, Set<Integer>> standbyTasks;
+    private final Map<String, Set<Integer>> warmupTasks;
+
+    public MemberAssignment(final Map<String, Set<Integer>> activeTasks,
+                            final Map<String, Set<Integer>> standbyTasks,
+                            final Map<String, Set<Integer>> warmupTasks) {
+        this.activeTasks = activeTasks;
+        this.standbyTasks = standbyTasks;
+        this.warmupTasks = warmupTasks;
+    }
+
+    public Map<String, Set<Integer>> activeTasks() {
+        return activeTasks;
+    }
+
+    public Map<String, Set<Integer>> standbyTasks() {
+        return standbyTasks;
+    }
+
+    public Map<String, Set<Integer>> warmupTasks() {
+        return warmupTasks;
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final MemberAssignment that = (MemberAssignment) o;
+        return Objects.equals(activeTasks, that.activeTasks)
+            && Objects.equals(standbyTasks, that.standbyTasks)
+            && Objects.equals(warmupTasks, that.warmupTasks);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(
+            activeTasks,
+            standbyTasks,
+            warmupTasks
+        );
+    }
+
+    @Override
+    public String toString() {
+        return "MemberAssignment{" +
+            "activeTasks=" + activeTasks +
+            ", standbyTasks=" + standbyTasks +
+            ", warmupTasks=" + warmupTasks +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java
new file mode 100644
index 00000000000..1a7502b9b52
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java
@@ -0,0 +1,115 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Mock implementation of {@link TaskAssignor} that assigns tasks to members in a round-robin fashion, with a bit of stickiness.
+ */
+public class MockAssignor implements TaskAssignor {
+
+    public static final String MOCK_ASSIGNOR_NAME = "mock";
+
+    @Override
+    public String name() {
+        return MOCK_ASSIGNOR_NAME;
+    }
+
+    @Override
+    public GroupAssignment assign(
+        final GroupSpec groupSpec,
+        final TopologyDescriber topologyDescriber
+    ) throws TaskAssignorException {
+
+        Map<String, MemberAssignment> newTargetAssignment = new HashMap<>();
+        Map<String, String[]> subtopologyToActiveMember = new HashMap<>();
+
+        for (String subtopology : groupSpec.subtopologies()) {
+            int numberOfPartitions = topologyDescriber.numPartitions(subtopology);
+            subtopologyToActiveMember.put(subtopology, new String[numberOfPartitions]);
+        }
+
+        // Copy existing assignment and fill temporary data structures
+        for (Map.Entry<String, AssignmentMemberSpec> memberEntry : groupSpec.members().entrySet()) {
+            final String memberId = memberEntry.getKey();
+            final AssignmentMemberSpec memberSpec = memberEntry.getValue();
+
+            Map<String, Set<Integer>> activeTasks = new HashMap<>(memberSpec.activeTasks());
+
+            newTargetAssignment.put(memberId, new MemberAssignment(activeTasks, new HashMap<>(), new HashMap<>()));
+            for (Map.Entry<String, Set<Integer>> entry : activeTasks.entrySet()) {
+                final String subtopologyId = entry.getKey();
+                final Set<Integer> taskIds = entry.getValue();
+                final String[] activeMembers = subtopologyToActiveMember.get(subtopologyId);
+                for (int taskId : taskIds) {
+                    if (activeMembers[taskId] != null) {
+                        throw new TaskAssignorException(
+                            "Task " + taskId + " of subtopology " + subtopologyId + " is assigned to multiple members.");
+                    }
+                    activeMembers[taskId] = memberId;
+                }
+            }
+        }
+
+        // Define priority queue to sort members by task count
+        PriorityQueue<MemberAndTaskCount> memberAndTaskCount = new PriorityQueue<>(Comparator.comparingInt(m -> m.taskCount));
+        memberAndTaskCount.addAll(
+            newTargetAssignment.keySet().stream()
+                .map(memberId -> new MemberAndTaskCount(memberId,
+                    newTargetAssignment.get(memberId).activeTasks().values().stream().mapToInt(Set::size).sum()))
+                .collect(Collectors.toSet())
+        );
+
+        // Assign unassigned tasks to members with fewest tasks
+        for (Map.Entry<String, String[]> entry : subtopologyToActiveMember.entrySet()) {
+            final String subtopologyId = entry.getKey();
+            final String[] activeMembers = entry.getValue();
+            for (int i = 0; i < activeMembers.length; i++) {
+                if (activeMembers[i] == null) {
+                    final MemberAndTaskCount m = memberAndTaskCount.poll();
+                    if (m == null) {
+                        throw new TaskAssignorException("No member available to assign task " + i + " of subtopology " + subtopologyId);
+                    }
+                    newTargetAssignment.get(m.memberId).activeTasks().computeIfAbsent(subtopologyId, k -> new HashSet<>()).add(i);
+                    activeMembers[i] = m.memberId;
+                    memberAndTaskCount.add(new MemberAndTaskCount(m.memberId, m.taskCount + 1));
+                }
+            }
+        }
+
+        return new GroupAssignment(newTargetAssignment);
+    }
+
+    private static class MemberAndTaskCount {
+
+        private final String memberId;
+        private final int taskCount;
+
+        MemberAndTaskCount(String memberId, int taskCount) {
+            this.memberId = memberId;
+            this.taskCount = taskCount;
+        }
+    }
+}
+
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignor.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignor.java
new file mode 100644
index 00000000000..c2c88b14236
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignor.java
@@ -0,0 +1,45 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.apache.kafka.common.annotation.InterfaceStability;
+
+/**
+ * Server side task assignor used by the GroupCoordinator.
+ * <p>
+ * The interface is kept in an internal module until KIP-848 is fully implemented and ready to be released.
+ */
+@InterfaceStability.Unstable
+public interface TaskAssignor {
+
+    /**
+     * Unique name for this assignor.
+     */
+    String name();
+
+    /**
+     * Assigns tasks to group members based on the given assignment specification and topic metadata.
+     *
+     * @param groupSpec         The assignment spec which includes member metadata.
+     * @param topologyDescriber The task metadata describer.
+     * @return The new assignment for the group.
+     */
+    GroupAssignment assign(
+        GroupSpec groupSpec,
+        TopologyDescriber topologyDescriber
+    ) throws TaskAssignorException;
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignorException.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignorException.java
new file mode 100644
index 00000000000..a3f7edd8a94
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskAssignorException.java
@@ -0,0 +1,33 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.apache.kafka.common.errors.ApiException;
+
+/**
+ * Exception thrown by {@link TaskAssignor#assign(GroupSpec, TopologyDescriber)}}. The exception is only used internally.
+ */
+public class TaskAssignorException extends ApiException {
+
+    public TaskAssignorException(String message) {
+        super(message);
+    }
+
+    public TaskAssignorException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
new file mode 100644
index 00000000000..3b828a60413
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TaskId.java
@@ -0,0 +1,66 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import java.util.Objects;
+
+public final class TaskId {
+
+    private final String subtopologyId;
+    private final int partition;
+
+    public TaskId(final String subtopologyId, final int partition) {
+        this.subtopologyId = subtopologyId;
+        this.partition = partition;
+    }
+
+    public String subtopologyId() {
+        return subtopologyId;
+    }
+
+    public int partition() {
+        return partition;
+    }
+
+    @Override
+    public boolean equals(final Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final TaskId taskId = (TaskId) o;
+        return partition == taskId.partition && Objects.equals(subtopologyId, taskId.subtopologyId);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(
+            subtopologyId,
+            partition
+        );
+    }
+
+    @Override
+    public String toString() {
+        return "TaskId{" +
+            "subtopologyId='" + subtopologyId + '\'' +
+            ", partition=" + partition +
+            '}';
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java
new file mode 100644
index 00000000000..f2a28e2cc10
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/TopologyDescriber.java
@@ -0,0 +1,37 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.apache.kafka.common.annotation.InterfaceStability;
+
+/**
+ * The subscribed topic describer is used by the {@link TaskAssignor} to obtain topic and task metadata of the subscribed topics.
+ * <p>
+ * The interface is kept in an internal module until KIP-848 is fully implemented and ready to be released.
+ */
+@InterfaceStability.Unstable
+public interface TopologyDescriber {
+
+    /**
+     * The number of partitions for the given subtopology.
+     *
+     * @param subtopologyId String corresponding to the subtopology.
+     * @return The number of tasks corresponding to the given subtopology ID, or -1 if the subtopology ID does not exist.
+     */
+    int numPartitions(String subtopologyId);
+
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
new file mode 100644
index 00000000000..b9c9a8e7aaa
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/GroupSpecImplTest.java
@@ -0,0 +1,72 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+
+public class GroupSpecImplTest {
+
+    private Map<String, AssignmentMemberSpec> members;
+    private List<String> subtopologies;
+    private GroupSpecImpl groupSpec;
+
+    @BeforeEach
+    void setUp() {
+        members = new HashMap<>();
+        subtopologies = new ArrayList<>();
+
+        members.put("test-member", new AssignmentMemberSpec(
+            Optional.of("test-instance"),
+            Optional.of("test-rack"),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        ));
+
+        subtopologies.add("test-subtopology");
+
+        groupSpec = new GroupSpecImpl(
+            members,
+            subtopologies
+        );
+    }
+
+    @Test
+    void testMembers() {
+        assertEquals(members, groupSpec.members());
+    }
+
+    @Test
+    void testSubtopologies() {
+        assertEquals(subtopologies, groupSpec.subtopologies());
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
new file mode 100644
index 00000000000..bc316db8772
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignorTest.java
@@ -0,0 +1,195 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.taskassignor;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.apache.kafka.common.utils.Utils.mkSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+
+public class MockAssignorTest {
+
+    private final MockAssignor assignor = new MockAssignor();
+
+
+    @Test
+    public void testBasicScenario() {
+
+        final GroupAssignment result = assignor.assign(
+            new GroupSpecImpl(
+                Collections.emptyMap(),
+                Collections.emptyList()
+            ),
+            x -> 5
+        );
+
+        assertEquals(0, result.members().size());
+    }
+
+
+    @Test
+    public void testSingleMember() {
+
+        final AssignmentMemberSpec memberSpec = new AssignmentMemberSpec(
+            Optional.empty(),
+            Optional.empty(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+
+        final GroupAssignment result = assignor.assign(
+            new GroupSpecImpl(
+                Collections.singletonMap("test_member", memberSpec),
+                Collections.singletonList("test-subtopology")
+            ),
+            x -> 4
+        );
+
+        assertEquals(1, result.members().size());
+        final MemberAssignment testMember = result.members().get("test_member");
+        assertNotNull(testMember);
+        assertEquals(mkMap(
+            mkEntry("test-subtopology", mkSet(0, 1, 2, 3))
+        ), testMember.activeTasks());
+    }
+
+
+    @Test
+    public void testTwoMembersTwoSubtopologies() {
+
+        final AssignmentMemberSpec memberSpec1 = new AssignmentMemberSpec(
+            Optional.empty(),
+            Optional.empty(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+
+        final AssignmentMemberSpec memberSpec2 = new AssignmentMemberSpec(
+            Optional.empty(),
+            Optional.empty(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+
+        final GroupAssignment result = assignor.assign(
+            new GroupSpecImpl(
+                mkMap(mkEntry("test_member1", memberSpec1), mkEntry("test_member2", memberSpec2)),
+                Arrays.asList("test-subtopology1", "test-subtopology2")
+            ),
+            x -> 4
+        );
+
+        final Map<String, Set<Integer>> expected1 = mkMap(
+            mkEntry("test-subtopology1", mkSet(1, 3)),
+            mkEntry("test-subtopology2", mkSet(1, 3))
+        );
+        final Map<String, Set<Integer>> expected2 = mkMap(
+            mkEntry("test-subtopology1", mkSet(0, 2)),
+            mkEntry("test-subtopology2", mkSet(0, 2))
+        );
+
+        assertEquals(2, result.members().size());
+        final MemberAssignment testMember1 = result.members().get("test_member1");
+        final MemberAssignment testMember2 = result.members().get("test_member2");
+        assertNotNull(testMember1);
+        assertNotNull(testMember2);
+        assertTrue(expected1.equals(testMember1.activeTasks()) || expected2.equals(testMember1.activeTasks()));
+        assertTrue(expected1.equals(testMember2.activeTasks()) || expected2.equals(testMember2.activeTasks()));
+    }
+
+    @Test
+    public void testTwoMembersTwoSubtopologiesStickiness() {
+
+        final AssignmentMemberSpec memberSpec1 = new AssignmentMemberSpec(
+            Optional.empty(),
+            Optional.empty(),
+            mkMap(
+                mkEntry("test-subtopology1", mkSet(0, 2, 3)),
+                mkEntry("test-subtopology2", mkSet(0))
+            ),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+
+        final AssignmentMemberSpec memberSpec2 = new AssignmentMemberSpec(
+            Optional.empty(),
+            Optional.empty(),
+            mkMap(
+                mkEntry("test-subtopology1", mkSet(1)),
+                mkEntry("test-subtopology2", mkSet(3))
+            ),
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            "test-process",
+            Collections.emptyMap(),
+            Collections.emptyMap(),
+            Collections.emptyMap()
+        );
+        final GroupAssignment result = assignor.assign(
+            new GroupSpecImpl(
+                mkMap(mkEntry("test_member1", memberSpec1), mkEntry("test_member2", memberSpec2)),
+                Arrays.asList("test-subtopology1", "test-subtopology2")
+            ),
+            x -> 4
+        );
+
+        assertEquals(2, result.members().size());
+        final MemberAssignment testMember1 = result.members().get("test_member1");
+        final MemberAssignment testMember2 = result.members().get("test_member2");
+        assertNotNull(testMember1);
+        assertNotNull(testMember2);
+        assertEquals(mkMap(
+            mkEntry("test-subtopology1", mkSet(0, 2, 3)),
+            mkEntry("test-subtopology2", mkSet(0))
+        ), testMember1.activeTasks());
+        assertEquals(mkMap(
+            mkEntry("test-subtopology1", mkSet(1)),
+            mkEntry("test-subtopology2", mkSet(1, 2, 3))
+        ), testMember2.activeTasks());
+    }
+
+}


(kafka) 03/42: Resolve merge conflict from 11/25 trunk rebase - Define RPCs to perform client-side assignment

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 7cd85abe2db709bec362e98ae40fe056006e7e25
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Thu May 16 22:58:44 2024 +0200

    Resolve merge conflict from 11/25 trunk rebase - Define RPCs to perform client-side assignment
    
    Even if we do not implement client-side assignment in the POC, let's define all public interfaces that will be part of the KIP in the branch, so that we have a single source of truth.
    
    Also updates the RPCs following discussions with responsive
    
     * Adds "userdata" for client-side assignment to the RPCs, as requested by Sophie.
     * Use task offsets instead of task lags
     * Allow the task offsets to be updated for 4 reasons
    
    See https://github.com/lucasbru/kafka/pull/8
---
 .../common/errors/StreamsInvalidAssignment.java    | 23 ++++++
 .../org/apache/kafka/common/protocol/ApiKeys.java  |  4 +-
 .../org/apache/kafka/common/protocol/Errors.java   |  1 +
 .../requests/StreamsInstallAssignmentRequest.java  | 63 ++++++++++++++
 .../requests/StreamsInstallAssignmentResponse.java | 62 ++++++++++++++
 .../requests/StreamsPrepareAssignmentRequest.java  | 63 ++++++++++++++
 .../requests/StreamsPrepareAssignmentResponse.java | 62 ++++++++++++++
 .../common/message/OffsetCommitRequest.json        |  2 +-
 .../common/message/OffsetFetchRequest.json         |  4 +-
 .../common/message/StreamsHeartbeatRequest.json    | 17 ++--
 .../message/StreamsInstallAssignmentRequest.json   | 39 +++++++++
 .../message/StreamsInstallAssignmentResponse.json  | 26 ++++++
 .../message/StreamsPrepareAssignmentRequest.json   | 16 ++++
 .../message/StreamsPrepareAssignmentResponse.json  | 96 ++++++++++++++++++++++
 14 files changed, 466 insertions(+), 12 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java
new file mode 100644
index 00000000000..dd6509f90f0
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidAssignment.java
@@ -0,0 +1,23 @@
+/*
+ * 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 org.apache.kafka.common.errors;
+
+public class StreamsInvalidAssignment extends ApiException {
+    public StreamsInvalidAssignment(String message) {
+        super(message);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
index fa9600d8536..7924677af3f 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/ApiKeys.java
@@ -132,7 +132,9 @@ public enum ApiKeys {
     DELETE_SHARE_GROUP_STATE(ApiMessageType.DELETE_SHARE_GROUP_STATE, true),
     READ_SHARE_GROUP_STATE_SUMMARY(ApiMessageType.READ_SHARE_GROUP_STATE_SUMMARY, true),
     STREAMS_HEARTBEAT(ApiMessageType.STREAMS_HEARTBEAT),
-    STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE);
+    STREAMS_INITIALIZE(ApiMessageType.STREAMS_INITIALIZE),
+    STREAMS_INSTALL_ASSIGNMENT(ApiMessageType.STREAMS_INSTALL_ASSIGNMENT),
+    STREAMS_PREPARE_ASSIGNMENT(ApiMessageType.STREAMS_PREPARE_ASSIGNMENT);
     
 
     private static final Map<ApiMessageType.ListenerType, EnumSet<ApiKeys>> APIS_BY_LISTENER =
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index 6246c4b4d14..9790d87863a 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -21,6 +21,7 @@ import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.BrokerIdNotRegisteredException;
 import org.apache.kafka.common.errors.BrokerNotAvailableException;
 import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
+import org.apache.kafka.common.errors.StreamsInvalidAssignment;
 import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
 import org.apache.kafka.common.errors.StreamsMissingInternalTopicsException;
 import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
new file mode 100644
index 00000000000..d793101c537
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentRequest.java
@@ -0,0 +1,63 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentRequestData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ApiMessage;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+
+public class StreamsInstallAssignmentRequest extends AbstractRequest  {
+
+    public static class Builder extends AbstractRequest.Builder<StreamsInstallAssignmentRequest> {
+        private final StreamsInstallAssignmentRequestData data;
+
+        public Builder(StreamsInstallAssignmentRequestData data) {
+            this(data, false);
+        }
+
+        public Builder(StreamsInstallAssignmentRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT, enableUnstableLastVersion);
+            this.data = data;
+        }
+
+        @Override
+        public StreamsInstallAssignmentRequest build(short version) {
+            return new StreamsInstallAssignmentRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final StreamsInstallAssignmentRequestData data;
+
+    public StreamsInstallAssignmentRequest(StreamsInstallAssignmentRequestData data, short version) {
+        super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT, version);
+        this.data = data;
+    }
+
+    @Override
+    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        return new StreamsInstallAssignmentResponse(
+            new StreamsInstallAssignmentResponseData()
+                .setThrottleTimeMs(throttleTimeMs)
+                .setErrorCode(Errors.forException(e).code())
+        );
+    }
+
+    @Override
+    public StreamsInstallAssignmentRequestData data() {
+        return data;
+    }
+
+    public static StreamsInstallAssignmentRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsInstallAssignmentRequest(new StreamsInstallAssignmentRequestData(
+            new ByteBufferAccessor(buffer), version), version);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
new file mode 100644
index 00000000000..3a09420f796
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsInstallAssignmentResponse.java
@@ -0,0 +1,62 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsInitializeResponseData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ApiMessage;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Possible error codes.
+ *
+ * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
+ * - {@link Errors#NOT_COORDINATOR}
+ * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
+ * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
+ * - {@link Errors#INVALID_REQUEST}
+ * - {@link Errors#INVALID_GROUP_ID}
+ * - {@link Errors#GROUP_ID_NOT_FOUND}
+ * - {@link Errors#UNKNOWN_MEMBER_ID}
+ * - {@link Errors#STALE_MEMBER_EPOCH}
+ * - {@link Errors#STREAMS_INVALID_ASSIGNMENT}
+ */
+public class StreamsInstallAssignmentResponse extends AbstractResponse {
+
+    private final StreamsInstallAssignmentResponseData data;
+
+    public StreamsInstallAssignmentResponse(StreamsInstallAssignmentResponseData data) {
+        super(ApiKeys.STREAMS_INSTALL_ASSIGNMENT);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsInstallAssignmentResponseData data() {
+        return data;
+    }
+
+    @Override
+    public Map<Errors, Integer> errorCounts() {
+        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
+    }
+
+    @Override
+    public int throttleTimeMs() {
+        return data.throttleTimeMs();
+    }
+
+    @Override
+    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
+        data.setThrottleTimeMs(throttleTimeMs);
+    }
+
+    public static StreamsInstallAssignmentResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsInstallAssignmentResponse(new StreamsInstallAssignmentResponseData(
+            new ByteBufferAccessor(buffer), version));
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
new file mode 100644
index 00000000000..3c83273bf4f
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentRequest.java
@@ -0,0 +1,63 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
+import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsPrepareAssignmentRequestData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ApiMessage;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+
+public class StreamsPrepareAssignmentRequest extends AbstractRequest  {
+
+    public static class Builder extends AbstractRequest.Builder<StreamsPrepareAssignmentRequest> {
+        private final StreamsPrepareAssignmentRequestData data;
+
+        public Builder(StreamsPrepareAssignmentRequestData data) {
+            this(data, false);
+        }
+
+        public Builder(StreamsPrepareAssignmentRequestData data, boolean enableUnstableLastVersion) {
+            super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT, enableUnstableLastVersion);
+            this.data = data;
+        }
+
+        @Override
+        public StreamsPrepareAssignmentRequest build(short version) {
+            return new StreamsPrepareAssignmentRequest(data, version);
+        }
+
+        @Override
+        public String toString() {
+            return data.toString();
+        }
+    }
+
+    private final StreamsPrepareAssignmentRequestData data;
+
+    public StreamsPrepareAssignmentRequest(StreamsPrepareAssignmentRequestData data, short version) {
+        super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT, version);
+        this.data = data;
+    }
+
+    @Override
+    public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
+        return new StreamsPrepareAssignmentResponse(
+            new StreamsPrepareAssignmentResponseData()
+                .setThrottleTimeMs(throttleTimeMs)
+                .setErrorCode(Errors.forException(e).code())
+        );
+    }
+
+    @Override
+    public StreamsPrepareAssignmentRequestData data() {
+        return data;
+    }
+
+    public static StreamsPrepareAssignmentRequest parse(ByteBuffer buffer, short version) {
+        return new StreamsPrepareAssignmentRequest(new StreamsPrepareAssignmentRequestData(
+            new ByteBufferAccessor(buffer), version), version);
+    }
+}
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
new file mode 100644
index 00000000000..99997022783
--- /dev/null
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsPrepareAssignmentResponse.java
@@ -0,0 +1,62 @@
+package org.apache.kafka.common.requests;
+
+import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsInstallAssignmentResponseData;
+import org.apache.kafka.common.message.StreamsPrepareAssignmentResponseData;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.protocol.ApiMessage;
+import org.apache.kafka.common.protocol.ByteBufferAccessor;
+import org.apache.kafka.common.protocol.Errors;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Possible error codes.
+ *
+ * - {@link Errors#GROUP_AUTHORIZATION_FAILED}
+ * - {@link Errors#NOT_COORDINATOR}
+ * - {@link Errors#COORDINATOR_NOT_AVAILABLE}
+ * - {@link Errors#COORDINATOR_LOAD_IN_PROGRESS}
+ * - {@link Errors#INVALID_REQUEST}
+ * - {@link Errors#INVALID_GROUP_ID}
+ * - {@link Errors#GROUP_ID_NOT_FOUND}
+ * - {@link Errors#UNKNOWN_MEMBER_ID}
+ * - {@link Errors#STALE_MEMBER_EPOCH}
+ */
+public class StreamsPrepareAssignmentResponse extends AbstractResponse {
+
+    private final StreamsPrepareAssignmentResponseData data;
+
+    public StreamsPrepareAssignmentResponse(StreamsPrepareAssignmentResponseData data) {
+        super(ApiKeys.STREAMS_PREPARE_ASSIGNMENT);
+        this.data = data;
+    }
+
+    @Override
+    public StreamsPrepareAssignmentResponseData data() {
+        return data;
+    }
+
+    @Override
+    public Map<Errors, Integer> errorCounts() {
+        return Collections.singletonMap(Errors.forCode(data.errorCode()), 1);
+    }
+
+    @Override
+    public int throttleTimeMs() {
+        return data.throttleTimeMs();
+    }
+
+    @Override
+    public void maybeSetThrottleTimeMs(int throttleTimeMs) {
+        data.setThrottleTimeMs(throttleTimeMs);
+    }
+
+    public static StreamsPrepareAssignmentResponse parse(ByteBuffer buffer, short version) {
+        return new StreamsPrepareAssignmentResponse(new StreamsPrepareAssignmentResponseData(
+            new ByteBufferAccessor(buffer), version));
+    }
+    
+}
diff --git a/clients/src/main/resources/common/message/OffsetCommitRequest.json b/clients/src/main/resources/common/message/OffsetCommitRequest.json
index 5b3029a5301..3cb15998420 100644
--- a/clients/src/main/resources/common/message/OffsetCommitRequest.json
+++ b/clients/src/main/resources/common/message/OffsetCommitRequest.json
@@ -41,7 +41,7 @@
     { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
       "about": "The unique group identifier." },
     { "name": "GenerationIdOrMemberEpoch", "type": "int32", "versions": "1+", "default": "-1", "ignorable": true,
-      "about": "The generation of the group if using the classic group protocol or the member epoch if using the consumer protocol." },
+      "about": "The generation of the group if using the classic group protocol or the member epoch if using the consumer or streams protocol." },
     { "name": "MemberId", "type": "string", "versions": "1+", "ignorable": true,
       "about": "The member ID assigned by the group coordinator." },
     { "name": "GroupInstanceId", "type": "string", "versions": "7+",
diff --git a/clients/src/main/resources/common/message/OffsetFetchRequest.json b/clients/src/main/resources/common/message/OffsetFetchRequest.json
index 82ac8065413..f154c8db448 100644
--- a/clients/src/main/resources/common/message/OffsetFetchRequest.json
+++ b/clients/src/main/resources/common/message/OffsetFetchRequest.json
@@ -54,9 +54,9 @@
       { "name": "GroupId", "type": "string", "versions": "8+", "entityType": "groupId",
         "about": "The group ID."},
       { "name": "MemberId", "type": "string", "versions": "9+", "nullableVersions": "9+", "default": "null", "ignorable": true,
-        "about": "The member id" },
+        "about": "The member ID assigned by the group coordinator if using the new consumer or streams protocol (KIP-848 / KIP-XXX)." },
       { "name": "MemberEpoch", "type": "int32", "versions": "9+", "default": "-1", "ignorable": true,
-        "about": "The member epoch if using the new consumer protocol (KIP-848)." },
+        "about": "The member epoch if using the new consumer or streams protocol (KIP-848 / KIP-XXX)." },
       { "name": "Topics", "type": "[]OffsetFetchRequestTopics", "versions": "8+", "nullableVersions": "8+",
         "about": "Each topic we would like to fetch offsets for, or null to fetch offsets for all topics.", "fields": [
         { "name": "Name", "type": "string", "versions": "8+", "entityType": "topicName",
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
index e21762e7e10..c97d0b912ff 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -60,20 +60,21 @@
     { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Used for rack-aware assignment algorithm. Null if unchanged since last heartbeat." },
 
-    { "name": "TaskLagUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
-      "about": "Reason for updating task lag. 0 if no update, 1 if task lag is updated due to warm up being ready, 2 if warm up failed" },
-    { "name": "TaskLag", "type": "[]TaskLag", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Cumulative lags for standby tasks. Only updatable when TaskLagUpdateReason is not zero. Null if unchanged since last heartbeat.",
+    { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
+      "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
+    { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
       "fields": [
         { "name": "TaskId", "type": "TaskId", "versions": "0+",
           "about": "The task ID" },
-        { "name": "Lag", "type": "int64", "versions": "0+",
-          "about": "The cumulative lag for the task" }
+        { "name": "Offset", "type": "int64", "versions": "0+",
+          "about": "The cumulative offset for the task" }
       ]
     },
+    { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
     { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
-      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat."
-    },
+      "about": "Generic array of assignment configuration strings. Null if unchanged since last heartbeat." },
     { "name": "ShutdownApplication", "type": "bool", "versions": "0+", "default": false,
       "about": "Whether all Streams clients in the group should shut down." }
   ],
diff --git a/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json b/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
new file mode 100644
index 00000000000..27d15cc66ec
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
@@ -0,0 +1,39 @@
+{
+  "apiKey": 78,
+  "type": "request",
+  "listeners": ["zkBroker", "broker"],
+  "name": "StreamsInstallAssignmentRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+      "about": "The group identifier." },
+    { "name": "MemberId", "type": "string", "versions": "0+",
+      "about": "The member id assigned by the group coordinator." },
+    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+      "about": "The member epoch." },
+    { "name": "GroupEpoch", "type": "int32", "versions": "0+",
+      "about": "The group epoch." },
+    { "name": "Error", "type": "int8", "versions": "0+",
+      "about": "The assignment error; or zero if the assignment is successful." },
+    { "name": "Members", "type": "[]Member", "versions": "0+",
+      "about": "The members.", "fields": [
+      { "name": "MemberId", "type": "string", "versions": "0+",
+        "about": "The member ID." },
+      { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Local assignment for this consumer." },
+      { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Local standby tasks for this consumer." },
+      { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Local warming up tasks for this consumer." }
+    ]}
+  ],
+  "commonStructs": [
+    { "name": "TaskId", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "subtopology ID" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]}
+  ]
+}
\ No newline at end of file
diff --git a/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json b/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json
new file mode 100644
index 00000000000..b1fe8e00644
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsInstallAssignmentResponse.json
@@ -0,0 +1,26 @@
+{
+  "apiKey": 78,
+  "type": "response",
+  "name": "StreamsInstallAssignmentResponse",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  // Supported errors:
+  // - GROUP_AUTHORIZATION_FAILED
+  // - NOT_COORDINATOR
+  // - COORDINATOR_NOT_AVAILABLE
+  // - COORDINATOR_LOAD_IN_PROGRESS
+  // - INVALID_REQUEST
+  // - INVALID_GROUP_ID
+  // - GROUP_ID_NOT_FOUND
+  // - UNKNOWN_MEMBER_ID
+  // - STALE_MEMBER_EPOCH
+  // - STREAMS_INVALID_ASSIGNMENT
+  "fields": [
+    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
+      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
+    { "name": "ErrorCode", "type": "int16", "versions": "0+",
+      "about": "The top-level error code, or 0 if there was no error" },
+    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The top-level error message, or null if there was no error." }
+  ]
+}
diff --git a/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json b/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json
new file mode 100644
index 00000000000..12b9098940c
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsPrepareAssignmentRequest.json
@@ -0,0 +1,16 @@
+{
+  "apiKey": 79,
+  "type": "request",
+  "listeners": ["zkBroker", "broker"],
+  "name": "StreamsPrepareAssignmentRequest",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  "fields": [
+    { "name": "GroupId", "type": "string", "versions": "0+", "entityType": "groupId",
+      "about": "The group identifier." },
+    { "name": "MemberId", "type": "string", "versions": "0+",
+      "about": "The member id assigned by the group coordinator." },
+    { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+      "about": "The member epoch." }
+  ]
+}
\ No newline at end of file
diff --git a/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json b/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
new file mode 100644
index 00000000000..c917931a568
--- /dev/null
+++ b/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
@@ -0,0 +1,96 @@
+{
+  "apiKey": 79,
+  "type": "response",
+  "name": "StreamsPrepareAssignmentResponse",
+  "validVersions": "0",
+  "flexibleVersions": "0+",
+  // Supported errors:
+  // - GROUP_AUTHORIZATION_FAILED
+  // - NOT_COORDINATOR
+  // - COORDINATOR_NOT_AVAILABLE
+  // - COORDINATOR_LOAD_IN_PROGRESS
+  // - INVALID_REQUEST
+  // - INVALID_GROUP_ID
+  // - GROUP_ID_NOT_FOUND
+  // - UNKNOWN_MEMBER_ID
+  // - STALE_MEMBER_EPOCH
+  "fields": [
+    { "name": "ThrottleTimeMs", "type": "int32", "versions": "0+",
+      "about": "The duration in milliseconds for which the request was throttled due to a quota violation, or zero if the request did not violate any quota." },
+    { "name": "ErrorCode", "type": "int16", "versions": "0+",
+      "about": "The top-level error code, or 0 if there was no error" },
+    { "name": "ErrorMessage", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+      "about": "The top-level error message, or null if there was no error." },
+    { "name": "GroupEpoch", "type": "int32", "versions": "0+",
+      "about": "The group epoch." },
+    { "name": "AssignorName", "type": "string", "versions": "0+",
+      "about": "The selected assignor." },
+    { "name": "Members", "type": "[]Member", "versions": "0+",
+      "about": "The members.", "fields": [
+      { "name": "MemberId", "type": "string", "versions": "0+",
+        "about": "The member ID." },
+      { "name": "MemberEpoch", "type": "int32", "versions": "0+",
+        "about": "The member epoch." },
+      { "name": "InstanceId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "The member instance ID." },
+      { "name": "RackId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "The rack ID." },
+
+      { "name": "TopologyHash", "type": "bytes", "versions": "0+",
+        "about": "The hash of the topology." },
+
+      { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Target active tasks for this consumer." },
+      { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Target standby tasks for this consumer." },
+      { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+",
+        "about": "Target warming up tasks for this consumer. " },
+
+      { "name": "ProcessId", "type": "uuid", "versions": "0+",
+        "about": "Identity of the streams instance that may have multiple consumers. " },
+      { "name": "ClientTags", "type": "[]KeyValue", "versions": "0+",
+        "about": "Used for rack-aware assignment algorithm." },
+      { "name": "TaskOffsetUpdateReason", "type":  "int8", "versions": "0+", "default": 0,
+        "about": "Reason for updating task offset. 0 if no update, 1 if task catches up with acceptable.recovery.lag, 2 if task falls behind acceptable.recovery.lag, 3 if a standby task is added or removed, 4 if triggerd by a time-interval" },
+      { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
+        "fields": [
+          { "name": "TaskId", "type": "TaskId", "versions": "0+",
+            "about": "The task ID" },
+          { "name": "Offset", "type": "int64", "versions": "0+",
+            "about": "The cumulative offset for the task" }
+        ]
+      },
+      { "name": "UserData", "type": "bytes", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "Opaque user data to be passed to the client-side assignor. Null if unchanged since last heartbeat." },
+      { "name": "AssignmentConfigs", "type": "[]KeyValue", "versions": "0+", "nullableVersions": "0+", "default": "null",
+        "about": "Generic array of assignment configuration strings."}
+    ]},
+    { "name": "Topics", "type": "[]TopicMetadata", "versions": "0+",
+      "about": "The topic-partition metadata.",
+      "fields": [
+        { "name": "TopicId", "type": "uuid", "versions": "0+",
+          "about": "The topic ID." },
+        { "name": "TopicName", "type": "string", "versions": "0+",
+          "about": "The topic name." },
+        { "name": "NumPartitions", "type": "int32", "versions": "0+",
+          "about": "The number of partitions." }
+      ]}
+  ],
+  "commonStructs": [
+    { "name": "TaskId", "versions": "0+", "fields": [
+      { "name": "Subtopology", "type": "string", "versions": "0+",
+        "about": "subtopology ID" },
+      { "name": "Partitions", "type": "[]int32", "versions": "0+",
+        "about": "partitions" }
+    ]},
+    { "name": "KeyValue", "versions": "0+",
+      "fields": [
+        { "name": "Key", "type": "string", "versions": "0+",
+          "about": "key of the config" },
+        { "name": "Value", "type": "string", "versions": "0+",
+          "about": "value of the config" }
+      ]
+    }
+  ]
+}
\ No newline at end of file


(kafka) 10/42: Add Assignment class in group coordinator for Streams

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 60f6773fa631a4c6e2700e858c06584f31b32511
Author: Bruno Cadonna <br...@confluent.io>
AuthorDate: Fri Jun 7 14:31:36 2024 +0200

    Add Assignment class in group coordinator for Streams
    
    See https://github.com/lucasbru/kafka/pull/17
---
 .../coordinator/group/streams/Assignment.java      | 124 +++++++++++++++
 .../coordinator/group/streams/MemberState.java     |  77 +++++++++
 .../kafka/coordinator/group/streams/TopicIds.java  | 176 +++++++++++++++++++++
 .../coordinator/group/streams/TopicMetadata.java   | 154 ++++++++++++++++++
 .../coordinator/group/AssignmentTestUtil.java      |  19 +++
 .../coordinator/group/streams/AssignmentTest.java  | 134 ++++++++++++++++
 6 files changed, 684 insertions(+)

diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
new file mode 100644
index 00000000000..735ee414785
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/Assignment.java
@@ -0,0 +1,124 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * An immutable assignment for a member.
+ */
+public class Assignment {
+    public static final Assignment EMPTY = new Assignment(
+        Collections.emptyMap(),
+        Collections.emptyMap(),
+        Collections.emptyMap()
+    );
+
+    private final Map<String, Set<Integer>> activeTasks;
+    private final Map<String, Set<Integer>> standbyTasks;
+    private final Map<String, Set<Integer>> warmupTasks;
+
+    public Assignment(final Map<String, Set<Integer>> activeTasks,
+                      final Map<String, Set<Integer>> standbyTasks,
+                      final Map<String, Set<Integer>> warmupTasks) {
+        this.activeTasks = Collections.unmodifiableMap(Objects.requireNonNull(activeTasks));
+        this.standbyTasks = Collections.unmodifiableMap(Objects.requireNonNull(standbyTasks));
+        this.warmupTasks = Collections.unmodifiableMap(Objects.requireNonNull(warmupTasks));
+    }
+
+    /**
+     * @return The assigned active tasks.
+     */
+    public Map<String, Set<Integer>> activeTasks() {
+        return activeTasks;
+    }
+
+    /**
+     * @return The assigned standby tasks.
+     */
+    public Map<String, Set<Integer>> standbyTasks() {
+        return standbyTasks;
+    }
+
+    /**
+     * @return The assigned warm-up tasks.
+     */
+    public Map<String, Set<Integer>> warmupTasks() {
+        return warmupTasks;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+        Assignment that = (Assignment) o;
+        return Objects.equals(activeTasks, that.activeTasks)
+            && Objects.equals(standbyTasks, that.standbyTasks)
+            && Objects.equals(warmupTasks, that.warmupTasks);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(activeTasks, standbyTasks, warmupTasks);
+    }
+
+    @Override
+    public String toString() {
+        return "Assignment(active tasks=" + activeTasks +
+            ", standby tasks=" + standbyTasks +
+            ", warm-up tasks=" + warmupTasks +')';
+    }
+
+    /**
+     * Creates a {{@link org.apache.kafka.coordinator.group.streams.Assignment}} from a
+     * {{@link org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue}}.
+     *
+     * @param record The record.
+     * @return A {{@link org.apache.kafka.coordinator.group.streams.Assignment}}.
+     */
+    public static Assignment fromRecord(
+        StreamsGroupTargetAssignmentMemberValue record
+    ) {
+        return new Assignment(
+            record.activeTasks().stream()
+                .collect(Collectors.toMap(
+                    StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                    taskId -> new HashSet<>(taskId.partitions())
+                    )
+                ),
+            record.standbyTasks().stream()
+                .collect(Collectors.toMap(
+                        StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                        taskId -> new HashSet<>(taskId.partitions())
+                    )
+                ),
+            record.warmupTasks().stream()
+                .collect(Collectors.toMap(
+                        StreamsGroupTargetAssignmentMemberValue.TaskId::subtopology,
+                        taskId -> new HashSet<>(taskId.partitions())
+                    )
+                )
+        );
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
new file mode 100644
index 00000000000..53518e61934
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/MemberState.java
@@ -0,0 +1,77 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The various states that a member can be in. For their definition,
+ * refer to the documentation of {{@link org.apache.kafka.coordinator.group.streams.CurrentAssignmentBuilder}}.
+ */
+public enum MemberState {
+
+    /**
+     * The member is fully reconciled with the desired target assignment.
+     */
+    STABLE((byte) 1),
+
+    /**
+     * The member must revoke some tasks in order to be able to
+     * transition to the next epoch.
+     */
+    UNREVOKED_TASKS((byte) 2),
+
+    /**
+     * The member transitioned to the last epoch but waits on some
+     * tasks which have not been revoked by their previous
+     * owners yet.
+     */
+    UNRELEASED_TASKS((byte) 3),
+
+    /**
+     * The member is in an unknown state. This can only happen if a future
+     * version of the software introduces a new state unknown by this version.
+     */
+    UNKNOWN((byte) 127);
+
+    private final static Map<Byte, MemberState> VALUES_TO_ENUMS = new HashMap<>();
+
+    static {
+        for (MemberState state: MemberState.values()) {
+            VALUES_TO_ENUMS.put(state.value(), state);
+        }
+    }
+
+    private final byte value;
+
+    MemberState(byte value) {
+        this.value = value;
+    }
+
+    public byte value() {
+        return value;
+    }
+
+    public static MemberState fromValue(byte value) {
+        MemberState state = VALUES_TO_ENUMS.get(value);
+        if (state == null) {
+            return UNKNOWN;
+        }
+        return state;
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java
new file mode 100644
index 00000000000..7beb9b9e4ff
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicIds.java
@@ -0,0 +1,176 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.image.TopicImage;
+import org.apache.kafka.image.TopicsImage;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * TopicIds is initialized with topic names (String) but exposes a Set of topic ids (Uuid) to the
+ * user and performs the conversion lazily with TopicsImage.
+ */
+public class TopicIds implements Set<Uuid> {
+    private final Set<String> topicNames;
+    private final TopicsImage image;
+
+    public TopicIds(
+        Set<String> topicNames,
+        TopicsImage image
+    ) {
+        this.topicNames = Objects.requireNonNull(topicNames);
+        this.image = Objects.requireNonNull(image);
+    }
+
+    @Override
+    public int size() {
+        return topicNames.size();
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return topicNames.isEmpty();
+    }
+
+    @Override
+    public boolean contains(Object o) {
+        if (o instanceof Uuid) {
+            Uuid topicId = (Uuid) o;
+            TopicImage topicImage = image.getTopic(topicId);
+            if (topicImage == null) return false;
+            return topicNames.contains(topicImage.name());
+        }
+        return false;
+    }
+
+    private static class TopicIdIterator implements Iterator<Uuid> {
+        final Iterator<String> iterator;
+        final TopicsImage image;
+        private Uuid next = null;
+
+        private TopicIdIterator(
+            Iterator<String> iterator,
+            TopicsImage image
+        ) {
+            this.iterator = Objects.requireNonNull(iterator);
+            this.image = Objects.requireNonNull(image);
+        }
+
+        @Override
+        public boolean hasNext() {
+            if (next != null) return true;
+            Uuid result = null;
+            do {
+                if (!iterator.hasNext()) {
+                    return false;
+                }
+                String next = iterator.next();
+                TopicImage topicImage = image.getTopic(next);
+                if (topicImage != null) {
+                    result = topicImage.id();
+                }
+            } while (result == null);
+            next = result;
+            return true;
+        }
+
+        @Override
+        public Uuid next() {
+            if (!hasNext()) throw new NoSuchElementException();
+            Uuid result = next;
+            next = null;
+            return result;
+        }
+    }
+
+    @Override
+    public Iterator<Uuid> iterator() {
+        return new TopicIdIterator(topicNames.iterator(), image);
+    }
+
+    @Override
+    public Object[] toArray() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public <T> T[] toArray(T[] a) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean add(Uuid o) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean remove(Object o) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean addAll(Collection c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void clear() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean removeAll(Collection c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean retainAll(Collection c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean containsAll(Collection c) {
+        for (Object o : c) {
+            if (!contains(o)) return false;
+        }
+        return true;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        TopicIds uuids = (TopicIds) o;
+
+        if (!Objects.equals(topicNames, uuids.topicNames)) return false;
+        return Objects.equals(image, uuids.image);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = topicNames.hashCode();
+        result = 31 * result + image.hashCode();
+        return result;
+    }
+}
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java
new file mode 100644
index 00000000000..b03afea1be1
--- /dev/null
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/TopicMetadata.java
@@ -0,0 +1,154 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupPartitionMetadataValue;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Immutable topic metadata.
+ */
+public class TopicMetadata {
+    /**
+     * The topic id.
+     */
+    private final Uuid id;
+
+    /**
+     * The topic name.
+     */
+    private final String name;
+
+    /**
+     * The number of partitions.
+     */
+    private final int numPartitions;
+
+    /**
+     * Map of every partition Id to a set of its rack Ids, if they exist.
+     * If rack information is unavailable for all partitions, this is an empty map.
+     */
+    private final Map<Integer, Set<String>> partitionRacks;
+
+    public TopicMetadata(
+        Uuid id,
+        String name,
+        int numPartitions,
+        Map<Integer, Set<String>> partitionRacks
+    ) {
+        this.id = Objects.requireNonNull(id);
+        if (Uuid.ZERO_UUID.equals(id)) {
+            throw new IllegalArgumentException("Topic id cannot be ZERO_UUID.");
+        }
+        this.name = Objects.requireNonNull(name);
+        if (name.isEmpty()) {
+            throw new IllegalArgumentException("Topic name cannot be empty.");
+        }
+        this.numPartitions = numPartitions;
+        if (numPartitions < 0) {
+            throw new IllegalArgumentException("Number of partitions cannot be negative.");
+        }
+        this.partitionRacks = Objects.requireNonNull(partitionRacks);
+    }
+
+    /**
+     * @return The topic id.
+     */
+    public Uuid id() {
+        return this.id;
+    }
+
+    /**
+     * @return The topic name.
+     */
+    public String name() {
+        return this.name;
+    }
+
+    /**
+     * @return The number of partitions.
+     */
+    public int numPartitions() {
+        return this.numPartitions;
+    }
+
+    /**
+     * @return Every partition mapped to the set of corresponding available rack Ids of its replicas.
+     *         An empty map is returned if rack information is unavailable for all partitions.
+     */
+    public Map<Integer, Set<String>> partitionRacks() {
+        return this.partitionRacks;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        TopicMetadata that = (TopicMetadata) o;
+
+        if (!id.equals(that.id)) return false;
+        if (!name.equals(that.name)) return false;
+        if (numPartitions != that.numPartitions) return false;
+        return partitionRacks.equals(that.partitionRacks);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = id.hashCode();
+        result = 31 * result + name.hashCode();
+        result = 31 * result + numPartitions;
+        result = 31 * result + partitionRacks.hashCode();
+        return result;
+    }
+
+    @Override
+    public String toString() {
+        return "TopicMetadata(" +
+            "id=" + id +
+            ", name=" + name +
+            ", numPartitions=" + numPartitions +
+            ", partitionRacks=" + partitionRacks +
+            ')';
+    }
+
+    public static TopicMetadata fromRecord(
+        StreamsGroupPartitionMetadataValue.TopicMetadata record
+    ) {
+        // Converting the data type from a list stored in the record to a map for the topic metadata.
+        Map<Integer, Set<String>> partitionRacks = new HashMap<>();
+        for (StreamsGroupPartitionMetadataValue.PartitionMetadata partitionMetadata : record.partitionMetadata()) {
+            partitionRacks.put(
+                partitionMetadata.partition(),
+                Collections.unmodifiableSet(new HashSet<>(partitionMetadata.racks()))
+            );
+        }
+
+        return new TopicMetadata(
+            record.topicId(),
+            record.topicName(),
+            record.numPartitions(),
+            partitionRacks);
+    }
+}
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
index 489d0d1fdd0..9759f41d727 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/AssignmentTestUtil.java
@@ -71,6 +71,25 @@ public class AssignmentTestUtil {
         return Collections.unmodifiableMap(assignment);
     }
 
+    @SafeVarargs
+    public static Map<String, Set<Integer>> mkStreamsAssignment(Map.Entry<String, Set<Integer>>... entries) {
+        Map<String, Set<Integer>> assignment = new HashMap<>();
+        for (Map.Entry<String, Set<Integer>> entry : entries) {
+            assignment.put(entry.getKey(), entry.getValue());
+        }
+        return assignment;
+    }
+
+    public static Map.Entry<String, Set<Integer>> mkTaskAssignment(
+        String subtopology,
+        Integer... partitions
+    ) {
+        return new AbstractMap.SimpleEntry<>(
+            subtopology,
+            new HashSet<>(Arrays.asList(partitions))
+        );
+    }
+
     /**
      * Verifies that the expected assignment is equal to the computed assignment for every member in the group.
      */
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
new file mode 100644
index 00000000000..baff38bceaf
--- /dev/null
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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 org.apache.kafka.coordinator.group.streams;
+
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkStreamsAssignment;
+import static org.apache.kafka.coordinator.group.AssignmentTestUtil.mkTaskAssignment;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class AssignmentTest {
+
+    @Test
+    public void testTasksCannotBeNull() {
+        assertThrows(NullPointerException.class, () -> new Assignment(null, Collections.emptyMap(), Collections.emptyMap()));
+        assertThrows(NullPointerException.class, () -> new Assignment(Collections.emptyMap(), null, Collections.emptyMap()));
+        assertThrows(NullPointerException.class, () -> new Assignment(Collections.emptyMap(), Collections.emptyMap(), null));
+    }
+
+    @Test
+    public void testAttributes() {
+        Map<String, Set<Integer>> activeTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology1", 1, 2, 3)
+        );
+        Map<String, Set<Integer>> standbyTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology2", 9, 8, 7)
+        );
+        Map<String, Set<Integer>> warmupTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology3", 4, 5, 6)
+        );
+        Assignment assignment = new Assignment(activeTasks, standbyTasks, warmupTasks);
+
+        assertEquals(activeTasks, assignment.activeTasks());
+        assertEquals(standbyTasks, assignment.standbyTasks());
+        assertEquals(warmupTasks, assignment.warmupTasks());
+    }
+
+    @Test
+    public void testFromTargetAssignmentRecord() {
+        String subtopology1 = "subtopology1";
+        String subtopology2 = "subtopology2";
+        List<StreamsGroupTargetAssignmentMemberValue.TaskId> activeTasks = new ArrayList<>();
+        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology1)
+            .setPartitions(Arrays.asList(1, 2, 3)));
+        activeTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology2)
+            .setPartitions(Arrays.asList(4, 5, 6)));
+        List<StreamsGroupTargetAssignmentMemberValue.TaskId> standbyTasks = new ArrayList<>();
+        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology1)
+            .setPartitions(Arrays.asList(7, 8, 9)));
+        standbyTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology2)
+            .setPartitions(Arrays.asList(1, 2, 3)));
+        List<StreamsGroupTargetAssignmentMemberValue.TaskId> warmupTasks = new ArrayList<>();
+        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology1)
+            .setPartitions(Arrays.asList(4, 5, 6)));
+        warmupTasks.add(new StreamsGroupTargetAssignmentMemberValue.TaskId()
+            .setSubtopology(subtopology2)
+            .setPartitions(Arrays.asList(7, 8, 9)));
+
+        StreamsGroupTargetAssignmentMemberValue record = new StreamsGroupTargetAssignmentMemberValue()
+            .setActiveTasks(activeTasks)
+            .setStandbyTasks(standbyTasks)
+            .setWarmupTasks(warmupTasks);
+
+        Assignment assignment = Assignment.fromRecord(record);
+
+        assertEquals(
+            mkStreamsAssignment(
+                mkTaskAssignment(subtopology1, 1, 2, 3),
+                mkTaskAssignment(subtopology2, 4, 5, 6)
+            ),
+            assignment.activeTasks()
+        );
+        assertEquals(
+            mkStreamsAssignment(
+                mkTaskAssignment(subtopology1, 7, 8, 9),
+                mkTaskAssignment(subtopology2, 1, 2, 3)
+            ),
+            assignment.standbyTasks()
+        );
+        assertEquals(
+            mkStreamsAssignment(
+                mkTaskAssignment(subtopology1, 4, 5, 6),
+                mkTaskAssignment(subtopology2, 7, 8, 9)
+            ),
+            assignment.warmupTasks()
+        );
+    }
+
+    @Test
+    public void testEquals() {
+        Map<String, Set<Integer>> activeTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology1", 1, 2, 3)
+        );
+        Map<String, Set<Integer>> standbyTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology2", 9, 8, 7)
+        );
+        Map<String, Set<Integer>> warmupTasks = mkStreamsAssignment(
+            mkTaskAssignment("subtopology3", 4, 5, 6)
+        );
+
+        assertEquals(
+            new Assignment(activeTasks, standbyTasks, warmupTasks),
+            new Assignment(activeTasks, standbyTasks, warmupTasks)
+        );
+    }
+}


(kafka) 31/42: MINOR: Fix unit tests (#17374)

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 0953df59d7b7c81842eb672dbb7918d554ca7266
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Mon Oct 7 13:36:14 2024 +0200

    MINOR: Fix unit tests (#17374)
    
    * MINOR: Fix unit tests
    
    Some unit tests were failing on the KIP1071 feature branch. This fixes
    them.
    
    * spotlessApply
---
 .../StreamsGroupHeartbeatRequestManager.java       |  1 +
 .../StreamsGroupInitializeRequestManager.java      |  1 +
 .../org/apache/kafka/common/protocol/Errors.java   | 10 +++++-----
 .../requests/StreamsGroupDescribeRequest.java      |  7 ++++---
 .../requests/StreamsGroupDescribeResponse.java     |  7 ++++---
 .../StreamsGroupHeartbeatRequestManagerTest.java   | 11 ++++++-----
 .../StreamsGroupInitializeRequestManagerTest.java  |  1 +
 .../scala/unit/kafka/server/RequestQuotaTest.scala |  9 +++++++++
 .../coordinator/group/GroupMetadataManager.java    |  4 ++--
 .../coordinator/group/streams/StreamsTopology.java |  4 ++--
 .../group/taskassignor/MockAssignor.java           |  1 -
 .../coordinator/group/streams/AssignmentTest.java  |  1 +
 .../CoordinatorStreamsRecordHelpersTest.java       |  1 +
 .../streams/CurrentAssignmentBuilderTest.java      |  1 +
 .../group/streams/StreamsGroupBuilder.java         |  3 ++-
 .../group/streams/StreamsGroupMemberTest.java      |  1 +
 .../group/streams/StreamsGroupTest.java            |  1 +
 .../group/streams/StreamsTopologyTest.java         | 22 ++++++++++++----------
 .../group/streams/TargetAssignmentBuilderTest.java |  1 +
 .../group/streams/TaskAssignmentTestUtil.java      |  2 +-
 .../SmokeTestDriverIntegrationTest.java            |  5 +++--
 .../org/apache/kafka/streams/StreamsConfig.java    |  2 +-
 .../internals/DefaultKafkaClientSupplier.java      |  2 +-
 .../streams/processor/internals/StreamThread.java  |  2 +-
 24 files changed, 62 insertions(+), 38 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
index 3a80765206d..7e31859571d 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManager.java
@@ -40,6 +40,7 @@ import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
 import org.apache.kafka.common.utils.Timer;
+
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
index 64565f347b1..b81beab78d9 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManager.java
@@ -23,6 +23,7 @@ import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
 import org.apache.kafka.common.requests.StreamsGroupInitializeResponse;
 import org.apache.kafka.common.utils.LogContext;
+
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
diff --git a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
index 00ed250ec73..db5194d4a2b 100644
--- a/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
+++ b/clients/src/main/java/org/apache/kafka/common/protocol/Errors.java
@@ -20,11 +20,6 @@ import org.apache.kafka.common.InvalidRecordException;
 import org.apache.kafka.common.errors.ApiException;
 import org.apache.kafka.common.errors.BrokerIdNotRegisteredException;
 import org.apache.kafka.common.errors.BrokerNotAvailableException;
-import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
-import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
-import org.apache.kafka.common.errors.StreamsGroupUninitializedException;
-import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
-import org.apache.kafka.common.errors.StreamsShutdownApplicationException;
 import org.apache.kafka.common.errors.ClusterAuthorizationException;
 import org.apache.kafka.common.errors.ConcurrentTransactionsException;
 import org.apache.kafka.common.errors.ControllerMovedException;
@@ -124,6 +119,11 @@ import org.apache.kafka.common.errors.ShareSessionNotFoundException;
 import org.apache.kafka.common.errors.SnapshotNotFoundException;
 import org.apache.kafka.common.errors.StaleBrokerEpochException;
 import org.apache.kafka.common.errors.StaleMemberEpochException;
+import org.apache.kafka.common.errors.StreamsGroupUninitializedException;
+import org.apache.kafka.common.errors.StreamsInconsistentTopologyException;
+import org.apache.kafka.common.errors.StreamsInvalidTopologyException;
+import org.apache.kafka.common.errors.StreamsMissingSourceTopicsException;
+import org.apache.kafka.common.errors.StreamsShutdownApplicationException;
 import org.apache.kafka.common.errors.TelemetryTooLargeException;
 import org.apache.kafka.common.errors.ThrottlingQuotaExceededException;
 import org.apache.kafka.common.errors.TimeoutException;
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java
index 2a3834d16a8..1f0c46fafe1 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeRequest.java
@@ -16,15 +16,16 @@
  */
 package org.apache.kafka.common.requests;
 
-import java.nio.ByteBuffer;
-import java.util.List;
-import java.util.stream.Collectors;
 import org.apache.kafka.common.message.StreamsGroupDescribeRequestData;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.stream.Collectors;
+
 public class StreamsGroupDescribeRequest extends AbstractRequest {
 
     public static class Builder extends AbstractRequest.Builder<StreamsGroupDescribeRequest> {
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java
index cf1d5529623..83db6700a4a 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/StreamsGroupDescribeResponse.java
@@ -16,14 +16,15 @@
  */
 package org.apache.kafka.common.requests;
 
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.Map;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
 
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Map;
+
 /**
  * Possible error codes.
  *
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
index a635d7d418e..f4e5d814a57 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupHeartbeatRequestManagerTest.java
@@ -29,6 +29,7 @@ import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatResponseData;
+import org.apache.kafka.common.metrics.Metrics;
 import org.apache.kafka.common.metrics.Sensor;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.Errors;
@@ -37,10 +38,10 @@ import org.apache.kafka.common.requests.RequestHeader;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
 import org.apache.kafka.common.requests.StreamsGroupHeartbeatResponse;
 import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
-import org.apache.kafka.common.metrics.Metrics;
-import org.apache.kafka.common.utils.LogContext;
+
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.mockito.ArgumentCaptor;
@@ -290,9 +291,9 @@ class StreamsGroupHeartbeatRequestManagerTest {
 
         mockResponse(data);
 
-        ArgumentCaptor<ConsumerGroupHeartbeatResponseData> captor = ArgumentCaptor.forClass(ConsumerGroupHeartbeatResponseData.class);
-        verify(membershipManager, times(1)).onHeartbeatSuccess(new ConsumerGroupHeartbeatResponse(captor.capture()));
-        ConsumerGroupHeartbeatResponseData response = captor.getValue();
+        ArgumentCaptor<ConsumerGroupHeartbeatResponse> captor = ArgumentCaptor.forClass(ConsumerGroupHeartbeatResponse.class);
+        verify(membershipManager, times(1)).onHeartbeatSuccess(captor.capture());
+        ConsumerGroupHeartbeatResponseData response = captor.getValue().data();
         assertEquals(Errors.NONE.code(), response.errorCode());
         assertEquals(TEST_MEMBER_ID, response.memberId());
         assertEquals(TEST_MEMBER_EPOCH, response.memberEpoch());
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
index ebba584b0db..11c92389f6a 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsGroupInitializeRequestManagerTest.java
@@ -21,6 +21,7 @@ import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.requests.StreamsGroupInitializeRequest;
 import org.apache.kafka.common.utils.LogContext;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.junit.jupiter.MockitoExtension;
diff --git a/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala b/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
index 4e481db1a21..154814e35c7 100644
--- a/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
+++ b/core/src/test/scala/unit/kafka/server/RequestQuotaTest.scala
@@ -739,6 +739,15 @@ class RequestQuotaTest extends BaseRequestTest {
         case ApiKeys.READ_SHARE_GROUP_STATE_SUMMARY =>
           new ReadShareGroupStateSummaryRequest.Builder(new ReadShareGroupStateSummaryRequestData(), true)
 
+        case ApiKeys.STREAMS_GROUP_DESCRIBE =>
+          new StreamsGroupDescribeRequest.Builder(new StreamsGroupDescribeRequestData(), true)
+
+        case ApiKeys.STREAMS_GROUP_HEARTBEAT =>
+          new StreamsGroupHeartbeatRequest.Builder(new StreamsGroupHeartbeatRequestData(), true)
+
+        case ApiKeys.STREAMS_GROUP_INITIALIZE =>
+          new StreamsGroupInitializeRequest.Builder(new StreamsGroupInitializeRequestData(), true)
+
         case _ =>
           throw new IllegalArgumentException("Unsupported API key " + apiKey)
     }
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
index 80785af9c76..a8f742f0d26 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java
@@ -141,8 +141,8 @@ import org.apache.kafka.coordinator.group.modern.share.ShareGroupAssignmentBuild
 import org.apache.kafka.coordinator.group.modern.share.ShareGroupMember;
 import org.apache.kafka.coordinator.group.streams.StreamsGroup;
 import org.apache.kafka.coordinator.group.streams.StreamsGroupMember;
-import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.coordinator.group.streams.StreamsTopology;
+import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.MetadataDelta;
 import org.apache.kafka.image.MetadataImage;
 import org.apache.kafka.image.TopicImage;
@@ -222,8 +222,8 @@ import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecor
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupMemberTombstoneRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupPartitionMetadataRecord;
-import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord;
 import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTargetAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.streams.CoordinatorStreamsRecordHelpers.newStreamsGroupTopologyRecord;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedActiveTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedStandbyTasksChanged;
 import static org.apache.kafka.coordinator.group.streams.StreamsGroupMember.hasAssignedWarmupTasksChanged;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
index 16b8f6d5178..27f138be05f 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsTopology.java
@@ -16,14 +16,14 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import java.util.HashMap;
-import java.util.List;
 import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
 import org.apache.kafka.common.message.StreamsGroupInitializeRequestData;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
 
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
diff --git a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java
index 1a7502b9b52..dbe9809632e 100644
--- a/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java
+++ b/group-coordinator/src/main/java/org/apache/kafka/coordinator/group/taskassignor/MockAssignor.java
@@ -112,4 +112,3 @@ public class MockAssignor implements TaskAssignor {
         }
     }
 }
-
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
index 65675136eb7..c3b3aebf42e 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/AssignmentTest.java
@@ -17,6 +17,7 @@
 package org.apache.kafka.coordinator.group.streams;
 
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTargetAssignmentMemberValue;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.ArrayList;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
index 839897d4dae..7ddbc832d80 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CoordinatorStreamsRecordHelpersTest.java
@@ -21,6 +21,7 @@ import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyKey;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
 import org.apache.kafka.server.common.ApiMessageAndVersion;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.Collections;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
index d6f83025c7f..533b7d6ab3a 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/CurrentAssignmentBuilderTest.java
@@ -20,6 +20,7 @@ import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.errors.FencedMemberEpochException;
 import org.apache.kafka.common.message.StreamsGroupHeartbeatRequestData;
 import org.apache.kafka.coordinator.group.streams.TaskAssignmentTestUtil.TaskRole;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.EnumSource;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
index e05365dbac8..b8b4ea8bcc1 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupBuilder.java
@@ -16,11 +16,12 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
 
 public class StreamsGroupBuilder {
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
index 00f6ef6c676..9e7e09ac8c6 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupMemberTest.java
@@ -22,6 +22,7 @@ import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAss
 import org.apache.kafka.coordinator.group.generated.StreamsGroupCurrentMemberAssignmentValue.TaskIds;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue;
 import org.apache.kafka.coordinator.group.generated.StreamsGroupMemberMetadataValue.KeyValue;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
index a7066ec7915..fbe9ca1821e 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsGroupTest.java
@@ -29,6 +29,7 @@ import org.apache.kafka.coordinator.group.OffsetExpirationCondition;
 import org.apache.kafka.coordinator.group.OffsetExpirationConditionImpl;
 import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetricsShard;
 import org.apache.kafka.timeline.SnapshotRegistry;
+
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
index 8cb9c9aa645..e83abcbfe7c 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/StreamsTopologyTest.java
@@ -16,11 +16,12 @@
  */
 package org.apache.kafka.coordinator.group.streams;
 
-import static org.apache.kafka.common.utils.Utils.mkEntry;
-import static org.apache.kafka.common.utils.Utils.mkMap;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertTrue;
+import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
+import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
+
+import org.junit.jupiter.api.Test;
 
 import java.util.Arrays;
 import java.util.Collections;
@@ -28,11 +29,12 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import org.apache.kafka.common.message.StreamsGroupDescribeResponseData;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.Subtopology;
-import org.apache.kafka.coordinator.group.generated.StreamsGroupTopologyValue.TopicInfo;
-import org.junit.jupiter.api.Test;
+
+import static org.apache.kafka.common.utils.Utils.mkEntry;
+import static org.apache.kafka.common.utils.Utils.mkMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 public class StreamsTopologyTest {
 
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
index e7b52deae42..e9324bcf696 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TargetAssignmentBuilderTest.java
@@ -26,6 +26,7 @@ import org.apache.kafka.coordinator.group.taskassignor.GroupSpecImpl;
 import org.apache.kafka.coordinator.group.taskassignor.MemberAssignment;
 import org.apache.kafka.coordinator.group.taskassignor.TaskAssignor;
 import org.apache.kafka.image.TopicsImage;
+
 import org.junit.jupiter.api.Test;
 
 import java.util.ArrayList;
diff --git a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
index 24a0b42eec8..c3980d0343f 100644
--- a/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
+++ b/group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TaskAssignmentTestUtil.java
@@ -23,8 +23,8 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Objects;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 
 public class TaskAssignmentTestUtil {
diff --git a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
index 78c23184f4f..ab8fb57d3fb 100644
--- a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
+++ b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java
@@ -16,9 +16,8 @@
  */
 package org.apache.kafka.streams.integration;
 
-import java.util.Locale;
-
 import kafka.api.IntegrationTestHarness;
+
 import org.apache.kafka.clients.consumer.ConsumerConfig;
 import org.apache.kafka.common.utils.Exit;
 import org.apache.kafka.streams.GroupProtocol;
@@ -26,6 +25,7 @@ import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.StreamsConfig.InternalConfig;
 import org.apache.kafka.streams.tests.SmokeTestClient;
 import org.apache.kafka.streams.tests.SmokeTestDriver;
+
 import org.junit.jupiter.api.Tag;
 import org.junit.jupiter.api.Timeout;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -33,6 +33,7 @@ import org.junit.jupiter.params.provider.CsvSource;
 
 import java.time.Duration;
 import java.util.ArrayList;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
diff --git a/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java b/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
index 6e171e022b5..476e582933e 100644
--- a/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
+++ b/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
@@ -16,7 +16,6 @@
  */
 package org.apache.kafka.streams;
 
-import java.util.Locale;
 import org.apache.kafka.clients.CommonClientConfigs;
 import org.apache.kafka.clients.MetadataRecoveryStrategy;
 import org.apache.kafka.clients.admin.Admin;
@@ -65,6 +64,7 @@ import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
index 1ec2053b3ec..e336aab5d03 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultKafkaClientSupplier.java
@@ -16,7 +16,6 @@
  */
 package org.apache.kafka.streams.processor.internals;
 
-import java.util.Optional;
 import org.apache.kafka.clients.admin.Admin;
 import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.consumer.ConsumerConfig;
@@ -30,6 +29,7 @@ import org.apache.kafka.common.serialization.ByteArraySerializer;
 import org.apache.kafka.streams.KafkaClientSupplier;
 
 import java.util.Map;
+import java.util.Optional;
 
 public class DefaultKafkaClientSupplier implements KafkaClientSupplier {
     @Override
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
index f26f9d55089..0b69a099663 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StreamThread.java
@@ -69,7 +69,6 @@ import org.apache.kafka.streams.processor.internals.tasks.DefaultTaskManager.Def
 import org.apache.kafka.streams.state.HostInfo;
 import org.apache.kafka.streams.state.internals.ThreadCache;
 
-import java.util.List;
 import org.slf4j.Logger;
 
 import java.time.Duration;
@@ -78,6 +77,7 @@ import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Queue;


(kafka) 11/42: Minor: Rename TaskId to TaskIds

Posted by ca...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cadonna pushed a commit to branch kip1071
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 41669d978ecb4ae58961f735df9c7a2b718ec8e6
Author: Lucas Brutschy <lb...@confluent.io>
AuthorDate: Fri Jun 7 11:55:06 2024 +0200

    Minor: Rename TaskId to TaskIds
    
    See https://github.com/lucasbru/kafka/pull/16
---
 .../internals/StreamsHeartbeatRequestManager.java      | 14 +++++++-------
 .../common/message/StreamsHeartbeatRequest.json        | 18 ++++++++++--------
 .../common/message/StreamsHeartbeatResponse.json       |  8 ++++----
 .../message/StreamsInstallAssignmentRequest.json       |  8 ++++----
 .../message/StreamsPrepareAssignmentResponse.json      | 14 ++++++++------
 .../internals/StreamsHeartbeatRequestManagerTest.java  |  6 +++---
 .../StreamsGroupCurrentMemberAssignmentValue.json      |  8 ++++----
 .../StreamsGroupTargetAssignmentMemberValue.json       |  8 ++++----
 8 files changed, 44 insertions(+), 40 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
index ffa6bb2657f..4f4d80104fd 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManager.java
@@ -29,7 +29,7 @@ import org.apache.kafka.common.errors.RetriableException;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
 import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData.TopicPartitions;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData;
-import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskId;
+import org.apache.kafka.common.message.StreamsHeartbeatRequestData.TaskIds;
 import org.apache.kafka.common.message.StreamsHeartbeatRequestData.HostInfo;
 import org.apache.kafka.common.message.StreamsHeartbeatResponseData;
 import org.apache.kafka.common.metrics.Metrics;
@@ -329,7 +329,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
     }
 
     private void updateTaskIdCollection(
-        final List<StreamsHeartbeatResponseData.TaskId> source,
+        final List<StreamsHeartbeatResponseData.TaskIds> source,
         final Set<StreamsAssignmentInterface.TaskId> target
     ) {
         target.clear();
@@ -605,7 +605,7 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
             return data;
         }
 
-        private List<TaskId> convertTaskIdCollection(final Set<StreamsAssignmentInterface.TaskId> tasks) {
+        private List<TaskIds> convertTaskIdCollection(final Set<StreamsAssignmentInterface.TaskId> tasks) {
             return tasks.stream()
                 .collect(
                     Collectors.groupingBy(StreamsAssignmentInterface.TaskId::subtopologyId,
@@ -614,10 +614,10 @@ public class StreamsHeartbeatRequestManager implements RequestManager {
                 .entrySet()
                 .stream()
                 .map(entry -> {
-                    TaskId id = new TaskId();
-                    id.setSubtopology(entry.getKey());
-                    id.setPartitions(entry.getValue());
-                    return id;
+                    TaskIds ids = new TaskIds();
+                    ids.setSubtopology(entry.getKey());
+                    ids.setPartitions(entry.getValue());
+                    return ids;
                 })
                 .collect(Collectors.toList());
         }
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
index cd8df8c477e..2ac6ce2e6e9 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatRequest.json
@@ -39,11 +39,11 @@
     { "name": "Assignor", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": null,
       "about": "The desired assignor. Picked by majority vote among clients. If null, the client votes for the broker to pick the assignor." },
 
-    { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
 
     { "name": "ProcessId", "type": "string", "versions": "0+", "nullableVersions": "0+", "default": "null",
@@ -65,8 +65,10 @@
     { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
       "fields": [
-        { "name": "TaskId", "type": "TaskId", "versions": "0+",
-          "about": "The task ID" },
+        { "name": "Subtopology", "type": "string", "versions": "0+",
+          "about": "A unique identifier of the subtopology." },
+        { "name": "Partition", "type": "int32", "versions": "0+",
+          "about": "The partition of the input topics." },
         { "name": "Offset", "type": "int64", "versions": "0+",
           "about": "The cumulative offset for the task" }
       ]
@@ -79,11 +81,11 @@
       "about": "Whether all Streams clients in the group should shut down." }
   ],
   "commonStructs": [
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
-        "about": "subtopology ID" },
+        "about": "A unique identifier of the subtopology." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
-        "about": "partitions" }
+        "about": "The partition of the input topics." }
     ]},
     { "name": "KeyValue", "versions": "0+",
       "fields": [
diff --git a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
index 513e1d78911..2a3e7f1ea80 100644
--- a/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
+++ b/clients/src/main/resources/common/message/StreamsHeartbeatResponse.json
@@ -62,11 +62,11 @@
       "about": "An error message relating to the current state of the assignment to this member." },
 
     // The streams app knows which partitions to fetch from given this information
-    { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local assignment for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local standby tasks for this consumer. Null if unchanged since last heartbeat." },
-    { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+", "nullableVersions": "0+", "default": "null",
+    { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+", "nullableVersions": "0+", "default": "null",
       "about": "Local warming up tasks for this consumer. Null if unchanged since last heartbeat." },
 
     // IQ-related information
@@ -89,7 +89,7 @@
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
         "about": "partitions" }
     ]},
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       // We are using strings here, to avoid fixing a structure on task IDs which will
       // allow introducing stable naming for subtopologies in the future.
       { "name": "Subtopology", "type": "string", "versions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json b/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
index 27d15cc66ec..847bb9bb215 100644
--- a/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
+++ b/clients/src/main/resources/common/message/StreamsInstallAssignmentRequest.json
@@ -20,16 +20,16 @@
       "about": "The members.", "fields": [
       { "name": "MemberId", "type": "string", "versions": "0+",
         "about": "The member ID." },
-      { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Local assignment for this consumer." },
-      { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Local standby tasks for this consumer." },
-      { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Local warming up tasks for this consumer." }
     ]}
   ],
   "commonStructs": [
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
         "about": "subtopology ID" },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
diff --git a/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json b/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
index c917931a568..1d9622caa9e 100644
--- a/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
+++ b/clients/src/main/resources/common/message/StreamsPrepareAssignmentResponse.json
@@ -39,11 +39,11 @@
       { "name": "TopologyHash", "type": "bytes", "versions": "0+",
         "about": "The hash of the topology." },
 
-      { "name": "ActiveTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "ActiveTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Target active tasks for this consumer." },
-      { "name": "StandbyTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "StandbyTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Target standby tasks for this consumer." },
-      { "name": "WarmupTasks", "type": "[]TaskId", "versions": "0+",
+      { "name": "WarmupTasks", "type": "[]TaskIds", "versions": "0+",
         "about": "Target warming up tasks for this consumer. " },
 
       { "name": "ProcessId", "type": "uuid", "versions": "0+",
@@ -55,8 +55,10 @@
       { "name": "TaskOffset", "type": "[]TaskOffset", "versions": "0+", "nullableVersions": "0+", "default": "null",
         "about": "Cumulative offsets for assigned and dormant standby tasks. Only updatable when TaskOffsetUpdateReason is not zero. Null if unchanged since last heartbeat.",
         "fields": [
-          { "name": "TaskId", "type": "TaskId", "versions": "0+",
-            "about": "The task ID" },
+          { "name": "Subtopology", "type": "string", "versions": "0+",
+            "about": "A unique identifier of the subtopology." },
+          { "name": "Partition", "type": "int32", "versions": "0+",
+            "about": "The partition of the input topics." },
           { "name": "Offset", "type": "int64", "versions": "0+",
             "about": "The cumulative offset for the task" }
         ]
@@ -78,7 +80,7 @@
       ]}
   ],
   "commonStructs": [
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
         "about": "subtopology ID" },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
index 17b99c9c72f..37e89bfdd69 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/StreamsHeartbeatRequestManagerTest.java
@@ -292,11 +292,11 @@ class StreamsHeartbeatRequestManagerTest {
             .setThrottleTimeMs(TEST_THROTTLE_TIME_MS)
             .setHeartbeatIntervalMs(1000)
             .setActiveTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskId().setSubtopology("0").setPartitions(Collections.singletonList(0))))
+                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("0").setPartitions(Collections.singletonList(0))))
             .setStandbyTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskId().setSubtopology("1").setPartitions(Collections.singletonList(1))))
+                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("1").setPartitions(Collections.singletonList(1))))
             .setWarmupTasks(Collections.singletonList(
-                new StreamsHeartbeatResponseData.TaskId().setSubtopology("2").setPartitions(Collections.singletonList(2))));
+                new StreamsHeartbeatResponseData.TaskIds().setSubtopology("2").setPartitions(Collections.singletonList(2))));
 
         mockResponse(data);
 
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
index d79e58cba75..0cbe1ba1e4e 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupCurrentMemberAssignmentValue.json
@@ -26,17 +26,17 @@
       "about": "If the last epoch bump is lost before reaching the member, the member will retry with the previous epoch." },
     { "name": "State", "versions": "0+", "type": "int8",
       "about": "The member state. See StreamsGroupMember.MemberState for the possible values." },
-    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned active tasks for this streams client." },
-    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned standby tasks for this streams client." },
-    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned warming up tasks for this streams client." },
     { "name": "ActiveTasksPendingRevocation", "versions": "0+", "type": "[]TaskId",
       "about": "The active tasks that must be revoked by this member." }
   ],
   "commonStructs": [
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",
diff --git a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
index 38526e4381c..06cb84ab18b 100644
--- a/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
+++ b/group-coordinator/src/main/resources/common/message/StreamsGroupTargetAssignmentMemberValue.json
@@ -20,15 +20,15 @@
   "validVersions": "0",
   "flexibleVersions": "0+",
   "fields": [
-    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "ActiveTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned active tasks for this streams client." },
-    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "StandbyTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned standby tasks for this streams client." },
-    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskId",
+    { "name": "WarmupTasks", "versions": "0+", "type": "[]TaskIds",
       "about": "Currently assigned warming up tasks for this streams client." }
   ],
   "commonStructs": [
-    { "name": "TaskId", "versions": "0+", "fields": [
+    { "name": "TaskIds", "versions": "0+", "fields": [
       { "name": "Subtopology", "type": "string", "versions": "0+",
         "about": "The subtopology identifier." },
       { "name": "Partitions", "type": "[]int32", "versions": "0+",