Skip to content

KAFKA-19454: Handle topics missing in metadata in share delete. #20090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 3, 2025
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
import org.apache.kafka.coordinator.group.streams.StreamsGroupHeartbeatResult;
import org.apache.kafka.image.MetadataDelta;
import org.apache.kafka.image.MetadataImage;
import org.apache.kafka.image.TopicImage;
import org.apache.kafka.server.authorizer.AuthorizableRequestContext;
import org.apache.kafka.server.authorizer.Authorizer;
import org.apache.kafka.server.record.BrokerCompressionType;
Expand Down Expand Up @@ -2137,10 +2138,22 @@ public void onPartitionsDeleted(
).get();

// At this point the metadata will not have been updated
// with the deleted topics.
Set<Uuid> topicIds = topicPartitions.stream()
.map(tp -> metadataImage.topics().getTopic(tp.topic()).id())
.collect(Collectors.toSet());
// with the deleted topics. However, we must guard against it.
if (metadataImage == null || metadataImage.equals(MetadataImage.EMPTY)) {
return;
}

Set<Uuid> topicIds = new HashSet<>();
for (TopicPartition tp : topicPartitions) {
TopicImage image = metadataImage.topics().getTopic(tp.topic());
if (image != null) {
topicIds.add(image.id());
}
}

if (topicIds.isEmpty()) {
return;
}

CompletableFuture.allOf(
FutureUtils.mapExceptionally(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8020,24 +8020,52 @@ public Optional<DeleteShareGroupStateParameters> shareGroupBuildPartitionDeleteR
// a retry for the same is possible. Since this is part of an admin operation
// retrying delete should not pose issues related to
// performance. Also, the share coordinator is idempotent on delete partitions.
Map<Uuid, InitMapValue> deletingTopics = shareGroupStatePartitionMetadata.get(shareGroupId).deletingTopics().stream()
.map(tid -> {
TopicImage image = metadataImage.topics().getTopic(tid);
return Map.entry(tid, new InitMapValue(image.name(), image.partitions().keySet(), -1));
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

if (!deletingTopics.isEmpty()) {
log.info("Existing deleting entries found in share group {} - {}", shareGroupId, deletingTopics);
deleteCandidates = combineInitMaps(deleteCandidates, deletingTopics);
Set<Uuid> currentDeleting = shareGroupStatePartitionMetadata.get(shareGroupId).deletingTopics();
Map<Uuid, InitMapValue> deleteRetryCandidates = new HashMap<>();
Set<Uuid> deletingToIgnore = new HashSet<>();
if (!currentDeleting.isEmpty()) {
if (metadataImage == null || metadataImage.equals(MetadataImage.EMPTY)) {
deletingToIgnore.addAll(currentDeleting);
} else {
for (Uuid deletingTopicId : currentDeleting) {
TopicImage topicImage = metadataImage.topics().getTopic(deletingTopicId);
if (topicImage == null) {
deletingToIgnore.add(deletingTopicId);
} else {
deleteRetryCandidates.put(deletingTopicId, new InitMapValue(topicImage.name(), topicImage.partitions().keySet(), -1));
}
}
}
}

if (!deletingToIgnore.isEmpty()) {
log.warn("Some topics for share group id {} were not found in the metadata image - {}", shareGroupId, deletingToIgnore);
}

if (!deleteRetryCandidates.isEmpty()) {
log.info("Existing deleting entries found in share group {} - {}", shareGroupId, deleteRetryCandidates);
deleteCandidates = combineInitMaps(deleteCandidates, deleteRetryCandidates);
}

// Remove all initializing and initialized topic info from record and add deleting. There
// could be previous deleting topics due to offsets delete, we need to account for them as well.
// If some older deleting topics could not be found in the metadata image, they will be ignored
// and logged.
records.add(GroupCoordinatorRecordHelpers.newShareGroupStatePartitionMetadataRecord(
shareGroupId,
Map.of(),
Map.of(),
deleteCandidates.entrySet().stream()
.map(entry -> Map.entry(entry.getKey(), entry.getValue().name()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
));

if (deleteCandidates.isEmpty()) {
return Optional.empty();
}

List<TopicData<PartitionIdData>> topicDataList = new ArrayList<>(deleteCandidates.size());

for (Map.Entry<Uuid, InitMapValue> entry : deleteCandidates.entrySet()) {
topicDataList.add(new TopicData<>(
entry.getKey(),
Expand All @@ -8047,15 +8075,6 @@ public Optional<DeleteShareGroupStateParameters> shareGroupBuildPartitionDeleteR
));
}

// Remove all initializing and initialized topic info from record and add deleting. There
// could be previous deleting topics due to offsets delete, we need to account for them as well.
records.add(GroupCoordinatorRecordHelpers.newShareGroupStatePartitionMetadataRecord(
shareGroupId,
Map.of(),
Map.of(),
attachTopicName(deleteCandidates.keySet())
));

return Optional.of(new DeleteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<PartitionIdData>()
.setGroupId(shareGroupId)
Expand Down Expand Up @@ -8247,13 +8266,15 @@ public CoordinatorResult<Void, CoordinatorRecord> maybeCleanupShareGroupState(
shareGroupStatePartitionMetadata.forEach((groupId, metadata) -> {
Set<Uuid> initializingDeletedCurrent = new HashSet<>(metadata.initializingTopics().keySet());
Set<Uuid> initializedDeletedCurrent = new HashSet<>(metadata.initializedTopics().keySet());
Set<Uuid> deletingDeletedCurrent = new HashSet<>(metadata.deletingTopics());

initializingDeletedCurrent.retainAll(deletedTopicIds);
initializedDeletedCurrent.retainAll(deletedTopicIds);
deletingDeletedCurrent.retainAll(deletedTopicIds);

// The deleted topic ids are neither present in initializing
// not initialized, so we have nothing to do.
if (initializingDeletedCurrent.isEmpty() && initializedDeletedCurrent.isEmpty()) {
// nor in initialized nor in deleting, so we have nothing to do.
if (initializingDeletedCurrent.isEmpty() && initializedDeletedCurrent.isEmpty() && deletingDeletedCurrent.isEmpty()) {
return;
}

Expand All @@ -8268,14 +8289,14 @@ public CoordinatorResult<Void, CoordinatorRecord> maybeCleanupShareGroupState(
Map<Uuid, InitMapValue> finalInitialized = new HashMap<>(metadata.initializedTopics());
initializedDeletedCurrent.forEach(finalInitialized::remove);

Set<Uuid> deletingTopics = new HashSet<>(metadata.deletingTopics());
deletingTopics.removeAll(deletedTopicIds);
Set<Uuid> finalDeleting = new HashSet<>(metadata.deletingTopics());
finalDeleting.removeAll(deletedTopicIds);

records.add(GroupCoordinatorRecordHelpers.newShareGroupStatePartitionMetadataRecord(
groupId,
finalInitializing,
finalInitialized,
attachTopicName(deletingTopics)
attachTopicName(finalDeleting)
));
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3240,6 +3240,110 @@ public void testOnPartitionsDeletedCleanupShareGroupState() {
BufferSupplier.NO_CACHING
)
);

verify(runtime, times(1)).scheduleWriteAllOperation(
ArgumentMatchers.eq("maybe-cleanup-share-group-state"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
);
}

@Test
public void testOnPartitionsDeletedCleanupShareGroupStateEmptyMetadata() {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorServiceBuilder()
.setConfig(createConfig())
.setRuntime(runtime)
.build();
service.startup(() -> 3);

MetadataImage image = new MetadataImageBuilder()
.addTopic(Uuid.randomUuid(), "bar", 1)
.build();
service.onNewMetadataImage(image, new MetadataDelta(image));

// No error in partition deleted callback
when(runtime.scheduleWriteAllOperation(
ArgumentMatchers.eq("on-partition-deleted"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
)).thenReturn(List.of(
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null)
));

when(runtime.scheduleWriteAllOperation(
ArgumentMatchers.eq("maybe-cleanup-share-group-state"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
)).thenReturn(List.of(
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null)
));

// The exception is logged and swallowed.
assertDoesNotThrow(() ->
service.onPartitionsDeleted(
List.of(new TopicPartition("foo", 0)),
BufferSupplier.NO_CACHING
)
);

verify(runtime, times(0)).scheduleWriteAllOperation(
ArgumentMatchers.eq("maybe-cleanup-share-group-state"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
);
}

@Test
public void testOnPartitionsDeletedCleanupShareGroupStateTopicsNotInMetadata() {
CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime = mockRuntime();
GroupCoordinatorService service = new GroupCoordinatorServiceBuilder()
.setConfig(createConfig())
.setRuntime(runtime)
.build();
service.startup(() -> 3);

MetadataImage image = MetadataImage.EMPTY;
service.onNewMetadataImage(image, new MetadataDelta(image));

// No error in partition deleted callback
when(runtime.scheduleWriteAllOperation(
ArgumentMatchers.eq("on-partition-deleted"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
)).thenReturn(List.of(
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null)
));

when(runtime.scheduleWriteAllOperation(
ArgumentMatchers.eq("maybe-cleanup-share-group-state"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
)).thenReturn(List.of(
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null),
CompletableFuture.completedFuture(null)
));

// The exception is logged and swallowed.
assertDoesNotThrow(() ->
service.onPartitionsDeleted(
List.of(new TopicPartition("foo", 0)),
BufferSupplier.NO_CACHING
)
);

verify(runtime, times(0)).scheduleWriteAllOperation(
ArgumentMatchers.eq("maybe-cleanup-share-group-state"),
ArgumentMatchers.eq(Duration.ofMillis(5000)),
ArgumentMatchers.any()
);
}

@Test
Expand Down
Loading