smjn commented on code in PR #17149: URL: https://github.com/apache/kafka/pull/17149#discussion_r1779349368
########## share-coordinator/src/main/java/org/apache/kafka/coordinator/share/PersisterStateBatchCombiner.java: ########## @@ -0,0 +1,394 @@ +/* + * 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.share; + +import org.apache.kafka.server.share.PersisterStateBatch; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.TreeSet; + +public class PersisterStateBatchCombiner { + private List<PersisterStateBatch> combinedBatchList; // link between pruning and merging + private final long startOffset; + private TreeSet<PersisterStateBatch> sortedBatches; + private List<PersisterStateBatch> finalBatchList; // final list is built here + + public PersisterStateBatchCombiner( + List<PersisterStateBatch> batchesSoFar, + List<PersisterStateBatch> newBatches, + long startOffset + ) { + initializeCombinedList(batchesSoFar, newBatches); + finalBatchList = new ArrayList<>(combinedBatchList.size() * 2); // heuristic size + this.startOffset = startOffset; + } + + private void initializeCombinedList(List<PersisterStateBatch> batchesSoFar, List<PersisterStateBatch> newBatches) { + boolean soFarEmpty = batchesSoFar == null || batchesSoFar.isEmpty(); + boolean newBatchesEmpty = newBatches == null || newBatches.isEmpty(); + + if (soFarEmpty && newBatchesEmpty) { + combinedBatchList = new ArrayList<>(); + } else if (soFarEmpty) { + combinedBatchList = newBatches; + } else if (newBatchesEmpty) { + combinedBatchList = batchesSoFar; + } else { + combinedBatchList = new ArrayList<>(batchesSoFar.size() + newBatches.size()); + combinedBatchList.addAll(batchesSoFar); + combinedBatchList.addAll(newBatches); + } + } + + /** + * Algorithm: Merge current state batches and new batches into a single non-overlapping batch list. + * Input: batchesSoFar, newBatches, startOffset + * Output: combined list with non-overlapping batches (finalBatchList) + * <p> + * - Add both currentBatches and newBatches into a single list combinedBatchList + * - Remove/prune any batches from the combinedBatchList: + * - if batch.lastOffset < startOffset then remove batch from combinedBatchList + * - else if batch.firstOffset > startOffset then we will keep the batch + * - else if batch.firstOffset <= startOffset <= batch.lastOffset then keep [startOffset, batch.lastOffset] part only and discard rest. + * - create a treeset sortedBatches using pruned combinedBatchList + * - do repeat until all batches in sortedSet are non-overlapping: + * - find first 2 overlapping batches in sortedBatches set, say, prev and candidate. + * - remove any non-overlapping batches from sortedBatches encountered during the find operation and add them to a finalBatchList + * - based on various conditions of offset overlap and batch state differences combine the batches or + * create new batches, if required, and add to the sortedSet. + * - done + * - return the finalBatchList + * + * @return list of {@link PersisterStateBatch} representing non-overlapping combined batches + */ + public List<PersisterStateBatch> combineStateBatches() { + pruneBatches(); + mergeBatches(); + return finalBatchList; + } + + private void mergeBatches() { + if (combinedBatchList.size() < 2) { + finalBatchList = combinedBatchList; + return; + } + + sortedBatches = new TreeSet<>(combinedBatchList); + + BatchOverlapState overlapState = getOverlappingState(); + + while (overlapState != BatchOverlapState.EMPTY) { + PersisterStateBatch prev = overlapState.prev(); + PersisterStateBatch candidate = overlapState.candidate(); + + // remove both previous and candidate for easier + // assessment about adding batches to sortedBatches + sortedBatches.remove(prev); + sortedBatches.remove(candidate); + + if (compareBatchState(candidate, prev) == 0) { // same state and overlap or contiguous + // overlap and same state (prev.firstOffset <= candidate.firstOffset) due to sort + // covers: + // case: 1 2 3 4 5 6 7 (contiguous) + // prev: ------ ------- ------- ------- ------- -------- ------- + // candidate: ------ ---- ---------- --- ---- ------- ------- + handleSameStateOverlap(prev, candidate); + } else { // diff state and non-contiguous overlap + // overlap and diff state + // covers: + // case: 1 2* 3 4 5 6 7* + // prev: ------ ------- ------- ------- ------- -------- ------ + // candidate: ------ ---- --------- ---- ---- ------- ------- + // max batches: 1 2 2 3 2 2 2 + // min batches: 1 1 1 1 1 2 1 + // * not possible with treeset + handleDiffStateOverlap(prev, candidate); + } + overlapState = getOverlappingState(); + } + finalBatchList.addAll(sortedBatches); // some non overlapping batches might have remained + } + + /** + * Compares the non-offset state of 2 batches i.e. the deliveryCount and deliverState. + * <p> + * Uses standard compareTo contract x < y => +int, x > y => -int, x == y => 0 + * + * @param b1 - {@link PersisterStateBatch} to compare + * @param b2 - {@link PersisterStateBatch} to compare + * @return int representing comparison result. + */ + private int compareBatchState(PersisterStateBatch b1, PersisterStateBatch b2) { + int deltaCount = Short.compare(b1.deliveryCount(), b2.deliveryCount()); + + // Delivery state could be: + // 0 - AVAILABLE (non-terminal) + // 1 - ACQUIRED - should not be persisted yet + // 2 - ACKNOWLEDGED (terminal) + // 3 - ARCHIVING - not implemented in KIP-932 - non-terminal - leads only to ARCHIVED + // 4 - ARCHIVED (terminal) + + if (deltaCount == 0) { // same delivery count + return Byte.compare(b1.deliveryState(), b2.deliveryState()); + } + return deltaCount; + } + + /** + * Accepts a sorted set of state batches and finds the first 2 batches which overlap. + * Overlap means that they have some offsets in common or, they are contiguous with the same state. + * <p> + * Along with the 2 overlapping batches, also returns a list of non overlapping intervals + * prefixing them. For example: + * ----- ---- ----- ----- ----- + * ------ + * <---------------> <--------> + * non-overlapping 1st overlapping pair + * + * @return object representing the overlap state + */ + private BatchOverlapState getOverlappingState() { + if (sortedBatches == null || sortedBatches.isEmpty()) { + return BatchOverlapState.EMPTY; + } + Iterator<PersisterStateBatch> iter = sortedBatches.iterator(); + PersisterStateBatch prev = iter.next(); + List<PersisterStateBatch> nonOverlapping = new ArrayList<>(sortedBatches.size()); + while (iter.hasNext()) { + PersisterStateBatch candidate = iter.next(); + if (candidate.firstOffset() <= prev.lastOffset() || // overlap + prev.lastOffset() + 1 == candidate.firstOffset() && compareBatchState(prev, candidate) == 0) { // contiguous Review Comment: Only continuous batches with exactly same state are returned here. We can perhaps rename the method to `getMergeCandidates()`? -- 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]
