smengcl commented on code in PR #10484: URL: https://github.com/apache/ozone/pull/10484#discussion_r3530175911
########## hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java: ########## @@ -0,0 +1,569 @@ +/* + * 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.hadoop.hdds.utils.db; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.primitives.UnsignedLong; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.PriorityQueue; +import org.apache.hadoop.hdds.utils.IOUtils; +import org.apache.hadoop.hdds.utils.db.managed.ManagedOptions; +import org.apache.hadoop.ozone.util.ClosableIterator; + +/** + * Dual-heap k-way merge over RocksDB SST files for snapshot diff. + * <p> + * Two heaps track non-tombstones and tombstones separately. For each user key, + * all versions are drained from both heaps, then snapshot-diff emit rules apply: + * emit the latest tombstone and/or latest value, including both when a delete is + * followed by a newer recreate. + * <p> + * When constructed with an exclusive minimum sequence number {@code S}, each SST + * source skips entries whose sequence is {@code <= S} while advancing. + */ +public final class LatestVersionedKWayMergeIterator implements + ClosableIterator<LatestVersionedKWayMergeIterator.MergedKeyValue> { + + /** RocksDB {@code ValueType::kTypeValue}. */ + public static final int ROCKS_TYPE_VALUE = 1; + private static final int DEFAULT_READ_AHEAD_SIZE = 2 * 1024 * 1024; + + private final ManagedOptions options; + private final List<ClosableIterator<? extends MergeHead>> iterators; + private final Long exclusiveMinSequenceNumber; + + private final PriorityQueue<HeapEntry> valueHeap; + private final PriorityQueue<HeapEntry> tombstoneHeap; + + private List<MergedKeyValue> emitQueue; + private boolean initialized; + + public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles) + throws IOException { + return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE, null); + } + + public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles, + int readAheadSizePerFile) throws IOException { + return overRawSstFiles(sstFiles, readAheadSizePerFile, null); + } + + /** + * Opens one iterator per SST file and merges them. + * + * @param exclusiveMinSequenceNumber when non-null, each source skips entries with + * sequence {@code <=} this value while advancing; when null, no entries are skipped + */ + public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles, + int readAheadSizePerFile, Long exclusiveMinSequenceNumber) throws IOException { + Objects.requireNonNull(sstFiles, "sstFiles cannot be null"); + ManagedOptions options = new ManagedOptions(); + List<ClosableIterator<? extends MergeHead>> sources = new ArrayList<>(sstFiles.size()); + for (Path file : sstFiles) { + sources.add(new RawSstIterator(options, file, readAheadSizePerFile)); + } + return new LatestVersionedKWayMergeIterator(options, sources, exclusiveMinSequenceNumber); + } + + public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles, + long exclusiveMinSequenceNumber) throws IOException { + return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE, exclusiveMinSequenceNumber); + } + + @VisibleForTesting + public static LatestVersionedKWayMergeIterator forTest( + List<ClosableIterator<MergedKeyValue>> iterators) { + return forTest(iterators, null); + } + + @VisibleForTesting + public static LatestVersionedKWayMergeIterator forTest( + List<ClosableIterator<MergedKeyValue>> iterators, Long exclusiveMinSequenceNumber) { + List<ClosableIterator<? extends MergeHead>> sources = new ArrayList<>(iterators.size()); + sources.addAll(iterators); + return new LatestVersionedKWayMergeIterator(null, sources, exclusiveMinSequenceNumber); + } + + private LatestVersionedKWayMergeIterator( + ManagedOptions options, + List<ClosableIterator<? extends MergeHead>> iterators, + Long exclusiveMinSequenceNumber) { + this.options = options; + this.iterators = new ArrayList<>(Objects.requireNonNull(iterators, "iterators cannot be null")); + this.exclusiveMinSequenceNumber = exclusiveMinSequenceNumber; + this.valueHeap = new PriorityQueue<>(Math.max(this.iterators.size(), 1)); + this.tombstoneHeap = new PriorityQueue<>(Math.max(this.iterators.size(), 1)); + this.emitQueue = new ArrayList<>(); + } + + @Override + public boolean hasNext() { + if (!emitQueue.isEmpty()) { + return true; + } + try { + return advance(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public MergedKeyValue next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements found."); + } + return emitQueue.remove(0); + } + + private boolean advance() throws IOException { + if (!initialized) { + initHeaps(); + initialized = true; + } + + while (emitQueue.isEmpty() && (!valueHeap.isEmpty() || !tombstoneHeap.isEmpty())) { + processNextUserKey(); + } + + return !emitQueue.isEmpty(); + } + + private void processNextUserKey() throws IOException { + if (valueHeap.isEmpty() && tombstoneHeap.isEmpty()) { + return; + } + + byte[] nextKey = null; + if (!valueHeap.isEmpty() && !tombstoneHeap.isEmpty()) { + int cmp = compareUserKeys( + valueHeap.peek().current.getUserKey(), tombstoneHeap.peek().current.getUserKey()); + nextKey = cmp <= 0 + ? valueHeap.peek().current.getUserKey() + : tombstoneHeap.peek().current.getUserKey(); + } else if (!valueHeap.isEmpty()) { + nextKey = valueHeap.peek().current.getUserKey(); + } else { + nextKey = tombstoneHeap.peek().current.getUserKey(); + } + + MergeHead latestValue = null; + long latestValueSeq = -1L; + MergeHead latestTombstone = null; + long latestTombstoneSeq = -1L; + + while (hasUserKey(valueHeap, nextKey) || hasUserKey(tombstoneHeap, nextKey)) { + DrainedVersion valueRound = drainHeapForUserKey(valueHeap, nextKey, true); + if (valueRound.entry != null && valueRound.sequence > latestValueSeq) { + latestValue = valueRound.entry; + latestValueSeq = valueRound.sequence; + } + DrainedVersion tombstoneRound = drainHeapForUserKey(tombstoneHeap, nextKey, false); + if (tombstoneRound.entry != null && tombstoneRound.sequence > latestTombstoneSeq) { + latestTombstone = tombstoneRound.entry; + latestTombstoneSeq = tombstoneRound.sequence; + } + } + + emitForUserKey(latestValue, latestTombstone); + } + + private void emitForUserKey(MergeHead latestValue, MergeHead latestTombstone) { + if (latestValue != null && latestTombstone != null) { + if (latestValue.getSequence() > latestTombstone.getSequence()) { + emitQueue.add(latestTombstone.toMergedKeyValue()); + emitQueue.add(latestValue.toMergedKeyValue()); + } else { + emitQueue.add(latestTombstone.toMergedKeyValue()); + } + } else if (latestValue != null) { + emitQueue.add(latestValue.toMergedKeyValue()); + } else if (latestTombstone != null) { + emitQueue.add(latestTombstone.toMergedKeyValue()); + } + } + + private boolean hasUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey) { + return !heap.isEmpty() + && compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0; + } + + private DrainedVersion drainHeapForUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey, + boolean snapshotValueWinners) throws IOException { + MergeHead latest = null; + long latestSeq = -1L; + + while (true) { + List<HeapEntry> polled = new ArrayList<>(); + while (!heap.isEmpty() + && compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0) { + HeapEntry entry = heap.poll(); + if (entry.current.getSequence() > latestSeq) { + latest = entry.current; + latestSeq = entry.current.getSequence(); + } + polled.add(entry); + } + if (polled.isEmpty()) { + break; + } + for (HeapEntry entry : polled) { + if (snapshotValueWinners && entry.current == latest + && entry.current instanceof RawSstHeapHead + && !entry.nextRecordHasSameUserKey(userKey)) { + ((RawSstHeapHead) entry.current).snapshotValue(); + } Review Comment: Hmm this still leaves the raw value buffer live across entry.advance() when the next native record has the same user key? If one SST has multiple versions of the same key, the higher-sequence value can remain the winner, but advancing to the lower-sequence record reuses the same CodecBuffer before the winner is emitted. Can we copy the value for the current winner before every advance, or just copy value bytes in RawSstIterator.next()? -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
