Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -1420,6 +1420,7 @@ project(':group-coordinator') {
implementation libs.hdrHistogram
implementation libs.re2j
implementation libs.slf4jApi
implementation libs.guava

testImplementation project(':clients').sourceSets.test.output
testImplementation project(':server-common').sourceSets.test.output
Expand Down
1 change: 1 addition & 0 deletions checkstyle/import-control-group-coordinator.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
<allow pkg="org.apache.kafka.coordinator.common.runtime" />
<allow pkg="com.google.re2j" />
<allow pkg="org.apache.kafka.metadata" />
<allow pkg="com.google.common.hash" />
<subpackage name="metrics">
<allow pkg="com.yammer.metrics"/>
<allow pkg="org.HdrHistogram" />
Expand Down
2 changes: 2 additions & 0 deletions gradle/dependencies.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ versions += [
classgraph: "4.8.173",
gradle: "8.10.2",
grgit: "4.1.1",
guava: "33.4.0-jre",
httpclient: "4.5.14",
jackson: "2.16.2",
jacoco: "0.8.10",
Expand Down Expand Up @@ -147,6 +148,7 @@ libs += [
caffeine: "com.github.ben-manes.caffeine:caffeine:$versions.caffeine",
classgraph: "io.github.classgraph:classgraph:$versions.classgraph",
commonsValidator: "commons-validator:commons-validator:$versions.commonsValidator",
guava: "com.google.guava:guava:$versions.guava",
jacksonAnnotations: "com.fasterxml.jackson.core:jackson-annotations:$versions.jackson",
jacksonDatabind: "com.fasterxml.jackson.core:jackson-databind:$versions.jackson",
jacksonDatabindYaml: "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:$versions.jackson",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,21 @@
import org.apache.kafka.common.KafkaException;
import org.apache.kafka.common.message.ListGroupsResponseData;
import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
import org.apache.kafka.image.ClusterImage;
import org.apache.kafka.image.TopicImage;
import org.apache.kafka.metadata.BrokerRegistration;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
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 java.util.function.Function;
Expand Down Expand Up @@ -209,4 +219,50 @@ void validateOffsetFetch(
default boolean shouldExpire() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintainability Issue: Missing documentation for hash algorithm design decisions

The implementation uses specific hashing algorithms (Murmur3 for topic hash and ordered combination for group hash) without documenting why these choices were made. This makes it difficult for future developers to understand the requirements and constraints when they need to modify the hashing logic.

Suggestion: Add documentation explaining the rationale behind the hash algorithm choices:

/**
 * Computes the hash of the topics in a group.
 *
 * @param topicHashes The map of topic hashes. Key is topic name and value is the topic hash.
 * @return The hash of the group.
 *
 * Note: We use ordered combination of hashes to ensure consistent results
 * regardless of the iteration order of the map. This is important for
 * deterministic behavior across different JVM implementations.
 */
static long computeGroupHash(Map<String, Long> topicHashes) {
  // Implementation unchanged
}

/**
 * Computes the hash of the topic id, name, number of partitions, and partition racks by Murmur3.
 * This hash is used to detect changes in topic configuration that would affect consumer group behavior.
 *
 * The hash includes:
 * - A version byte to allow for future hash algorithm changes
 * - Topic ID and name to identify the topic
 * - Number of partitions and their configuration to detect partition changes
 * - Rack information to detect changes in rack assignment that might affect consumer group behavior
 *
 * @param topicImage The topic image.
 * @param clusterImage The cluster image.
 * @return The hash of the topic.
 */
static long computeTopicHash(TopicImage topicImage, ClusterImage clusterImage) {
  // Implementation unchanged
}

return true;
}

/**
* Computes the hash of the topics in a group.
*
* @param topicHashes The map of topic hashes. Key is topic name and value is the topic hash.
* @return The hash of the group.
*/
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Consider adding a brief JavaDoc comment explaining the purpose of this method and when it should be used.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintainability Issue: Magic byte value in hash computation

The magic byte (byte) 0 is used directly in the hash computation without explanation. While this appears to be a version identifier for the hashing algorithm, future developers may not understand its significance or when it should be changed.

Suggestion:

// Define a named constant for the hash algorithm version
private static final byte TOPIC_HASH_VERSION = (byte) 0;

static long computeTopicHash(TopicImage topicImage, ClusterImage clusterImage) {
  HashFunction hf = Hashing.murmur3_128();
  Hasher topicHasher = hf.newHasher()
    .putByte(TOPIC_HASH_VERSION) // Hash algorithm version identifier
    .putLong(topicImage.id().hashCode()) // topic Id
    // rest of the method unchanged
}

static long computeGroupHash(Map<String, Long> topicHashes) {
return Hashing.combineOrdered(
topicHashes.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> HashCode.fromLong(e.getValue()))
.toList()
).asLong();
}
Comment on lines +230 to +237

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent Sorting Logic

The computeGroupHash method sorts entries by key (topic name) but the test in testComputeGroupHashWithDifferentOrder expects order sensitivity. This creates a logical inconsistency as the test expects the hash to change when entry order changes, but the implementation explicitly sorts entries, making order irrelevant.

Suggested change
return Hashing.combineOrdered(
topicHashes.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> HashCode.fromLong(e.getValue()))
.toList()
).asLong();
}
static long computeGroupHash(Map<String, Long> topicHashes) {
return Hashing.combineOrdered(
topicHashes.entrySet()
.stream()
.map(e -> HashCode.fromLong(e.getValue()))
.toList()
).asLong();
}
Standards
  • Algorithm-Correctness-Hash-Logic
  • Logic-Verification-Test-Alignment


/**
* Computes the hash of the topic id, name, number of partitions, and partition racks by Murmur3.
*
* @param topicImage The topic image.
* @param clusterImage The cluster image.
* @return The hash of the topic.
*/
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improvement: The computeTopicHash method is quite complex. Consider breaking it down into smaller helper methods for better readability and maintainability.

static long computeTopicHash(TopicImage topicImage, ClusterImage clusterImage) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security Note: Be cautious when using Murmur3 for security-sensitive hashing. It's designed for speed and distribution quality, not cryptographic security. If this hash is used for any security purposes, consider using a cryptographic hash function instead.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dependency Injection Opportunity

Static method tightly couples hash computation to specific image types. Consider introducing a strategy or dependency injection pattern to enhance flexibility and testability of hash computation.

Standards
  • SOLID-DIP
  • Design-Pattern-Strategy
  • Clean-Code-Dependency-Management

HashFunction hf = Hashing.murmur3_128();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reuse Hash Function

Creating a new HashFunction instance for each computeTopicHash call is inefficient. Consider making this a static final constant since Murmur3_128 is thread-safe and immutable, reducing object creation overhead when computing hashes for multiple topics.

Standards
  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Object-Reuse
  • Memory-Allocation-Optimization

Comment on lines +246 to +247

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Null Handling Missing

No explicit null checks for topicImage or clusterImage parameters. This could potentially cause NullPointerException during hash computation if invalid inputs are provided.

Standards
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • DbC-Preconditions

Hasher topicHasher = hf.newHasher()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintainability: The magic byte (byte) 0 should be defined as a named constant with a comment explaining its purpose.

.putByte((byte) 0) // magic byte

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extract Hash Constants

Magic numbers like '(byte) 0' reduce code maintainability as their purpose is unclear. Extracting this as a named constant would document its purpose and make future changes safer if the magic byte value needs modification.

Standards
  • Clean-Code-Naming
  • Maintainability-Quality-Constants
  • Clean-Code-Comments

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Magic Number Usage

Magic number 0 is used directly in the code without a named constant. This reduces code readability and makes future modifications error-prone if the magic byte value needs to change across multiple locations.

Standards
  • Clean-Code-Constants
  • Maintainability-Quality-Readability

.putLong(topicImage.id().hashCode()) // topic Id
.putString(topicImage.name(), StandardCharsets.UTF_8) // topic name
.putInt(topicImage.partitions().size()); // number of partitions

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance: The stream operation here creates intermediate collections and could be optimized. Consider using a more direct approach if this is in a performance-critical path.

topicImage.partitions().entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Murmur3 Hash Complexity

Stream sorting for partition entries introduces O(n log n) complexity during hash computation. For large partition sets, this could create unnecessary computational overhead during metadata processing.

Standards
  • ISO-IEC-25010-Performance-Efficiency-Time-Behavior
  • Algorithmic-Complexity-Linear-Optimization
  • Optimization-Pattern-Stream-Processing

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Topic Hash Ordering Sensitivity

Topic hash computation relies on sorted partition entries to ensure consistent hash generation. Sorting prevents hash variations from different partition order inputs, maintaining logical integrity of hash computation.

Standards
  • Algorithm-Correctness-Ordering
  • Logic-Verification-Consistency
  • Mathematical-Accuracy-Hash-Stability

topicHasher.putInt(entry.getKey()); // partition id
String racks = Arrays.stream(entry.getValue().replicas)
.mapToObj(clusterImage::broker)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Consider extracting the rack string generation into a separate method for better readability and potential reuse.

.filter(Objects::nonNull)
.map(BrokerRegistration::rack)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing Null Check

The code calls Optional::get without verifying if the Optional is present, which can throw NoSuchElementException if a broker has no rack information. This breaks the hash computation logic when brokers without rack information exist.

Standards
  • Algorithm-Correctness-Input-Validation
  • Logic-Verification-Null-Safety
  • Business-Rule-Error-Handling

.filter(Optional::isPresent)
.map(Optional::get)
.sorted()
Comment on lines +254 to +262

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Complex Hash Computation Logic

Complex stream processing for rack extraction introduces cognitive complexity. Consider extracting this logic into a separate method with clear, single responsibility to improve readability and maintainability.

Standards
  • SOLID-SRP
  • Clean-Code-Method-Complexity
  • Refactoring-Extract-Method

.collect(Collectors.joining(";"));
topicHasher.putString(racks, StandardCharsets.UTF_8); // sorted racks with separator ";"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing Import Validation

The code uses Collectors.joining() but lacks a corresponding import for java.util.stream.Collectors. This will cause compilation failure, preventing the hash computation functionality from working correctly.

Standards
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • ISO-IEC-25010-Reliability-Maturity

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing Import Statement

The code uses Collectors.joining() but lacks the required import for java.util.stream.Collectors. This will cause compilation failure, preventing the hash computation functionality from working at all.

Suggested change
topicHasher.putString(racks, StandardCharsets.UTF_8); // sorted racks with separator ";"
import java.util.stream.Collectors;
Standards
  • ISO-IEC-25010-Functional-Correctness-Appropriateness
  • ISO-IEC-25010-Reliability-Maturity

});
return topicHasher.hash().asLong();
}
}
Comment on lines +261 to 268

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optimize String Concatenation

String concatenation in a loop using Collectors.joining creates intermediate String objects. For large numbers of replicas, this can cause unnecessary memory allocation and garbage collection pressure. Consider using a StringBuilder for better memory efficiency.

Standards
  • ISO-IEC-25010-Performance-Efficiency-Resource-Utilization
  • Optimization-Pattern-Memory-Allocation
  • Algorithmic-Complexity-Linear-Optimization

Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
* 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.common.Uuid;
import org.apache.kafka.image.MetadataImage;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

public class GroupTest {
private static final Uuid FOO_TOPIC_ID = Uuid.randomUuid();
private static final String FOO_TOPIC_NAME = "foo";
private static final String BAR_TOPIC_NAME = "bar";
private static final int FOO_NUM_PARTITIONS = 2;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing: This test class is missing MetadataImageBuilder. Make sure it's properly defined or imported.

private static final MetadataImage FOO_METADATA_IMAGE = new MetadataImageBuilder()
.addTopic(FOO_TOPIC_ID, FOO_TOPIC_NAME, FOO_NUM_PARTITIONS)
.addRacks()
.build();

@Test
void testComputeTopicHash() {
long result = Group.computeTopicHash(FOO_METADATA_IMAGE.topics().getTopic(FOO_TOPIC_ID), FOO_METADATA_IMAGE.cluster());

HashFunction hf = Hashing.murmur3_128();
Hasher topicHasher = hf.newHasher()
.putByte((byte) 0) // magic byte
.putLong(FOO_TOPIC_ID.hashCode()) // topic Id
.putString(FOO_TOPIC_NAME, StandardCharsets.UTF_8) // topic name
.putInt(FOO_NUM_PARTITIONS) // number of partitions
.putInt(0) // partition 0
.putString("rack0;rack1", StandardCharsets.UTF_8) // rack of partition 0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improvement: Consider using a constant for the rack separator string (;) to ensure consistency across the codebase.

.putInt(1) // partition 1
.putString("rack1;rack2", StandardCharsets.UTF_8); // rack of partition 1
assertEquals(topicHasher.hash().asLong(), result);
}

@Test
void testComputeTopicHashWithDifferentMagicByte() {
long result = Group.computeTopicHash(FOO_METADATA_IMAGE.topics().getTopic(FOO_TOPIC_ID), FOO_METADATA_IMAGE.cluster());

HashFunction hf = Hashing.murmur3_128();
Hasher topicHasher = hf.newHasher()
.putByte((byte) 1) // different magic byte
.putLong(FOO_TOPIC_ID.hashCode()) // topic Id
.putString(FOO_TOPIC_NAME, StandardCharsets.UTF_8) // topic name
.putInt(FOO_NUM_PARTITIONS) // number of partitions
.putInt(0) // partition 0
.putString("rack0;rack1", StandardCharsets.UTF_8) // rack of partition 0
.putInt(1) // partition 1
.putString("rack1;rack2", StandardCharsets.UTF_8); // rack of partition 1
assertNotEquals(topicHasher.hash().asLong(), result);
}

@Test
void testComputeTopicHashWithDifferentPartitionOrder() {
long result = Group.computeTopicHash(FOO_METADATA_IMAGE.topics().getTopic(FOO_TOPIC_ID), FOO_METADATA_IMAGE.cluster());

HashFunction hf = Hashing.murmur3_128();
Hasher topicHasher = hf.newHasher()
.putByte((byte) 0) // magic byte
.putLong(FOO_TOPIC_ID.hashCode()) // topic Id
.putString(FOO_TOPIC_NAME, StandardCharsets.UTF_8) // topic name
.putInt(FOO_NUM_PARTITIONS) // number of partitions
// different partition order
.putInt(1) // partition 1
.putString("rack1;rack2", StandardCharsets.UTF_8) // rack of partition 1
.putInt(0) // partition 0
.putString("rack0;rack1", StandardCharsets.UTF_8); // rack of partition 0
assertNotEquals(topicHasher.hash().asLong(), result);
}

@Test
void testComputeTopicHashWithDifferentRackOrder() {
long result = Group.computeTopicHash(FOO_METADATA_IMAGE.topics().getTopic(FOO_TOPIC_ID), FOO_METADATA_IMAGE.cluster());

HashFunction hf = Hashing.murmur3_128();
Hasher topicHasher = hf.newHasher()
.putByte((byte) 0) // magic byte
.putLong(FOO_TOPIC_ID.hashCode()) // topic Id
.putString(FOO_TOPIC_NAME, StandardCharsets.UTF_8) // topic name
.putInt(FOO_NUM_PARTITIONS) // number of partitions
.putInt(0) // partition 0
.putString("rack1;rack0", StandardCharsets.UTF_8) // different rack order of partition 0
.putInt(1) // partition 1
.putString("rack1;rack2", StandardCharsets.UTF_8); // rack of partition 1
assertNotEquals(topicHasher.hash().asLong(), result);
}

@ParameterizedTest
@MethodSource("differentFieldGenerator")
void testComputeTopicHashWithDifferentField(MetadataImage differentImage, Uuid topicId) {
long result = Group.computeTopicHash(FOO_METADATA_IMAGE.topics().getTopic(FOO_TOPIC_ID), FOO_METADATA_IMAGE.cluster());

assertNotEquals(
Group.computeTopicHash(
differentImage.topics().getTopic(topicId),
differentImage.cluster()
),
result
);
}

private static Stream<Arguments> differentFieldGenerator() {
Uuid differentTopicId = Uuid.randomUuid();
return Stream.of(
Arguments.of(new MetadataImageBuilder() // different topic id
.addTopic(differentTopicId, FOO_TOPIC_NAME, FOO_NUM_PARTITIONS)
.addRacks()
.build(),
differentTopicId
),
Arguments.of(new MetadataImageBuilder() // different topic name
.addTopic(FOO_TOPIC_ID, "bar", FOO_NUM_PARTITIONS)
.addRacks()
.build(),
FOO_TOPIC_ID
),
Arguments.of(new MetadataImageBuilder() // different partitions
.addTopic(FOO_TOPIC_ID, FOO_TOPIC_NAME, 1)
.addRacks()
.build(),
FOO_TOPIC_ID
),
Arguments.of(new MetadataImageBuilder() // different racks
.addTopic(FOO_TOPIC_ID, FOO_TOPIC_NAME, FOO_NUM_PARTITIONS)
.build(),
FOO_TOPIC_ID
)
);
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing: Consider adding a test case for an empty map of topic hashes to ensure proper handling of edge cases.

@Test
void testComputeGroupHash() {
long result = Group.computeGroupHash(Map.of(
BAR_TOPIC_NAME, 123L,
FOO_TOPIC_NAME, 456L
));

long expected = Hashing.combineOrdered(List.of(
HashCode.fromLong(123L),
HashCode.fromLong(456L)
)).asLong();
assertEquals(expected, result);
}

@Test
void testComputeGroupHashWithDifferentOrder() {
long result = Group.computeGroupHash(Map.of(
BAR_TOPIC_NAME, 123L,
FOO_TOPIC_NAME, 456L
));

long unexpected = Hashing.combineOrdered(List.of(
HashCode.fromLong(456L),
HashCode.fromLong(123L)
)).asLong();
assertNotEquals(unexpected, result);
}
}