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


##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -660,6 +699,8 @@ private void clearCurrentTaskAssignment() {
     private void clearTaskAndPartitionAssignment() {
         subscriptionState.assignFromSubscribed(Collections.emptySet());
         notifyAssignmentChange(Collections.emptySet());
+        final Set<String> inputTopics = assignedInputTopics(currentAssignment);
+        topicPartitionsCache.keySet().retainAll(inputTopics);

Review Comment:
   `currentAssignment` is still the old assignment here, so the `retainAll` 
keeps the counts of exactly the topics being cleared, which makes it a no-op 
given the pruning after each assignment. A higher count then survives a fence 
or leave and the rejoin. Shouldn't this be `topicPartitionsCache.clear()`, like 
`clearPendingAssignmentsAndLocalNamesCache()` in the consumer? That would also 
match tying the guard to the current assignment. Recreating a topic with fewer 
partitions isn't supported, as the comment below says, but with a cleared cache 
a rejoin would at least not keep assigning partitions that no longer exist 
(e.g. with a cached count of 3 and metadata saying 1, tasks 0_1 and 0_2 resolve 
to nonexistent partitions after the rejoin).



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java:
##########


Review Comment:
   Could you update the PR description? It still describes the 
applied/reconciled split, duplicate revocation prevention, late-callback 
protection and FATAL on mismatch, which are now part of #23773.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -1122,7 +1174,24 @@ private void processAssignmentReceived(Map<String, 
SortedSet<Integer>> activeTas
     }
 
     private boolean targetAssignmentReconciled() {
-        return currentAssignment.equals(targetAssignment);
+        // A new member epoch may assign the same tasks after a 
partition-count change.
+        // With client-side metadata resolution, stale but known counts can 
produce
+        // incomplete input partitions while all tasks are considered resolved.
+        // This check may therefore report completion before the client 
observes
+        // the updated counts; a later metadata update alone does not reopen 
reconciliation.
+        //
+        // This limitation is accepted when broker-provided assignment 
metadata is
+        // unavailable. Local metadata alone cannot establish which partition 
counts
+        // the coordinator used for the assignment.
+        // TODO: KAFKA-21526

Review Comment:
   Could we drop the TODO and the ticket number here? TODOs are rare in this 
package, and the follow-up is tracked in KAFKA-21526 anyway. I'd keep the 
description of the limitation (stale but known counts can produce incomplete 
input partitions, and a later metadata update alone doesn't reopen 
reconciliation) and drop the part about broker-provided metadata, since that 
doesn't exist yet.



##########
streams/src/main/java/org/apache/kafka/streams/processor/internals/DefaultStreamsRebalanceListener.java:
##########
@@ -96,6 +96,7 @@ public void onTasksAssigned(final 
StreamsRebalanceData.Assignment assignment) {
         final StreamsRebalanceData.Assignment runningAssignment = 
deduplicateTasks(assignment);
         final Map<TaskId, Set<TopicPartition>> activeTasksWithPartitions =
             pairWithTopicPartitions(runningAssignment.activeTasks().stream());
+        activeTasksWithPartitions.values().forEach(partitions -> 
partitions.retainAll(assignment.assignedPartitions()));
         final Map<TaskId, Set<TopicPartition>> standbyTasksWithPartitions =

Review Comment:
   Standby and warm-up tasks are still paired with partitions that don't exist 
(e.g. A-2 for a 1-partition topic A), and the same goes for `onTasksRevoked`. 
They show up in the thread metadata (`metadataForLocalThreads`), and recycling 
an affected task between active and standby (e.g. 0_1 or 0_2 in the merge test) 
logs the "Detected unmatched input partitions" warning. Everything else looks 
inert, but should we filter these as well so we pass what the classic protocol 
passes? That would need the resolved partition set for standby/warm-up tasks 
too.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -92,20 +95,27 @@ private static class LocalAssignment {
         public final Map<String, SortedSet<Integer>> warmupTasks;
         public final boolean isGroupReady;
 
+        // Null for assignments received from brokers that do not provide 
partition information.

Review Comment:
   This field is needed with current brokers too, since it holds what we 
resolved from local metadata and applied. But the comment reads as if `null` 
meant a broker that doesn't send partitions, and no broker sends them; it just 
means the assignment hasn't been resolved yet (the target assignment). Maybe 
something like "Input partitions of the resolved active tasks, computed from 
local metadata. Null for a target assignment that has not been resolved yet. 
May be empty." Could we also drop `assignedPartitions` from 
`equals`/`hashCode`? Since the target always has null, target and current can 
never be equal under `equals`, which is a trap for later use, and 
`reconcilingCompleted` doesn't need it.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -1122,7 +1174,24 @@ private void processAssignmentReceived(Map<String, 
SortedSet<Integer>> activeTas
     }
 
     private boolean targetAssignmentReconciled() {
-        return currentAssignment.equals(targetAssignment);
+        // A new member epoch may assign the same tasks after a 
partition-count change.
+        // With client-side metadata resolution, stale but known counts can 
produce
+        // incomplete input partitions while all tasks are considered resolved.
+        // This check may therefore report completion before the client 
observes
+        // the updated counts; a later metadata update alone does not reopen 
reconciliation.
+        //
+        // This limitation is accepted when broker-provided assignment 
metadata is
+        // unavailable. Local metadata alone cannot establish which partition 
counts
+        // the coordinator used for the assignment.
+        // TODO: KAFKA-21526
+        // Use broker-provided topic IDs and partition counts to resolve and
+        // validate the assignment against the coordinator's metadata snapshot.
+        return currentAssignment.reconcilingCompleted(targetAssignment);

Review Comment:
   Once `assignedPartitions` is out of `equals`/`hashCode` (see the other 
comment), `reconcilingCompleted` is the same as `equals`, so this could be 
`currentAssignment.equals(targetAssignment)` like 
`targetAssignmentReconciled()` in `AbstractMembershipManager`, and 
`reconcilingCompleted` can go. The skip check in `assignTasks` can switch to 
`equals` the same way.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -1162,23 +1231,32 @@ private void maybeReconcile() {
                 "current assignment.");
             return;
         }
-        if (reconciliationInProgress) {
+
+        if (isReconciliationInProgress()) {
             log.trace("Ignoring reconciliation attempt. Another reconciliation 
is already in progress. Assignment {}" +
                 " will be handled in the next reconciliation loop.", 
targetAssignment);
             return;
         }
 
+        if (isPartialAssignmentReconciled() && (metadata.updateVersion() == 
lastReconciledMetadataVersion)) {

Review Comment:
   Could we structure this like `AbstractMembershipManager.maybeReconcile` for 
the consumer? There, `findResolvableAssignmentAndTriggerMetadataUpdate()` runs 
first. If the resolved assignment equals `currentAssignment`, it returns when 
the local epoch is unchanged and otherwise acks without running the callbacks, 
and revocations are computed against the resolved assignment. If we resolve 
here before revoking and compare the resolved tasks and input partitions with 
`currentAssignment`, we don't need `lastReconciledMetadataVersion`, the 
metadata version check on `isPartialAssignmentReconciled()`, 
`AssignTasksResult` or the skip path in `assignTasks`. Re-resolving on each 
poll while reconciling is cheap, and the consumer does the same, including 
`requestUpdate(true)` while something is unresolved. One difference we'd have 
to keep: when the local epoch changed, we still need to run the callback rather 
than ack directly, since the heartbeat reports the listener's 
`reconciledAssignment`.



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -1286,36 +1364,77 @@ private CompletableFuture<Void> assignTasks(final 
SortedSet<StreamsRebalanceData
                 .collect(Collectors.joining(", "))
         );
 
-        final SortedSet<TopicPartition> partitionsToAssign = 
topicPartitionsForActiveTasks(activeTasksToAssign);
-        final SortedSet<TopicPartition> partitionsToAssignNotPreviouslyOwned =
-            partitionsToAssignNotPreviouslyOwned(partitionsToAssign, 
topicPartitionsForActiveTasks(ownedActiveTasks));
+        final Cluster metadataSnapshot = metadata.fetch();
+        final int metadataVersion = metadata.updateVersion();
+
+        // Include all resolvable active tasks in the target assignment, 
including those already applied.
+        // During partial reconciliation, passing only newly resolved tasks 
would cause TaskManager
+        // to treat previously assigned tasks omitted from the callback as 
removed.
+        final SortedSet<StreamsRebalanceData.TaskId> 
resolvedActiveTasksToAssign = 
filterTasksResolvableFromLocalMetadata(activeTasksToAssign, metadataSnapshot);
+        final SortedSet<TopicPartition> resolvedPartitionsToAssign = 
topicPartitionsForActiveTasks(resolvedActiveTasksToAssign, metadataSnapshot);
+
+        // Request a metadata update if any task has an unknown input topic 
partition count
+        // or no valid input partition according to the locally known counts.
+        if (resolvedActiveTasksToAssign.size() < activeTasksToAssign.size()) {
+            metadata.requestUpdate(true);
+        }
+        final SortedSet<TopicPartition> ownedAssignedPartitions = 
previousAssignedAssignment.assignedPartitions;
+        final SortedSet<TopicPartition> partitionsToAssignNotPreviouslyOwned = 
partitionsToAssignNotPreviouslyOwned(
+            resolvedPartitionsToAssign,
+            ownedAssignedPartitions
+        );
+        final Map<String, SortedSet<Integer>> resolvedActiveTasks = 
toTasksAssignment(resolvedActiveTasksToAssign);
+
+        // Capture the resolved portion of the target assignment.
+        // It becomes currentAssignment only after reconciliation completes 
successfully.
+        final LocalAssignment resolvedLocalAssignment = new LocalAssignment(
+            assignmentToReconcile.localEpoch,
+            resolvedActiveTasks,
+            assignmentToReconcile.standbyTasks,
+            assignmentToReconcile.warmupTasks,
+            assignmentToReconcile.isGroupReady,
+            resolvedPartitionsToAssign
+        );
+
+        // Skip applying the assignment and invoking the callback if the 
resolved tasks
+        // and partitions match the previously reconciled assignment at the 
same local epoch.
+        if 
(resolvedPartitionsToAssign.equals(previousAssignedAssignment.assignedPartitions)
 &&
+            
resolvedLocalAssignment.reconcilingCompleted(previousAssignedAssignment)
+        ) {
+            return CompletableFuture.completedFuture(new 
AssignTasksResult(null, metadataVersion));
+        }
 
         // Enqueue event to app thread to apply assignment within poll() and 
invoke callback.
-        // The app thread will trigger ApplyAssignmentEvent to update 
subscription state on background thread.
+        // The app thread will trigger Apply to update subscription state on 
background thread.
         CompletableFuture<Void> partitionsAssignedAndCallbackExecuted =
             enqueueStreamsPartitionsAssignedEvent(
-                partitionsToAssign,
+                resolvedPartitionsToAssign,
                 partitionsToAssignNotPreviouslyOwned,
                 new StreamsRebalanceData.Assignment(
-                    activeTasksToAssign,
+                    resolvedActiveTasksToAssign,
                     standbyTasksToAssign,
                     warmupTasksToAssign,
+                    resolvedLocalAssignment.assignedPartitions,
+                    resolvedLocalAssignment.localEpoch,
                     isGroupReady
                 )
             );
-        partitionsAssignedAndCallbackExecuted.whenComplete((__, callbackError) 
-> {
+
+        // Retain cached partition counts only for input topics of the tasks 
in the new assignment.
+        final Set<String> assignedInputTopics = 
assignedInputTopics(resolvedLocalAssignment);
+
+        return partitionsAssignedAndCallbackExecuted.whenComplete((__, 
callbackError) -> {
             if (callbackError == null) {
-                
subscriptionState.enablePartitionsAwaitingCallback(partitionsToAssign);
+                
subscriptionState.enablePartitionsAwaitingCallback(resolvedLocalAssignment.assignedPartitions);
+                topicPartitionsCache.keySet().retainAll(assignedInputTopics);

Review Comment:
   Yes https://github.com/apache/kafka/pull/23773



##########
clients/src/main/java/org/apache/kafka/clients/consumer/internals/StreamsMembershipManager.java:
##########
@@ -1286,36 +1364,77 @@ private CompletableFuture<Void> assignTasks(final 
SortedSet<StreamsRebalanceData
                 .collect(Collectors.joining(", "))
         );
 
-        final SortedSet<TopicPartition> partitionsToAssign = 
topicPartitionsForActiveTasks(activeTasksToAssign);
-        final SortedSet<TopicPartition> partitionsToAssignNotPreviouslyOwned =
-            partitionsToAssignNotPreviouslyOwned(partitionsToAssign, 
topicPartitionsForActiveTasks(ownedActiveTasks));
+        final Cluster metadataSnapshot = metadata.fetch();
+        final int metadataVersion = metadata.updateVersion();
+
+        // Include all resolvable active tasks in the target assignment, 
including those already applied.
+        // During partial reconciliation, passing only newly resolved tasks 
would cause TaskManager
+        // to treat previously assigned tasks omitted from the callback as 
removed.
+        final SortedSet<StreamsRebalanceData.TaskId> 
resolvedActiveTasksToAssign = 
filterTasksResolvableFromLocalMetadata(activeTasksToAssign, metadataSnapshot);
+        final SortedSet<TopicPartition> resolvedPartitionsToAssign = 
topicPartitionsForActiveTasks(resolvedActiveTasksToAssign, metadataSnapshot);
+
+        // Request a metadata update if any task has an unknown input topic 
partition count
+        // or no valid input partition according to the locally known counts.
+        if (resolvedActiveTasksToAssign.size() < activeTasksToAssign.size()) {
+            metadata.requestUpdate(true);
+        }
+        final SortedSet<TopicPartition> ownedAssignedPartitions = 
previousAssignedAssignment.assignedPartitions;
+        final SortedSet<TopicPartition> partitionsToAssignNotPreviouslyOwned = 
partitionsToAssignNotPreviouslyOwned(
+            resolvedPartitionsToAssign,
+            ownedAssignedPartitions
+        );
+        final Map<String, SortedSet<Integer>> resolvedActiveTasks = 
toTasksAssignment(resolvedActiveTasksToAssign);
+
+        // Capture the resolved portion of the target assignment.
+        // It becomes currentAssignment only after reconciliation completes 
successfully.
+        final LocalAssignment resolvedLocalAssignment = new LocalAssignment(
+            assignmentToReconcile.localEpoch,
+            resolvedActiveTasks,
+            assignmentToReconcile.standbyTasks,
+            assignmentToReconcile.warmupTasks,
+            assignmentToReconcile.isGroupReady,
+            resolvedPartitionsToAssign
+        );
+
+        // Skip applying the assignment and invoking the callback if the 
resolved tasks
+        // and partitions match the previously reconciled assignment at the 
same local epoch.
+        if 
(resolvedPartitionsToAssign.equals(previousAssignedAssignment.assignedPartitions)
 &&
+            
resolvedLocalAssignment.reconcilingCompleted(previousAssignedAssignment)
+        ) {
+            return CompletableFuture.completedFuture(new 
AssignTasksResult(null, metadataVersion));
+        }
 
         // Enqueue event to app thread to apply assignment within poll() and 
invoke callback.
-        // The app thread will trigger ApplyAssignmentEvent to update 
subscription state on background thread.
+        // The app thread will trigger Apply to update subscription state on 
background thread.
         CompletableFuture<Void> partitionsAssignedAndCallbackExecuted =
             enqueueStreamsPartitionsAssignedEvent(
-                partitionsToAssign,
+                resolvedPartitionsToAssign,
                 partitionsToAssignNotPreviouslyOwned,
                 new StreamsRebalanceData.Assignment(
-                    activeTasksToAssign,
+                    resolvedActiveTasksToAssign,
                     standbyTasksToAssign,
                     warmupTasksToAssign,
+                    resolvedLocalAssignment.assignedPartitions,
+                    resolvedLocalAssignment.localEpoch,
                     isGroupReady
                 )
             );
-        partitionsAssignedAndCallbackExecuted.whenComplete((__, callbackError) 
-> {
+
+        // Retain cached partition counts only for input topics of the tasks 
in the new assignment.
+        final Set<String> assignedInputTopics = 
assignedInputTopics(resolvedLocalAssignment);

Review Comment:
   The consumer prunes its topic names cache in `assignPartitions` 
(`assignedTopicNamesCache.values().retainAll(...)` in 
`AbstractMembershipManager`), after the revoke callback and the abort check, 
right after queuing the assign callback and outside its future. If we do the 
same here (with the input topics of the whole target, as discussed in the other 
thread), a late callback no longer touches the cache, and only the 
`enablePartitionsAwaitingCallback` part is left for #23773.



-- 
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