lucasbru commented on code in PR #24294:
URL: https://github.com/apache/kafka/pull/24294#discussion_r4642876574


##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -4785,14 +4817,21 @@ private Map<String, TasksTuple> refineAssignment(
      * {@code -2}, which keeps the group out of {@code STABLE}.
      *
      * @param refinedAssignment The intermediate assignment keyed by member ID.
+     * @param targetAssignment  All members' target assignments, which the 
intermediate assignment was refined from.
      * @param group             The streams group.
      *
      * @return True if a member's intermediate assignment differs from its 
assigned tasks.
      */
     private static boolean differsFromAssignedTasks(
         final Map<String, TasksTuple> refinedAssignment,
+        final Map<String, TasksTuple> targetAssignment,
         final StreamsGroup group
     ) {
+        if (refinedAssignment == targetAssignment) {

Review Comment:
   This shortcut, and the one in maybeCacheRefinedAssignment, only kicks in 
when the refiner hands back the exact map it was given. Both current refiners 
do, but nothing in AssignmentRefiner#refine says so. Could we document it 
there? Something like "returning targetAssignment itself when nothing changes 
keeps stable heartbeats cheap". Also say in the comment here that the == means 
the refiner returned the target assignment unchanged.
   
   Related: the speedup doesn't apply to AssignmentRefinerImpl, which still 
scans the whole group in refine() on every stable heartbeat. I measured 
~0.6-1.1 ms per heartbeat at 1000 members before and after. Might be worth 
saying in the PR description that the numbers are for the NoOp refiner.



##########
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/coordinator/StreamsGroupHeartbeatBenchmark.java:
##########
@@ -0,0 +1,547 @@
+/*
+ * 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.jmh.coordinator;
+
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.internals.Topic;
+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.network.ClientInformation;
+import org.apache.kafka.common.network.ListenerName;
+import org.apache.kafka.common.protocol.ApiKeys;
+import org.apache.kafka.common.record.internal.RecordBatch;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.requests.RequestHeader;
+import org.apache.kafka.common.security.auth.KafkaPrincipal;
+import org.apache.kafka.common.security.auth.SecurityProtocol;
+import org.apache.kafka.common.utils.MockTime;
+import org.apache.kafka.common.utils.internals.LogContext;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorMetadataImage;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorRecord;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorResult;
+import org.apache.kafka.coordinator.common.runtime.CoordinatorTimer;
+import org.apache.kafka.coordinator.common.runtime.MetadataImageBuilder;
+import org.apache.kafka.coordinator.common.runtime.MockCoordinatorExecutor;
+import org.apache.kafka.coordinator.group.GroupConfigManager;
+import org.apache.kafka.coordinator.group.GroupCoordinatorConfig;
+import org.apache.kafka.coordinator.group.GroupCoordinatorShard;
+import org.apache.kafka.coordinator.group.metrics.GroupCoordinatorMetrics;
+import org.apache.kafka.coordinator.group.modern.share.ShareGroupConfig;
+import org.apache.kafka.coordinator.group.streams.AssignmentRefinerImpl;
+import org.apache.kafka.coordinator.group.streams.NoOpAssignmentRefiner;
+import org.apache.kafka.coordinator.group.streams.StreamsGroup;
+import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
+import org.apache.kafka.timeline.SnapshotRegistry;
+
+import com.yammer.metrics.core.MetricsRegistry;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Threads;
+import org.openjdk.jmh.annotations.Warmup;
+
+import java.net.InetAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Benchmarks how the group coordinator processes streams group heartbeats, 
and how it replays the records of a group.
+ * <ul>
+ *     <li>{@code stableHeartbeat}: a heartbeat of a member of a stable group 
that has nothing to report.</li>
+ *     <li>{@code taskOffsetsHeartbeat}: heartbeats of the members of a stable 
group, one in every
+ *     {@code heartbeatsPerTaskOffsetsReport} of which reports the offsets of 
the member's standby tasks, as a client
+ *     does every {@code group.streams.task.offset.interval.ms}. {@code 1} 
reports on every heartbeat; {@code 12} is
+ *     the default ratio of that interval (60 s) to {@code 
group.streams.heartbeat.interval.ms} (5 s). The members
+ *     report in different rounds, like clients whose timers are not aligned. 
A member reports no offsets for an
+ *     active task it processes, so without standby replicas the report is 
empty.</li>
+ *     <li>{@code replayGroupRecords}: replaying all records that built the 
stable group into a new coordinator, as
+ *     when the coordinator loads the group.</li>

Review Comment:
   nit: this only measures in-memory replay. A real load also deserializes, 
does the loader's offset bookkeeping, and runs onLoaded (session timeouts). 
Maybe say "in-memory replay of all records that built the stable group", and 
point to GroupCoordinatorShardLoadingBenchmark for the full load path.



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java:
##########
@@ -691,38 +707,64 @@ public Map<String, MemberTaskOffsets> taskOffsets() {
     /**
      * Returns the intermediate assignment that was derived for the given 
assignment epoch, if any. A value derived for
      * an earlier epoch is not returned: the intermediate assignment of an 
epoch is fixed, but a new epoch means a new
-     * refinement step, which has to be derived anew.
+     * refinement step, which has to be derived anew. If the intermediate 
assignment of that epoch is the target
+     * assignment, the given target assignment is returned, which may include 
changes whose records are not replayed
+     * yet, such as a static member replacing another.
      *
-     * @param assignmentEpoch The assignment epoch to return the intermediate 
assignment for.
+     * @param assignmentEpoch  The assignment epoch to return the intermediate 
assignment for.
+     * @param targetAssignment All members' target assignments of that epoch.
      *
      * @return The intermediate assignment keyed by member ID, or {@code null} 
if it was not derived for that epoch.
      */
-    public Map<String, TasksTuple> refinedAssignment(int assignmentEpoch) {
+    public Map<String, TasksTuple> refinedAssignment(int assignmentEpoch, 
Map<String, TasksTuple> targetAssignment) {
         final RefinedAssignment cached = refinedAssignment.get();
-        return cached.assignmentEpoch() == assignmentEpoch ? 
cached.assignment() : null;
+        if (cached.assignmentEpoch() != assignmentEpoch) {
+            return null;
+        }
+        return cached.isTargetAssignment() ? targetAssignment : 
cached.assignment();
     }
 
     /**
      * Caches the intermediate assignment derived for the given assignment 
epoch. This is transient state; it must be
      * set from the heartbeat path only, never while replaying records.
      * <p>
      * The given map is copied, so that the cached assignment is genuinely 
fixed for its epoch rather than tracking
-     * whatever the caller hands over: a refiner that returns the target 
assignment as-is would otherwise leave the
-     * cache holding a view of {@link #targetAssignment()}, which changes as 
records are replayed. Only the map itself
-     * is copied -- a {@link TasksTuple} already owns its task sets, so there 
is nothing else that could change
-     * underneath. The copy is free once the refiner returns a map it built 
itself, because {@link Map#copyOf} hands
-     * back an already-immutable map unchanged.
+     * whatever the caller hands over. An intermediate assignment that is the 
target assignment itself is cached with
+     * {@link #setRefinedAssignmentToTargetAssignment} instead, which does not 
copy it. Only the map itself is copied --
+     * a {@link TasksTuple} already owns its task sets, so there is nothing 
else that could change underneath. The copy
+     * is free once the refiner returns a map it built itself, because {@link 
Map#copyOf} hands back an
+     * already-immutable map unchanged.

Review Comment:
   Since this paragraph is being touched anyway: I don't think "the copy is 
free" holds. AssignmentRefinerImpl.assemble returns 
Collections.unmodifiableMap(...), and Map.copyOf only returns its argument 
unchanged for the JDK's own immutable maps (Map.of / Map.copyOf), so this 
copies all members. Instead of fixing this comment, maybe have the refiner 
return a Map.copyOf'd map so the copy here really is free.



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/streams/StreamsGroup.java:
##########
@@ -691,38 +707,64 @@ public Map<String, MemberTaskOffsets> taskOffsets() {
     /**
      * Returns the intermediate assignment that was derived for the given 
assignment epoch, if any. A value derived for
      * an earlier epoch is not returned: the intermediate assignment of an 
epoch is fixed, but a new epoch means a new
-     * refinement step, which has to be derived anew.
+     * refinement step, which has to be derived anew. If the intermediate 
assignment of that epoch is the target
+     * assignment, the given target assignment is returned, which may include 
changes whose records are not replayed
+     * yet, such as a static member replacing another.
      *
-     * @param assignmentEpoch The assignment epoch to return the intermediate 
assignment for.
+     * @param assignmentEpoch  The assignment epoch to return the intermediate 
assignment for.
+     * @param targetAssignment All members' target assignments of that epoch.
      *
      * @return The intermediate assignment keyed by member ID, or {@code null} 
if it was not derived for that epoch.
      */
-    public Map<String, TasksTuple> refinedAssignment(int assignmentEpoch) {
+    public Map<String, TasksTuple> refinedAssignment(int assignmentEpoch, 
Map<String, TasksTuple> targetAssignment) {
         final RefinedAssignment cached = refinedAssignment.get();
-        return cached.assignmentEpoch() == assignmentEpoch ? 
cached.assignment() : null;
+        if (cached.assignmentEpoch() != assignmentEpoch) {
+            return null;
+        }
+        return cached.isTargetAssignment() ? targetAssignment : 
cached.assignment();
     }
 
     /**
      * Caches the intermediate assignment derived for the given assignment 
epoch. This is transient state; it must be
      * set from the heartbeat path only, never while replaying records.
      * <p>
      * The given map is copied, so that the cached assignment is genuinely 
fixed for its epoch rather than tracking
-     * whatever the caller hands over: a refiner that returns the target 
assignment as-is would otherwise leave the
-     * cache holding a view of {@link #targetAssignment()}, which changes as 
records are replayed. Only the map itself
-     * is copied -- a {@link TasksTuple} already owns its task sets, so there 
is nothing else that could change
-     * underneath. The copy is free once the refiner returns a map it built 
itself, because {@link Map#copyOf} hands
-     * back an already-immutable map unchanged.
+     * whatever the caller hands over. An intermediate assignment that is the 
target assignment itself is cached with
+     * {@link #setRefinedAssignmentToTargetAssignment} instead, which does not 
copy it. Only the map itself is copied --
+     * a {@link TasksTuple} already owns its task sets, so there is nothing 
else that could change underneath. The copy
+     * is free once the refiner returns a map it built itself, because {@link 
Map#copyOf} hands back an
+     * already-immutable map unchanged.
      *
      * @param assignmentEpoch    The assignment epoch the intermediate 
assignment was derived for.
      * @param refinedAssignment  The intermediate assignment keyed by member 
ID.
      */
     public void setRefinedAssignment(int assignmentEpoch, Map<String, 
TasksTuple> refinedAssignment) {
         this.refinedAssignment.set(new RefinedAssignment(
             assignmentEpoch,
-            Map.copyOf(Objects.requireNonNull(refinedAssignment))
+            Map.copyOf(Objects.requireNonNull(refinedAssignment)),
+            false
         ));
     }
 
+    /**
+     * Caches that the intermediate assignment of the given assignment epoch 
is its target assignment, without copying
+     * the target assignment. This is transient state; it must be set from the 
heartbeat path only, never while
+     * replaying records.
+     * <p>
+     * Within an assignment epoch, the target assignment only changes when a 
static member replaces another, which
+     * relabels the replaced member's target assignment the same way {@link 
#relabelRefinedAssignment} relabels a cached
+     * copy, and when a member is removed, whose intermediate assignment is 
then no longer read.

Review Comment:
   I don't think "no longer read" holds when the removed member rejoins with 
the same member ID in the same assignment epoch. That can happen if it isn't 
the last member and the assignor is deferred by the assignment interval. Before 
this PR it got its old tasks back from the frozen copy. Now it reads the live 
target assignment, where its entry was tombstoned, so it gets EMPTY. That's 
arguably the better behavior (it matches warm-ups disabled), but the comment 
should say what actually happens. Maybe also state the conclusion explicitly: 
reading the live target assignment is equivalent to a frozen copy as long as 
those are the only in-epoch changes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to