This is an automated email from the ASF dual-hosted git repository.
lucasbru pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/trunk by this push:
new 5a91e404fa8 KAFKA-20169: Support static membership for Kafka Streams
with the streams rebalance protocol at Client Side. (#22559)
5a91e404fa8 is described below
commit 5a91e404fa82f27d316c818f9a79e34dfcaf7039
Author: ChickenchickenLove <[email protected]>
AuthorDate: Thu Jun 25 04:14:24 2026 +0900
KAFKA-20169: Support static membership for Kafka Streams with the streams
rebalance protocol at Client Side. (#22559)
### Summary
This PR adds the remaining client-side support for static membership
when Kafka Streams uses the streams rebalance protocol
(`group.protocol=streams`) introduced by KIP-1071.
The change allows `group.instance.id` to be used with the streams
protocol, sends the proper static-member leave epoch when a static
Streams member closes with `DEFAULT` or `REMAIN_IN_GROUP`, and treats
`UNRELEASED_INSTANCE_ID` as a known fatal heartbeat error.
Some close-related changes that were part of my previous full PR
https://github.com/apache/kafka/pull/21603 are intentionally not
included here because they are already covered by
https://github.com/apache/kafka/pull/21579, which introduced
`CloseOptions.DEFAULT` for Kafka Streams.
### Changes
- Allow static membership configuration with `group.protocol=streams`.
- Handle `UNRELEASED_INSTANCE_ID` explicitly in
`StreamsGroupHeartbeatRequestManager`.
- Add coverage for static member close behavior:
- `DEFAULT` and `REMAIN_IN_GROUP` use
`LEAVE_GROUP_STATIC_MEMBER_EPOCH`.
- `LEAVE_GROUP` uses `LEAVE_GROUP_MEMBER_EPOCH`.
- `pollOnClose` sends the static leave epoch and instance id.
- Update Streams config tests to verify `group.instance.id` is allowed
for unprefixed, `consumer.`, and
`main.consumer.` configurations.
Reviewers: Lucas Brutschy <[email protected]>
---
.../StreamsGroupHeartbeatRequestManager.java | 8 +
.../StreamsGroupHeartbeatRequestManagerTest.java | 68 +++
.../internals/StreamsMembershipManagerTest.java | 139 +++--
docs/streams/developer-guide/config-streams.md | 2 +-
.../developer-guide/streams-rebalance-protocol.md | 4 +-
docs/streams/upgrade-guide.md | 4 +-
.../KafkaStreamsCloseOptionsIntegrationTest.java | 71 ++-
.../KafkaStreamsStaticMemberIntegrationTest.java | 596 +++++++++++++++++++++
.../org/apache/kafka/streams/StreamsConfig.java | 6 -
.../apache/kafka/streams/StreamsConfigTest.java | 33 +-
10 files changed, 863 insertions(+), 68 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 283625cf2fc..4793025f88c 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
@@ -651,10 +651,18 @@ public class StreamsGroupHeartbeatRequestManager
implements RequestManager {
case STREAMS_INVALID_TOPOLOGY:
case STREAMS_INVALID_TOPOLOGY_EPOCH:
case STREAMS_TOPOLOGY_FENCED:
+ case UNRELEASED_INSTANCE_ID:
logger.error("StreamsGroupHeartbeatRequest failed due to {}:
{}", error, errorMessage);
handleFatalFailure(error.exception(errorMessage));
break;
+ case FENCED_INSTANCE_ID:
+ logger.error("StreamsGroupHeartbeatRequest failed because
instance id {} is fenced: {}. " +
+ "Check for another Streams instance using the same
group instance id.",
+ membershipManager.groupInstanceId().get(), errorMessage);
+ handleFatalFailure(error.exception(errorMessage));
+ break;
+
case FENCED_MEMBER_EPOCH:
logInfo(
String.format("StreamsGroupHeartbeatRequest failed for
member %s because epoch %s is fenced.",
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 b8f17713351..9d92d251745 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
@@ -1331,6 +1331,7 @@ class StreamsGroupHeartbeatRequestManagerTest {
names = {
"INVALID_REQUEST",
"GROUP_MAX_SIZE_REACHED",
+ "UNRELEASED_INSTANCE_ID",
"UNSUPPORTED_VERSION",
"STREAMS_INVALID_TOPOLOGY",
"STREAMS_INVALID_TOPOLOGY_EPOCH",
@@ -1381,6 +1382,47 @@ class StreamsGroupHeartbeatRequestManagerTest {
}
}
+ @Test
+ public void testFencedInstanceIdErrorResponse() {
+ try (
+ final MockedConstruction<HeartbeatRequestState>
heartbeatRequestStateMockedConstruction = mockConstruction(
+ HeartbeatRequestState.class,
+ (mock, context) ->
when(mock.canSendRequest(time.milliseconds())).thenReturn(true));
+ final
MockedConstruction<StreamsGroupHeartbeatRequestManager.HeartbeatState>
heartbeatStateMockedConstruction =
+
mockConstruction(StreamsGroupHeartbeatRequestManager.HeartbeatState.class);
+ final LogCaptureAppender logAppender =
LogCaptureAppender.createAndRegister(StreamsGroupHeartbeatRequestManager.class)
+ ) {
+ final StreamsGroupHeartbeatRequestManager heartbeatRequestManager
= createStreamsGroupHeartbeatRequestManager();
+ final StreamsGroupHeartbeatRequestManager.HeartbeatState
heartbeatState =
+ heartbeatStateMockedConstruction.constructed().get(0);
+
when(coordinatorRequestManager.coordinator()).thenReturn(Optional.of(coordinatorNode));
+
when(membershipManager.groupInstanceId()).thenReturn(Optional.of(INSTANCE_ID));
+
+ final NetworkClientDelegate.PollResult result =
heartbeatRequestManager.poll(time.milliseconds());
+
+ assertEquals(1, result.unsentRequests.size());
+ final NetworkClientDelegate.UnsentRequest networkRequest =
result.unsentRequests.get(0);
+ final String errorMessage = "message";
+ final ClientResponse response =
buildClientErrorResponse(Errors.FENCED_INSTANCE_ID, errorMessage);
+
+ networkRequest.handler().onComplete(response);
+
+ assertTrue(logAppender.getMessages("ERROR").stream()
+ .anyMatch(m -> m.contains("StreamsGroupHeartbeatRequest failed
because instance id " +
+ INSTANCE_ID + " is fenced: " + errorMessage + ". Check for
another Streams instance using " +
+ "the same group instance id.")));
+ verify(heartbeatState).reset();
+
+ ArgumentCaptor<ErrorEvent> errorEvent =
ArgumentCaptor.forClass(ErrorEvent.class);
+ verify(backgroundEventHandler).add(errorEvent.capture());
+ assertEquals(errorMessage,
errorEvent.getValue().error().getMessage());
+ assertInstanceOf(Errors.FENCED_INSTANCE_ID.exception().getClass(),
errorEvent.getValue().error());
+
+ verify(membershipManager).transitionToFatal();
+ verify(membershipManager).onFatalHeartbeatFailure();
+ }
+ }
+
@ParameterizedTest
@EnumSource(
value = Errors.class,
@@ -1458,7 +1500,9 @@ class StreamsGroupHeartbeatRequestManagerTest {
Errors.INVALID_REQUEST,
Errors.GROUP_MAX_SIZE_REACHED,
Errors.FENCED_MEMBER_EPOCH,
+ Errors.FENCED_INSTANCE_ID,
Errors.UNKNOWN_MEMBER_ID,
+ Errors.UNRELEASED_INSTANCE_ID,
Errors.UNSUPPORTED_VERSION,
Errors.STREAMS_INVALID_TOPOLOGY,
Errors.STREAMS_INVALID_TOPOLOGY_EPOCH,
@@ -1495,6 +1539,30 @@ class StreamsGroupHeartbeatRequestManagerTest {
assertEquals(LEAVE_GROUP_MEMBER_EPOCH,
streamsRequest.data().memberEpoch());
}
+ @ParameterizedTest
+ @EnumSource(value = CloseOptions.GroupMembershipOperation.class, names =
{"DEFAULT", "REMAIN_IN_GROUP"})
+ public void testPollOnCloseWhenStaticMemberIsLeaving(final
CloseOptions.GroupMembershipOperation operation) {
+ final StreamsGroupHeartbeatRequestManager heartbeatRequestManager =
createStreamsGroupHeartbeatRequestManager();
+ when(membershipManager.isLeavingGroup()).thenReturn(true);
+ when(membershipManager.leaveGroupOperation()).thenReturn(operation);
+
when(membershipManager.groupInstanceId()).thenReturn(Optional.of(INSTANCE_ID));
+ when(membershipManager.groupId()).thenReturn(GROUP_ID);
+ when(membershipManager.memberId()).thenReturn(MEMBER_ID);
+
when(membershipManager.memberEpoch()).thenReturn(LEAVE_GROUP_STATIC_MEMBER_EPOCH);
+
+ NetworkClientDelegate.PollResult result =
heartbeatRequestManager.pollOnClose(time.milliseconds());
+
+ assertEquals(1, result.unsentRequests.size());
+ final NetworkClientDelegate.UnsentRequest networkRequest =
result.unsentRequests.get(0);
+ StreamsGroupHeartbeatRequest streamsRequest =
+ (StreamsGroupHeartbeatRequest)
networkRequest.requestBuilder().build();
+
+ assertEquals(GROUP_ID, streamsRequest.data().groupId());
+ assertEquals(MEMBER_ID, streamsRequest.data().memberId());
+ assertEquals(LEAVE_GROUP_STATIC_MEMBER_EPOCH,
streamsRequest.data().memberEpoch());
+ assertEquals(INSTANCE_ID, streamsRequest.data().instanceId());
+ }
+
@Test
public void testMaximumTimeToWaitPollTimerExpired() {
try (
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 5761eefd09e..79b21e470d2 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
@@ -40,6 +40,8 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
@@ -60,6 +62,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static
org.apache.kafka.clients.consumer.internals.ConsumerUtils.CONSUMER_METRIC_GROUP_PREFIX;
import static
org.apache.kafka.clients.consumer.internals.ConsumerUtils.COORDINATOR_METRICS_SUFFIX;
@@ -84,6 +87,7 @@ import static org.mockito.Mockito.when;
public class StreamsMembershipManagerTest {
private static final String GROUP_ID = "test-group";
+ private static final String INSTANCE_ID = "instance-1";
private static final int MEMBER_EPOCH = 1;
private static final String SUBTOPOLOGY_ID_0 = "subtopology-0";
@@ -1450,57 +1454,65 @@ public class StreamsMembershipManagerTest {
@Test
public void testLeaveGroupEpochIsStaticMemberEpochForStaticMember() {
- final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
- GROUP_ID,
- Optional.of("instance-1"),
- streamsRebalanceData, subscriptionState, backgroundEventHandler,
- new LogContext("test"), time, new Metrics(time)
- );
-
assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ try (final Metrics localMetrics = new Metrics(time)) {
+ final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
+ GROUP_ID,
+ Optional.of(INSTANCE_ID),
+ streamsRebalanceData, subscriptionState,
backgroundEventHandler,
+ new LogContext("test"), time, localMetrics
+ );
+
assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ }
}
@Test
public void
testLeaveGroupEpochIsDynamicMemberEpochForStaticMemberWithLeaveGroupOperation()
{
- final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
- GROUP_ID,
- Optional.of("instance-1"),
- streamsRebalanceData, subscriptionState, backgroundEventHandler,
- new LogContext("test"), time, new Metrics(time)
- );
- staticMember.registerStateListener(memberStateListener);
-
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.LEAVE_GROUP);
- assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ try (final Metrics localMetrics = new Metrics(time)) {
+ final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
+ GROUP_ID,
+ Optional.of(INSTANCE_ID),
+ streamsRebalanceData, subscriptionState,
backgroundEventHandler,
+ new LogContext("test"), time, localMetrics
+ );
+ staticMember.registerStateListener(memberStateListener);
+
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.LEAVE_GROUP);
+
assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ }
}
@Test
public void
testLeaveGroupEpochIsStaticMemberEpochForStaticMemberWithRemainInGroup() {
- final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
- GROUP_ID,
- Optional.of("instance-1"),
- streamsRebalanceData, subscriptionState, backgroundEventHandler,
- new LogContext("test"), time, new Metrics(time)
- );
- staticMember.registerStateListener(memberStateListener);
-
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP);
-
assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ try (final Metrics localMetrics = new Metrics(time)) {
+ final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
+ GROUP_ID,
+ Optional.of(INSTANCE_ID),
+ streamsRebalanceData, subscriptionState,
backgroundEventHandler,
+ new LogContext("test"), time, localMetrics
+ );
+ staticMember.registerStateListener(memberStateListener);
+
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP);
+
assertEquals(StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
staticMember.leaveGroupEpoch());
+ }
}
@Test
public void
testIsLeavingGroupReturnsTrueForStaticMemberWithRemainInGroupOperation() {
setupStreamsRebalanceDataWithOneSubtopologyOneSourceTopic(SUBTOPOLOGY_ID_0,
"topic");
- final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
- GROUP_ID,
- Optional.of("instance-1"),
- streamsRebalanceData, subscriptionState, backgroundEventHandler,
- new LogContext("test"), time, new Metrics(time)
- );
- staticMember.registerStateListener(memberStateListener);
- staticMember.onSubscriptionUpdated();
- staticMember.onConsumerPoll();
- assertEquals(MemberState.JOINING, staticMember.state());
-
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP);
- assertEquals(MemberState.LEAVING, staticMember.state());
- assertTrue(staticMember.isLeavingGroup());
+ try (final Metrics localMetrics = new Metrics(time)) {
+ final StreamsMembershipManager staticMember = new
StreamsMembershipManager(
+ GROUP_ID,
+ Optional.of(INSTANCE_ID),
+ streamsRebalanceData, subscriptionState,
backgroundEventHandler,
+ new LogContext("test"), time, localMetrics
+ );
+ staticMember.registerStateListener(memberStateListener);
+ staticMember.onSubscriptionUpdated();
+ staticMember.onConsumerPoll();
+ assertEquals(MemberState.JOINING, staticMember.state());
+
staticMember.leaveGroupOnClose(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP);
+ assertEquals(MemberState.LEAVING, staticMember.state());
+ assertTrue(staticMember.isLeavingGroup());
+ }
}
@Test
@@ -1542,6 +1554,51 @@ public class StreamsMembershipManagerTest {
verify(memberStateListener,
never()).onMemberEpochUpdated(Optional.of(MEMBER_EPOCH + 1),
membershipManager.memberId());
}
+ @ParameterizedTest
+ @MethodSource("staticMemberLeaveOnCloseOperations")
+ public void testStaticMemberUsesExpectedLeaveEpochOnClose(
+ final CloseOptions.GroupMembershipOperation operation,
+ final int expectedEpoch
+ ) {
+ try (final Metrics localMetrics = new Metrics(time)) {
+ StreamsMembershipManager membershipManagerWithStaticMember = new
StreamsMembershipManager(
+ GROUP_ID,
+ Optional.of(INSTANCE_ID),
+ streamsRebalanceData,
+ subscriptionState,
+ backgroundEventHandler,
+ new LogContext("test"),
+ time,
+ localMetrics
+ );
+
membershipManagerWithStaticMember.registerStateListener(memberStateListener);
+ joining(membershipManagerWithStaticMember);
+
+ CompletableFuture<Void> onGroupLeft =
membershipManagerWithStaticMember.leaveGroupOnClose(operation);
+
+ assertEquals(MemberState.LEAVING,
membershipManagerWithStaticMember.state());
+ assertEquals(expectedEpoch,
membershipManagerWithStaticMember.memberEpoch());
+ assertFalse(onGroupLeft.isDone());
+ }
+ }
+
+ private static Stream<Arguments> staticMemberLeaveOnCloseOperations() {
+ return Stream.of(
+ Arguments.of(
+ CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP,
+ StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH
+ ),
+ Arguments.of(
+ CloseOptions.GroupMembershipOperation.DEFAULT,
+ StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH
+ ),
+ Arguments.of(
+ CloseOptions.GroupMembershipOperation.LEAVE_GROUP,
+ StreamsGroupHeartbeatRequest.LEAVE_GROUP_MEMBER_EPOCH
+ )
+ );
+ }
+
@Test
public void testOnHeartbeatSuccessWhenInUnsubscribeLeaveNotInProgress() {
membershipManager.onHeartbeatSuccess(makeHeartbeatResponseWithActiveTasks(
@@ -2688,6 +2745,12 @@ public class StreamsMembershipManagerTest {
verifyInStateJoining(membershipManager);
}
+ private void joining(StreamsMembershipManager givenMembershipManager) {
+ givenMembershipManager.onSubscriptionUpdated();
+ givenMembershipManager.onConsumerPoll();
+ verifyInStateJoining(givenMembershipManager);
+ }
+
private void reconcile(final StreamsGroupHeartbeatResponse response) {
membershipManager.onHeartbeatSuccess(response);
membershipManager.poll(time.milliseconds());
diff --git a/docs/streams/developer-guide/config-streams.md
b/docs/streams/developer-guide/config-streams.md
index 961308fa3b5..51bacbc2066 100644
--- a/docs/streams/developer-guide/config-streams.md
+++ b/docs/streams/developer-guide/config-streams.md
@@ -1398,7 +1398,7 @@ Serde for the inner class of a windowed record. Must
implement the `Serde` inter
### group.protocol
-> The group protocol used by the Kafka Streams client used for coordination.
It determines how the client will communicate with the Kafka brokers and other
clients in the same group. The default value is `"classic"`, which is the
classic consumer group protocol. Can be set to `"streams"` (requires
broker-side enablement) to enable the new Kafka Streams group protocol.
+> The group protocol used by the Kafka Streams client used for coordination.
It determines how the client will communicate with the Kafka brokers and other
clients in the same group. The default value is `"classic"`, which is the
classic consumer group protocol. Can be set to `"streams"` (requires
broker-side enablement) to enable the new Kafka Streams group protocol. When
set to `"streams"`, `group.instance.id` can be used for static membership.
### rack.aware.assignment.non_overlap_cost
diff --git a/docs/streams/developer-guide/streams-rebalance-protocol.md
b/docs/streams/developer-guide/streams-rebalance-protocol.md
index 80dcb3b5e72..eb49f43dc5d 100644
--- a/docs/streams/developer-guide/streams-rebalance-protocol.md
+++ b/docs/streams/developer-guide/streams-rebalance-protocol.md
@@ -49,12 +49,12 @@ The following features are available in the current release:
* **Offline Migration**: After shutting down all members and waiting for their
`session.timeout.ms` to expire (or forcing an explicit group leave), a classic
group can be converted to a streams group and a streams group can be converted
to a classic group. The only broker-side group data that will be preserved are
the committed offsets. Internal topics (changelog and repartition topics) will
continue to exist as regular Kafka topics.
+* **Static Membership**: Streams applications can configure
`group.instance.id` when using `group.protocol=streams`. Kafka Streams derives
unique group instance IDs for its stream threads internally.
+
# What's Not Supported in This Version
The following features are not yet available and should be avoided when using
the new protocol:
-* **Static Membership**: Setting a client `instance.id` will be rejected.
-
* **Topology Updates**: If a topology is changed significantly (e.g., by
adding new source topics or changing the number of subtopologies), a new
streams group must be created.
* **High Availability Assignor**: Only the sticky assignor is supported. This
implies that "warmup tasks" and rack aware assignment are not supported yet.
diff --git a/docs/streams/upgrade-guide.md b/docs/streams/upgrade-guide.md
index 0951515f865..df78b93d72c 100644
--- a/docs/streams/upgrade-guide.md
+++ b/docs/streams/upgrade-guide.md
@@ -85,6 +85,8 @@ Kafka Streams now persists state store changelog offsets
inside each state store
As part of KIP-1035, the per-store changelog offset is written into RocksDB on
each commit and is made durable on disk only when RocksDB flushes its memtable
to an SST file — either organically once the memtable fills `write_buffer_size`
(16 MB by default), or on a clean store close. Earlier releases force-flushed
RocksDB on every commit. A consequence is that for a **low-traffic store**
whose memtable rarely fills, the on-disk offset can lag the store's actual
position until the next cl [...]
+Kafka Streams now supports static membership with the Streams Rebalance
Protocol. Applications using `group.protocol=streams` may configure
`group.instance.id`; Kafka Streams derives unique group instance IDs for its
stream threads internally.
+
### Header-aware state stores for the Processor API (KIP-1271)
{#kip-1271-headers-aware-stores}
Kafka Streams adds **header-aware** state stores. Opt in with the new `Stores`
suppliers whose names end with `WithHeaders` and the matching `StoreBuilder`
factories. For example:
@@ -185,7 +187,7 @@ This Early Access release covers a subset of the
functionality detailed in [KIP-
**What's Not Included in Early Access**
- * **Static Membership:** Setting a client `instance.id` will be rejected.
+ * **Static Membership:** Setting `group.instance.id` was rejected in the 4.1
Early Access release. Static membership is supported with the Streams Rebalance
Protocol starting in 4.3.0.
* **Topology Updates:** If a topology is changed significantly (e.g., by
adding new source topics or changing the number of sub-topologies), a new
streams group must be created.
* **High Availability Assignor:** Only the sticky assignor is supported.
* **Regular Expressions:** Pattern-based topic subscription is not supported.
diff --git
a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsCloseOptionsIntegrationTest.java
b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsCloseOptionsIntegrationTest.java
index 26aa359583c..a47d31af7f3 100644
---
a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsCloseOptionsIntegrationTest.java
+++
b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsCloseOptionsIntegrationTest.java
@@ -18,8 +18,10 @@ package org.apache.kafka.streams.integration;
import org.apache.kafka.clients.CommonClientConfigs;
import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.StreamsGroupDescription;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.LongSerializer;
import org.apache.kafka.common.serialization.Serdes;
@@ -49,6 +51,8 @@ import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
import java.io.File;
import java.io.IOException;
@@ -72,6 +76,7 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
protected static final String INPUT_TOPIC = "inputTopic";
protected static final String OUTPUT_TOPIC = "outputTopic";
+ protected static final String GROUP_INSTANCE_ID = "someGroupInstance";
protected Properties streamsConfig;
protected static KafkaStreams streams;
@@ -111,7 +116,7 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
streamsConfig = new Properties();
streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, appID);
- streamsConfig.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
"someGroupInstance");
+ streamsConfig.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
GROUP_INSTANCE_ID);
streamsConfig.put(StreamsConfig.STATE_DIR_CONFIG,
testFolder.getPath());
streamsConfig.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG,
Serdes.Long().getClass());
streamsConfig.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,
Serdes.String().getClass());
@@ -212,7 +217,7 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
streams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.LEAVE_GROUP)
.withTimeout(Duration.ofSeconds(30)));
- waitForEmptyStreamGroup(adminClient,
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG), 0);
+ waitForEmptyStreamGroup(adminClient,
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG),
TestUtils.DEFAULT_MAX_WAIT_MS);
}
@Test
@@ -227,7 +232,7 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
streams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.DEFAULT)
.withTimeout(Duration.ofSeconds(30)));
- waitForEmptyStreamGroup(adminClient,
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG), 0);
+ waitForEmptyStreamGroup(adminClient,
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG),
TestUtils.DEFAULT_MAX_WAIT_MS);
}
@Test
@@ -246,6 +251,44 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
"Group should still have a member after REMAIN_IN_GROUP close
under Streams protocol");
}
+ @ParameterizedTest
+ @EnumSource(value = CloseOptions.GroupMembershipOperation.class, names =
{"DEFAULT", "REMAIN_IN_GROUP"})
+ public void testStaticMemberCloseUsesStaticLeaveEpochStreamsProtocol(
+ final CloseOptions.GroupMembershipOperation operation
+ ) throws Exception {
+ final int numStreamThreads = 2;
+ streamsConfig.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG,
numStreamThreads);
+ streamsConfig.put(StreamsConfig.GROUP_PROTOCOL_CONFIG,
GroupProtocol.STREAMS.name());
+
+ streams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig);
+ IntegrationTestUtils.startApplicationAndWaitUntilRunning(streams);
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ streams.close(CloseOptions.groupMembershipOperation(operation)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ waitForStaticStreamsGroupMembersEpoch(
+ streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG),
+ GROUP_INSTANCE_ID,
+ StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH,
+ numStreamThreads
+ );
+ }
+
+ @Test
+ public void testStaticMemberLeaveGroupStreamsProtocol() throws Exception {
+ streamsConfig.put(StreamsConfig.GROUP_PROTOCOL_CONFIG,
GroupProtocol.STREAMS.name());
+
+ streams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig);
+ IntegrationTestUtils.startApplicationAndWaitUntilRunning(streams);
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+
streams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.LEAVE_GROUP)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ waitForEmptyStreamGroup(adminClient,
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG),
TestUtils.DEFAULT_MAX_WAIT_MS);
+ }
+
protected Topology setupTopologyWithoutIntermediateUserTopic() {
final StreamsBuilder builder = new StreamsBuilder();
@@ -272,4 +315,26 @@ public class KafkaStreamsCloseOptionsIntegrationTest {
IntegrationTestUtils.produceKeyValuesSynchronouslyWithTimestamp(INPUT_TOPIC,
Collections.singleton(record), producerConfig, mockTime.milliseconds());
}
}
+
+ private void waitForStaticStreamsGroupMembersEpoch(
+ final String applicationId,
+ final String baseInstanceId,
+ final int expectedEpoch,
+ final int expectedMemberCount
+ ) throws Exception {
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
+
adminClient.describeStreamsGroups(Collections.singletonList(applicationId))
+ .describedGroups()
+ .get(applicationId)
+ .get();
+
+ return groupDescription.members().size() == expectedMemberCount &&
+ groupDescription.members().stream().allMatch(member ->
+ member.instanceId()
+ .filter(instanceId ->
instanceId.startsWith(baseInstanceId + "-"))
+ .isPresent() &&
+ member.memberEpoch() == expectedEpoch);
+ }, "Static streams group members did not reach expected member epoch "
+ expectedEpoch);
+ }
}
diff --git
a/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsStaticMemberIntegrationTest.java
b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsStaticMemberIntegrationTest.java
new file mode 100644
index 00000000000..fb9bec552b7
--- /dev/null
+++
b/streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/KafkaStreamsStaticMemberIntegrationTest.java
@@ -0,0 +1,596 @@
+/*
+ * 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.integration;
+
+import org.apache.kafka.clients.CommonClientConfigs;
+import org.apache.kafka.clients.admin.Admin;
+import org.apache.kafka.clients.admin.StreamsGroupDescription;
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.common.requests.StreamsGroupHeartbeatRequest;
+import org.apache.kafka.common.serialization.LongDeserializer;
+import org.apache.kafka.common.serialization.LongSerializer;
+import org.apache.kafka.common.serialization.Serdes;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.Utils;
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig;
+import org.apache.kafka.streams.CloseOptions;
+import org.apache.kafka.streams.GroupProtocol;
+import org.apache.kafka.streams.KafkaStreams;
+import org.apache.kafka.streams.KeyValue;
+import org.apache.kafka.streams.StreamsBuilder;
+import org.apache.kafka.streams.StreamsConfig;
+import org.apache.kafka.streams.Topology;
+import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster;
+import org.apache.kafka.streams.integration.utils.IntegrationTestUtils;
+import org.apache.kafka.streams.kstream.KStream;
+import org.apache.kafka.streams.kstream.Produced;
+import org.apache.kafka.test.TestUtils;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestInfo;
+import org.junit.jupiter.api.Timeout;
+
+import java.io.File;
+import java.io.IOException;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.apache.kafka.streams.utils.TestUtils.safeUniqueTestName;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@Tag("integration")
+@Timeout(600)
+public class KafkaStreamsStaticMemberIntegrationTest {
+
+ private static MockTime mockTime;
+
+ protected static final String INPUT_TOPIC = "inputTopic";
+ protected static final String OUTPUT_TOPIC = "outputTopic";
+ protected static final String GROUP_INSTANCE_ID = "someGroupInstance";
+
+ protected Properties streamsConfig;
+ protected static KafkaStreams streams;
+ protected static Admin adminClient;
+ protected Properties commonClientConfig;
+ private Properties producerConfig;
+ protected Properties resultConsumerConfig;
+ private final File testFolder = TestUtils.tempDirectory();
+
+ public static final EmbeddedKafkaCluster CLUSTER;
+
+ static {
+ final Properties brokerProps = new Properties();
+
brokerProps.setProperty(GroupCoordinatorConfig.GROUP_MAX_SESSION_TIMEOUT_MS_CONFIG,
Integer.toString(Integer.MAX_VALUE));
+ CLUSTER = new EmbeddedKafkaCluster(1, brokerProps);
+ }
+
+ @BeforeAll
+ public static void startCluster() throws IOException {
+ CLUSTER.start();
+ }
+
+ @AfterAll
+ public static void closeCluster() {
+ Utils.closeQuietly(adminClient, "admin");
+ CLUSTER.stop();
+ }
+
+ @BeforeEach
+ public void before(final TestInfo testName) throws Exception {
+ mockTime = CLUSTER.time;
+
+ final String appID = safeUniqueTestName(testName);
+
+ commonClientConfig = new Properties();
+ commonClientConfig.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG,
CLUSTER.bootstrapServers());
+
+ streamsConfig = new Properties();
+ streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, appID);
+ streamsConfig.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
GROUP_INSTANCE_ID);
+ streamsConfig.put(StreamsConfig.STATE_DIR_CONFIG,
testFolder.getPath());
+ streamsConfig.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG,
Serdes.Long().getClass());
+ streamsConfig.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG,
Serdes.String().getClass());
+ streamsConfig.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
+ streamsConfig.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100L);
+ streamsConfig.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, 100);
+ streamsConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
+ // In this test, we set the SESSION_TIMEOUT_MS_CONFIG high in order to
show that the call to
+ // `close(CloseOptions)` can remove the application from the Consumer
Groups successfully.
+ streamsConfig.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG,
Integer.MAX_VALUE);
+ streamsConfig.putAll(commonClientConfig);
+
+ producerConfig = new Properties();
+ producerConfig.put(ProducerConfig.ACKS_CONFIG, "all");
+ producerConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
LongSerializer.class);
+ producerConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class);
+ producerConfig.putAll(commonClientConfig);
+
+ resultConsumerConfig = new Properties();
+ resultConsumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, appID +
"-result-consumer");
+ resultConsumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,
"earliest");
+ resultConsumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
LongDeserializer.class);
+
resultConsumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class);
+ resultConsumerConfig.putAll(commonClientConfig);
+
+ if (adminClient == null) {
+ adminClient = Admin.create(commonClientConfig);
+ }
+
+ CLUSTER.deleteAllTopics();
+ CLUSTER.createTopic(INPUT_TOPIC, 2, 1);
+ CLUSTER.createTopic(OUTPUT_TOPIC, 2, 1);
+
+ add10InputElements();
+ }
+
+ @AfterEach
+ public void after() throws Exception {
+ if (streams != null) {
+ streams.close(Duration.ofSeconds(30));
+ streams = null;
+ }
+ Utils.delete(testFolder);
+ }
+
+ @Test
+ public void
testStaticMemberJoinRegistersThreadScopedInstanceIdsStreamsProtocol() throws
Exception {
+ final int numStreamThreads = 2;
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+
+ streamsConfig.put(StreamsConfig.GROUP_PROTOCOL_CONFIG,
GroupProtocol.STREAMS.name());
+ streamsConfig.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG,
numStreamThreads);
+ streamsConfig.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
GROUP_INSTANCE_ID);
+
+ streams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(), streamsConfig);
+ IntegrationTestUtils.startApplicationAndWaitUntilRunning(streams);
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == numStreamThreads &&
+ groupDescription.members().stream().allMatch(member ->
+ member.instanceId()
+ .filter(instanceId ->
instanceId.startsWith(GROUP_INSTANCE_ID + "-"))
+ .isPresent() &&
+ member.memberEpoch() >= 0);
+ }, "Static streams members did not join with thread-scoped instance
ids");
+ }
+
+ @Test
+ public void
testStaticMemberCloseWithLeaveGroupTriggersRebalanceStreamsProtocol() throws
Exception {
+ final File firstStateDir = TestUtils.tempDirectory();
+ final File secondStateDir = TestUtils.tempDirectory();
+ final String firstInstanceId = "instance-1";
+ final String secondInstanceId = "instance-2";
+
+ final AtomicInteger secondStreamsRebalances = new AtomicInteger(0);
+
+ try (final KafkaStreams streams1 = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(),
staticStreamsConfig(firstInstanceId, firstStateDir));
+ final KafkaStreams streams2 = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(),
staticStreamsConfig(secondInstanceId, secondStateDir))) {
+ streams2.setStateListener((newState, oldState) -> {
+ if (newState == KafkaStreams.State.REBALANCING) {
+ secondStreamsRebalances.incrementAndGet();
+ }
+ });
+
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(Arrays.asList(streams1,
streams2));
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
+
adminClient.describeStreamsGroups(Collections.singletonList(applicationId))
+ .describedGroups()
+ .get(applicationId)
+ .get();
+
+ return groupDescription.members().size() == 2;
+ }, "Streams group did not reach 2 static members");
+
+ final int initialStreams2Rebalances =
secondStreamsRebalances.get();
+
+
streams1.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.LEAVE_GROUP)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
+
adminClient.describeStreamsGroups(Collections.singletonList(applicationId))
+ .describedGroups()
+ .get(applicationId)
+ .get();
+
+ return groupDescription.members().size() == 1 &&
+ groupDescription.members().stream().allMatch(member ->
+ member.instanceId()
+ .filter(instanceId ->
instanceId.startsWith("instance-2-"))
+ .isPresent());
+ }, "Streams group did not retain only the remaining static member
after LEAVE_GROUP close");
+
+ TestUtils.waitForCondition(
+ () -> secondStreamsRebalances.get() >
initialStreams2Rebalances,
+ "Remaining streams instance did not observe a rebalance after
static member left the group"
+ );
+ } finally {
+ Utils.delete(firstStateDir);
+ Utils.delete(secondStateDir);
+ }
+ }
+
+ @Test
+ public void testStaticMemberCanRejoinAfterRemainInGroupStreamsProtocol()
throws Exception {
+ final File firstStateDir = TestUtils.tempDirectory();
+ final File secondStateDir = TestUtils.tempDirectory();
+ final File restartedStateDir = TestUtils.tempDirectory();
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+ final String firstInstanceId = "instance-1";
+ final String secondInstanceId = "instance-2";
+
+ try {
+ try (final KafkaStreams firstStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(firstInstanceId, firstStateDir)
+ );
+ final KafkaStreams secondStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(secondInstanceId, secondStateDir)
+ )) {
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(Arrays.asList(firstStreams,
secondStreams));
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Streams group did not reach 2 active static members");
+
+ final StreamsGroupDescription initialGroupDescription =
describeStreamsGroup(applicationId);
+ final String firstMemberId =
staticStreamsMemberId(initialGroupDescription, firstInstanceId).orElseThrow();
+
+
firstStreams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasStaticStreamsMemberWithMemberIdAndEpoch(
+ groupDescription,
+ firstInstanceId,
+ firstMemberId,
+
StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH
+ ) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member did not remain in group with static
leave epoch");
+
+ try (final KafkaStreams restartedStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(firstInstanceId, restartedStateDir)
+ )) {
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(restartedStreams);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ final Optional<String> rejoinedMemberId =
staticStreamsMemberId(groupDescription, firstInstanceId);
+
+ return groupDescription.members().size() == 2 &&
+ rejoinedMemberId.isPresent() &&
+ !rejoinedMemberId.get().equals(firstMemberId) &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member did not rejoin with a new member
id after REMAIN_IN_GROUP close");
+ }
+ }
+ } finally {
+ Utils.delete(firstStateDir);
+ Utils.delete(secondStateDir);
+ Utils.delete(restartedStateDir);
+ }
+ }
+
+ @Test
+ public void testStaticMemberCanRejoinAfterLeaveGroupStreamsProtocol()
throws Exception {
+ final File firstStateDir = TestUtils.tempDirectory();
+ final File secondStateDir = TestUtils.tempDirectory();
+ final File restartedStateDir = TestUtils.tempDirectory();
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+ final String firstInstanceId = "instance-1";
+ final String secondInstanceId = "instance-2";
+
+ try {
+ try (final KafkaStreams firstStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(firstInstanceId, firstStateDir)
+ );
+ final KafkaStreams secondStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(secondInstanceId, secondStateDir)
+ )) {
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(Arrays.asList(firstStreams,
secondStreams));
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Streams group did not reach 2 active static members");
+
+
firstStreams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.LEAVE_GROUP)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 1 &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member did not leave the group with
LEAVE_GROUP");
+
+ try (final KafkaStreams restartedStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(firstInstanceId, restartedStateDir)
+ )) {
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(restartedStreams);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member did not rejoin after LEAVE_GROUP
close");
+ }
+ }
+ } finally {
+ Utils.delete(firstStateDir);
+ Utils.delete(secondStateDir);
+ Utils.delete(restartedStateDir);
+ }
+ }
+
+ @Test
+ public void
testStaticMemberRemainingInGroupExpiresAndTriggersRebalanceStreamsProtocol()
throws Exception {
+ final int sessionTimeoutMs = 1000;
+ final int heartbeatIntervalMs = 100;
+ final File firstStateDir = TestUtils.tempDirectory();
+ final File secondStateDir = TestUtils.tempDirectory();
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+ final String firstInstanceId = "instance-1";
+ final String secondInstanceId = "instance-2";
+
+ CLUSTER.setGroupHeartbeatTimeout(applicationId, heartbeatIntervalMs);
+ CLUSTER.setGroupSessionTimeout(applicationId, sessionTimeoutMs);
+
+ try {
+ try (final KafkaStreams firstStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(firstInstanceId, firstStateDir)
+ );
+ final KafkaStreams secondStreams = new KafkaStreams(
+ setupTopologyWithoutIntermediateUserTopic(),
+ staticStreamsConfig(secondInstanceId, secondStateDir)
+ )) {
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(Arrays.asList(firstStreams,
secondStreams));
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Streams group did not reach 2 active static members");
+
+ final StreamsGroupDescription initialGroupDescription =
describeStreamsGroup(applicationId);
+ final String firstMemberId =
staticStreamsMemberId(initialGroupDescription, firstInstanceId).orElseThrow();
+
+
firstStreams.close(CloseOptions.groupMembershipOperation(CloseOptions.GroupMembershipOperation.REMAIN_IN_GROUP)
+ .withTimeout(Duration.ofSeconds(30)));
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasStaticStreamsMemberWithMemberIdAndEpoch(
+ groupDescription,
+ firstInstanceId,
+ firstMemberId,
+
StreamsGroupHeartbeatRequest.LEAVE_GROUP_STATIC_MEMBER_EPOCH
+ ) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member did not remain in group with static
leave epoch");
+
+ final int groupEpochAfterStaticLeave =
describeStreamsGroup(applicationId).groupEpoch();
+
+ TestUtils.waitForCondition(() -> {
+ mockTime.sleep(heartbeatIntervalMs);
+
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 1 &&
+ groupDescription.groupEpoch() >
groupEpochAfterStaticLeave &&
+ staticStreamsMemberId(groupDescription,
firstInstanceId).isEmpty() &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Static streams member was not removed after session
timeout");
+ }
+ } finally {
+ Utils.delete(firstStateDir);
+ Utils.delete(secondStateDir);
+ }
+ }
+
+ @Test
+ public void
testDuplicateStaticInstanceIdDoesNotReplaceExistingStreamsMember() throws
Exception {
+ final File firstStateDir = TestUtils.tempDirectory();
+ final File secondStateDir = TestUtils.tempDirectory();
+ final File conflictStateDir = TestUtils.tempDirectory();
+ final String applicationId =
streamsConfig.getProperty(StreamsConfig.APPLICATION_ID_CONFIG);
+ final String firstInstanceId = "instance-1";
+ final String secondInstanceId = "instance-2";
+ final AtomicInteger firstStreamsRebalances = new AtomicInteger(0);
+ final AtomicInteger secondStreamsRebalances = new AtomicInteger(0);
+
+ try {
+ try (final KafkaStreams firstStreams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(),
staticStreamsConfig(firstInstanceId, firstStateDir));
+ final KafkaStreams secondStreams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(),
staticStreamsConfig(secondInstanceId, secondStateDir));
+ final KafkaStreams conflictStreams = new
KafkaStreams(setupTopologyWithoutIntermediateUserTopic(),
staticStreamsConfig(firstInstanceId, conflictStateDir))) {
+ firstStreams.setStateListener((newState, oldState) -> {
+ if (newState == KafkaStreams.State.REBALANCING) {
+ firstStreamsRebalances.incrementAndGet();
+ }
+ });
+ secondStreams.setStateListener((newState, oldState) -> {
+ if (newState == KafkaStreams.State.REBALANCING) {
+ secondStreamsRebalances.incrementAndGet();
+ }
+ });
+
+
IntegrationTestUtils.startApplicationAndWaitUntilRunning(Arrays.asList(firstStreams,
secondStreams));
+
IntegrationTestUtils.waitUntilMinKeyValueRecordsReceived(resultConsumerConfig,
OUTPUT_TOPIC, 10);
+
+ TestUtils.waitForCondition(() -> {
+ final StreamsGroupDescription groupDescription =
describeStreamsGroup(applicationId);
+ return groupDescription.members().size() == 2 &&
+ hasActiveStaticStreamsMember(groupDescription,
firstInstanceId) &&
+ hasActiveStaticStreamsMember(groupDescription,
secondInstanceId);
+ }, "Streams group did not reach 2 active static members");
+
+ final StreamsGroupDescription initialGroupDescription =
describeStreamsGroup(applicationId);
+ final String firstMemberId =
staticStreamsMemberId(initialGroupDescription, firstInstanceId).orElseThrow();
+ final String secondMemberId =
staticStreamsMemberId(initialGroupDescription, secondInstanceId).orElseThrow();
+ final int initialGroupEpoch =
initialGroupDescription.groupEpoch();
+ final int firstRebalancesBeforeConflict =
firstStreamsRebalances.get();
+ final int secondRebalancesBeforeConflict =
secondStreamsRebalances.get();
+
+ conflictStreams.start();
+
+ TestUtils.waitForCondition(
+ () -> conflictStreams.state() == KafkaStreams.State.ERROR,
+ "Conflicting static streams member did not transition to
ERROR after duplicate static instance id"
+ );
+
+ final StreamsGroupDescription groupDescriptionAfterConflict =
describeStreamsGroup(applicationId);
+
+ assertEquals(2,
groupDescriptionAfterConflict.members().size());
+ assertEquals(initialGroupEpoch,
groupDescriptionAfterConflict.groupEpoch());
+ assertEquals(firstMemberId,
staticStreamsMemberId(groupDescriptionAfterConflict,
firstInstanceId).orElseThrow());
+ assertEquals(secondMemberId,
staticStreamsMemberId(groupDescriptionAfterConflict,
secondInstanceId).orElseThrow());
+
assertTrue(hasActiveStaticStreamsMember(groupDescriptionAfterConflict,
firstInstanceId));
+
assertTrue(hasActiveStaticStreamsMember(groupDescriptionAfterConflict,
secondInstanceId));
+ assertEquals(firstRebalancesBeforeConflict,
firstStreamsRebalances.get());
+ assertEquals(secondRebalancesBeforeConflict,
secondStreamsRebalances.get());
+ }
+ } finally {
+ Utils.delete(firstStateDir);
+ Utils.delete(secondStateDir);
+ Utils.delete(conflictStateDir);
+ }
+ }
+
+ protected Topology setupTopologyWithoutIntermediateUserTopic() {
+ final StreamsBuilder builder = new StreamsBuilder();
+
+ final KStream<Long, String> input = builder.stream(INPUT_TOPIC);
+
+ input.to(OUTPUT_TOPIC, Produced.with(Serdes.Long(), Serdes.String()));
+ return builder.build();
+ }
+
+ private void add10InputElements() {
+ final List<KeyValue<Long, String>> records =
Arrays.asList(KeyValue.pair(0L, "aaa"),
+ KeyValue.pair(1L, "bbb"),
+ KeyValue.pair(0L, "ccc"),
+ KeyValue.pair(1L, "ddd"),
+ KeyValue.pair(0L, "eee"),
+ KeyValue.pair(1L, "fff"),
+ KeyValue.pair(0L, "ggg"),
+ KeyValue.pair(1L, "hhh"),
+ KeyValue.pair(0L, "iii"),
+ KeyValue.pair(1L, "jjj"));
+
+ for (final KeyValue<Long, String> record : records) {
+ mockTime.sleep(10);
+
IntegrationTestUtils.produceKeyValuesSynchronouslyWithTimestamp(INPUT_TOPIC,
Collections.singleton(record), producerConfig, mockTime.milliseconds());
+ }
+ }
+
+ private Properties staticStreamsConfig(final String groupInstanceId, final
File stateDir) {
+ final Properties config = new Properties();
+ config.putAll(streamsConfig);
+ config.put(StreamsConfig.GROUP_PROTOCOL_CONFIG,
GroupProtocol.STREAMS.name());
+ config.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1);
+ config.put(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG, groupInstanceId);
+ config.put(StreamsConfig.STATE_DIR_CONFIG, stateDir.getPath());
+ return config;
+ }
+
+ private StreamsGroupDescription describeStreamsGroup(final String
applicationId) throws Exception {
+ return
adminClient.describeStreamsGroups(Collections.singletonList(applicationId))
+ .describedGroups()
+ .get(applicationId)
+ .get();
+ }
+
+ private boolean hasActiveStaticStreamsMember(
+ final StreamsGroupDescription groupDescription,
+ final String baseInstanceId
+ ) {
+ return groupDescription.members().stream().anyMatch(member ->
+ member.instanceId()
+ .filter(instanceId -> instanceId.startsWith(baseInstanceId +
"-"))
+ .isPresent() &&
+ member.memberEpoch() >= 0
+ );
+ }
+
+ private boolean hasStaticStreamsMemberWithMemberIdAndEpoch(
+ final StreamsGroupDescription groupDescription,
+ final String baseInstanceId,
+ final String expectedMemberId,
+ final int expectedEpoch
+ ) {
+ return groupDescription.members().stream().anyMatch(member ->
+ member.instanceId()
+ .filter(instanceId -> instanceId.startsWith(baseInstanceId +
"-"))
+ .isPresent() &&
+ member.memberId().equals(expectedMemberId) &&
+ member.memberEpoch() == expectedEpoch
+ );
+ }
+
+ private Optional<String> staticStreamsMemberId(
+ final StreamsGroupDescription groupDescription,
+ final String baseInstanceId
+ ) {
+ return groupDescription.members().stream()
+ .filter(member -> member.instanceId()
+ .filter(instanceId -> instanceId.startsWith(baseInstanceId +
"-"))
+ .isPresent())
+ .map(member -> member.memberId())
+ .findFirst();
+ }
+
+}
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 54dcb726c47..220268c75ac 100644
--- a/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
+++ b/streams/src/main/java/org/apache/kafka/streams/StreamsConfig.java
@@ -1628,12 +1628,6 @@ public class StreamsConfig extends AbstractConfig {
private void verifyStreamsProtocolCompatibility(final boolean doLog) {
if (doLog && isStreamsProtocolEnabled()) {
- final Map<String, Object> mainConsumerConfigs =
getMainConsumerConfigs("dummy", "dummy", -1);
- final String instanceId = (String)
mainConsumerConfigs.get(CommonClientConfigs.GROUP_INSTANCE_ID_CONFIG);
- if (instanceId != null && !instanceId.isEmpty()) {
- throw new ConfigException("Streams rebalance protocol does not
support static membership. "
- + "Please set group.protocol=classic or remove
group.instance.id from the configuration.");
- }
if (getInt(StreamsConfig.MAX_WARMUP_REPLICAS_CONFIG) != 0) {
log.warn("Warmup replicas are not supported yet with the
streams protocol and will be ignored. "
+ "If you want to use warmup replicas, please set
group.protocol=classic.");
diff --git
a/streams/src/test/java/org/apache/kafka/streams/StreamsConfigTest.java
b/streams/src/test/java/org/apache/kafka/streams/StreamsConfigTest.java
index 481c1ad6bae..87648a25171 100644
--- a/streams/src/test/java/org/apache/kafka/streams/StreamsConfigTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/StreamsConfigTest.java
@@ -243,6 +243,22 @@ public class StreamsConfigTest {
assertNull(returnedProps.get(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG));
}
+ @ParameterizedTest
+ @ValueSource(strings = {"", StreamsConfig.CONSUMER_PREFIX,
StreamsConfig.MAIN_CONSUMER_PREFIX})
+ public void shouldAllowStaticMembershipWhenStreamsProtocolUsed(final
String prefix) {
+ props.put(StreamsConfig.GROUP_PROTOCOL_CONFIG, "streams");
+ props.put(prefix + ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
"static-member-1");
+
+ final StreamsConfig streamsConfig = new StreamsConfig(props);
+ final Map<String, Object> mainConsumerConfigs =
+ streamsConfig.getMainConsumerConfigs(groupId, clientId, threadIdx);
+
+ assertThat(
+ mainConsumerConfigs.get(ConsumerConfig.GROUP_INSTANCE_ID_CONFIG),
+ equalTo("static-member-1-" + threadIdx)
+ );
+ }
+
@Test
public void consumerConfigMustContainStreamPartitionAssignorConfig() {
props.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 42);
@@ -1864,23 +1880,6 @@ public class StreamsConfigTest {
}
}
- @ParameterizedTest
- @ValueSource(strings = {"", StreamsConfig.CONSUMER_PREFIX,
StreamsConfig.MAIN_CONSUMER_PREFIX})
- public void
shouldThrowConfigExceptionWhenStreamsProtocolUsedWithStaticMembership(final
String prefix) {
- final Properties props = new Properties();
- props.put(StreamsConfig.APPLICATION_ID_CONFIG, "test-app");
- props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "dummy:9092");
- props.put(StreamsConfig.GROUP_PROTOCOL_CONFIG, "streams");
- props.put(prefix + ConsumerConfig.GROUP_INSTANCE_ID_CONFIG,
"static-member-1");
-
- final ConfigException exception = assertThrows(
- ConfigException.class,
- () -> new StreamsConfig(props)
- );
- assertTrue(exception.getMessage().contains("Streams rebalance protocol
does not support static membership. " +
- "Please set group.protocol=classic or remove group.instance.id
from the configuration."));
- }
-
@Test
public void shouldSetDefaultDeadLetterQueue() {
final StreamsConfig config = new StreamsConfig(props);