You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by "SaketaChalamchala (via GitHub)" <gi...@apache.org> on 2026/06/10 18:59:31 UTC

[PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

SaketaChalamchala opened a new pull request, #10484:
URL: https://github.com/apache/ozone/pull/10484

   ## What changes were proposed in this pull request?
   
   Developed with the help of Cursor AI.
   
   This PR adds a k-way merge iterator over native RocksDB SST reader/iterator in `hadoop-hdds/rocks-native` module that emits the latest value and/or the latest tombstone per key.
   This PR intended as the foundation for a more efficient snapshot diff ([HDDS-9154](https://issues.apache.org/jira/browse/HDDS-9154)) where the diff can be calculated directly from the delta set of SST files instead of doing a random lookup from the target snapshot.
   
   - `VersionedKWayMergeIterator` performs a dual-heap k-way merge over multiple SST file iterators:
       - A value heap for non-tombstone entries
       - A tombstone heap for delete/tombstone entries
       - For each user key, the iterator drains all versions from both heaps, tracks the highest-sequence value and tombstone, then delegates emission to a pluggable `VersionedMergeEmitter`. Heap ordering and user-key grouping are controlled by `VersionedMergeComparators`.
       - Deferred value copying: raw SST heap heads hold CodecBuffer references and copy on emit.
   - `LatestVersionMergeComparators` implements `VersionedMergeComparators` — user key ascending, sequence descending (newest rocksDB entry first)
   - `LatestVersionMergeEmitter` implements  `VersionedMergeEmitter` — emission rules:
       - `valueSeq > tombstoneSeq` → emit both (delete→recreate)
       - `tombstoneSeq >= valueSeq` → emit tombstone only
       - value-only or tombstone-only otherwise
   
   ## What is the link to the Apache JIRA
   
   https://issues.apache.org/jira/browse/HDDS-15388
   
   ## How was this patch tested?
   
   Unit Tests.
   


-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3555329925


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,553 @@
+/*
+ * 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));
+    }

Review Comment:
   Good catch. I made this change in the latest update.



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,553 @@
+/*
+ * 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);
+    }

Review Comment:
   Done.



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3397426870


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/VersionedMergeComparators.java:
##########


Review Comment:
   Can this PR be simplified to a single-purpose raw-SST merge iterator? Right now it adds a bunch of generic interfaces that are only used by this like VersionedMergeComparators, VersionedMergeEmitter, VersionedMergeEntry, etc.
   
   Something like one PriorityQueue, one byte[] comparator, and one private method to choose the latest value/tombstone should be much smaller and easier to review.



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/VersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.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;
+
+/**
+ * Generic dual-heap k-way merge over versioned key streams.
+ * <p>
+ * Two heaps track non-tombstones and tombstones separately. For each user key,
+ * all versions are drained from both heaps, then {@link VersionedMergeEmitter}
+ * decides what to output. {@link VersionedMergeComparators} controls user-key
+ * grouping and heap ordering.
+ * <p>
+ * Snapshot diff uses {@link LatestVersionMergeComparators} and
+ * {@link LatestVersionMergeEmitter} to capture delete-recreate patterns.
+ */
+public final class VersionedKWayMergeIterator implements ClosableIterator<VersionedKWayMergeIterator.MergedKeyValue> {
+
+  public static final int ROCKS_TYPE_VALUE = VersionedMergeEntry.ROCKS_TYPE_VALUE;
+  private static final int DEFAULT_READ_AHEAD_SIZE = 2 * 1024 * 1024;
+
+  private final ManagedOptions options;
+  private final List<ClosableIterator<? extends VersionedMergeEntry>> iterators;
+  private final VersionedMergeComparators comparators;
+  private final VersionedMergeEmitter emitter;
+
+  private final PriorityQueue<HeapEntry> valueHeap;
+  private final PriorityQueue<HeapEntry> tombstoneHeap;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles)
+      throws IOException {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) throws IOException {
+    return overRawSstFiles(sstFiles, readAheadSizePerFile,
+        LatestVersionMergeComparators.INSTANCE, LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile, VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) throws IOException {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    Objects.requireNonNull(comparators, "comparators cannot be null");
+    Objects.requireNonNull(emitter, "emitter cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(sstFiles.size());
+    for (Path file : sstFiles) {
+      sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+    }
+    return new VersionedKWayMergeIterator(options, sources, comparators, emitter);
+  }
+
+  @VisibleForTesting
+  VersionedKWayMergeIterator(List<ClosableIterator<? extends VersionedMergeEntry>> iterators) {
+    this(null, iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators) {
+    return forTest(iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators,
+      VersionedMergeComparators comparators, VersionedMergeEmitter emitter) {
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(iterators.size());
+    sources.addAll(iterators);
+    return new VersionedKWayMergeIterator(null, sources, comparators, emitter);
+  }
+
+  private VersionedKWayMergeIterator(
+      ManagedOptions options,
+      List<ClosableIterator<? extends VersionedMergeEntry>> iterators,
+      VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) {
+    this.options = options;
+    this.iterators = new ArrayList<>(Objects.requireNonNull(iterators, "iterators cannot be null"));
+    this.comparators = Objects.requireNonNull(comparators, "comparators cannot be null");
+    this.emitter = Objects.requireNonNull(emitter, "emitter cannot be null");
+    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 = comparators.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();
+    }
+
+    VersionedMergeEntry latestValue = null;
+    long latestValueSeq = -1L;
+    VersionedMergeEntry latestTombstone = null;
+    long latestTombstoneSeq = -1L;
+
+    while (hasUserKey(valueHeap, nextKey) || hasUserKey(tombstoneHeap, nextKey)) {
+      DrainedVersion valueRound = drainHeapForUserKey(valueHeap, nextKey);
+      if (valueRound.entry != null && valueRound.sequence > latestValueSeq) {
+        latestValue = valueRound.entry;
+        latestValueSeq = valueRound.sequence;
+      }
+      DrainedVersion tombstoneRound = drainHeapForUserKey(tombstoneHeap, nextKey);
+      if (tombstoneRound.entry != null && tombstoneRound.sequence > latestTombstoneSeq) {
+        latestTombstone = tombstoneRound.entry;
+        latestTombstoneSeq = tombstoneRound.sequence;
+      }
+    }
+
+    emitter.emit(latestValue, latestTombstone, emitQueue);
+  }
+
+  private boolean hasUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey) {
+    return !heap.isEmpty()
+        && comparators.compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0;
+  }
+
+  private DrainedVersion drainHeapForUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey)
+      throws IOException {
+    VersionedMergeEntry latest = null;
+    long latestSeq = -1L;
+
+    while (true) {
+      List<HeapEntry> polled = new ArrayList<>();
+      while (!heap.isEmpty()
+          && comparators.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) {
+        entry.advance();
+        if (entry.current != null) {
+          offerToHeap(entry);
+        }
+      }
+    }
+
+    return new DrainedVersion(latest, latestSeq);
+  }
+
+  private void offerToHeap(HeapEntry entry) {
+    if (entry.current.isTombstone()) {
+      tombstoneHeap.offer(entry);
+    } else {
+      valueHeap.offer(entry);
+    }
+  }
+
+  private void initHeaps() throws IOException {
+    for (int idx = 0; idx < iterators.size(); idx++) {
+      ClosableIterator<? extends VersionedMergeEntry> iterator = iterators.get(idx);
+      HeapEntry entry = new HeapEntry(idx, iterator);
+      if (entry.current != null) {
+        offerToHeap(entry);
+      }
+    }
+  }
+
+  @Override
+  public void close() {
+    IOUtils.closeQuietly(iterators);
+    if (options != null) {
+      options.close();
+    }
+  }
+
+  static MergedKeyValue toMergedKeyValue(VersionedMergeEntry entry) {
+    if (entry instanceof MergedKeyValue) {
+      return (MergedKeyValue) entry;
+    }
+    if (entry instanceof RawSstHeapHead) {
+      return ((RawSstHeapHead) entry).toMergedKeyValue();
+    }
+    throw new IllegalStateException("Unexpected entry type: " + entry.getClass());
+  }
+
+  private static final class RawSstHeapHead implements VersionedMergeEntry {
+    private final byte[] key;
+    private final long sequence;
+    private final int type;
+    private final CodecBuffer valueBuffer;
+
+    RawSstHeapHead(byte[] key, long sequence, int type, CodecBuffer valueBuffer) {
+      this.key = Objects.requireNonNull(key, "key cannot be null");
+      this.sequence = sequence;
+      this.type = type;
+      this.valueBuffer = valueBuffer;
+    }
+
+    @Override
+    public byte[] getUserKey() {
+      return key;
+    }
+
+    @Override
+    public long getSequence() {
+      return sequence;
+    }
+
+    @Override
+    public int getValueType() {
+      return type;
+    }
+
+    MergedKeyValue toMergedKeyValue() {
+      byte[] value = null;
+      if (!isTombstone() && valueBuffer != null) {
+        value = copyBuffer(valueBuffer);
+      }
+      return new MergedKeyValue(key, UnsignedLong.fromLongBits(sequence), type, value);
+    }
+  }
+
+  private static final class DrainedVersion {
+    private final VersionedMergeEntry entry;
+    private final long sequence;
+
+    private DrainedVersion(VersionedMergeEntry entry, long sequence) {
+      this.entry = entry;
+      this.sequence = sequence;
+    }
+  }
+
+  private final class HeapEntry implements Comparable<HeapEntry> {
+    private final int index;
+    private final ClosableIterator<? extends VersionedMergeEntry> iterator;
+    private VersionedMergeEntry current;
+
+    private HeapEntry(int index, ClosableIterator<? extends VersionedMergeEntry> iterator)
+        throws IOException {
+      this.index = index;
+      this.iterator = iterator;
+      advance();
+    }
+
+    private void advance() throws IOException {
+      if (iterator.hasNext()) {
+        current = iterator.next();
+      } else {
+        current = null;
+        iterator.close();
+      }
+    }
+
+    @Override
+    public int compareTo(HeapEntry other) {
+      return comparators.compareHeapOrder(
+          this.current, this.index, other.current, other.index);
+    }
+  }
+
+  private static final class RawSstIterator implements ClosableIterator<RawSstHeapHead> {
+    private final ManagedRawSSTFileReader reader;
+    private final ManagedRawSSTFileIterator<ManagedRawSSTFileIterator.KeyValue> iterator;
+
+    private RawSstIterator(ManagedOptions options, Path file, int readAheadSize) {
+      this.reader = new ManagedRawSSTFileReader(
+          options, file.toAbsolutePath().toString(), readAheadSize);
+      this.iterator = reader.newIterator(kv -> kv, null, null, IteratorType.KEY_AND_VALUE);
+    }
+
+    @Override
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    @Override
+    public RawSstHeapHead next() {
+      ManagedRawSSTFileIterator.KeyValue keyValue = iterator.next();
+      int type = keyValue.getType();
+      CodecBuffer valueBuffer = type == ROCKS_TYPE_VALUE ? keyValue.getValue() : null;

Review Comment:
   This stores the CodecBuffer from ManagedRawSSTFileIterator in a RawSstHeapHead, but drainHeapForUserKey() can call entry.advance() before toMergedKeyValue() copies the value. The key is copied immediately, while the value is copied later, after the underlying iterator may have reused or released the buffer. Should RawSstIterator.next() copy the value bytes before creating RawSstHeapHead?



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/VersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.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;
+
+/**
+ * Generic dual-heap k-way merge over versioned key streams.
+ * <p>
+ * Two heaps track non-tombstones and tombstones separately. For each user key,
+ * all versions are drained from both heaps, then {@link VersionedMergeEmitter}
+ * decides what to output. {@link VersionedMergeComparators} controls user-key
+ * grouping and heap ordering.
+ * <p>
+ * Snapshot diff uses {@link LatestVersionMergeComparators} and
+ * {@link LatestVersionMergeEmitter} to capture delete-recreate patterns.
+ */
+public final class VersionedKWayMergeIterator implements ClosableIterator<VersionedKWayMergeIterator.MergedKeyValue> {
+
+  public static final int ROCKS_TYPE_VALUE = VersionedMergeEntry.ROCKS_TYPE_VALUE;
+  private static final int DEFAULT_READ_AHEAD_SIZE = 2 * 1024 * 1024;
+
+  private final ManagedOptions options;
+  private final List<ClosableIterator<? extends VersionedMergeEntry>> iterators;
+  private final VersionedMergeComparators comparators;
+  private final VersionedMergeEmitter emitter;
+
+  private final PriorityQueue<HeapEntry> valueHeap;
+  private final PriorityQueue<HeapEntry> tombstoneHeap;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles)
+      throws IOException {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) throws IOException {
+    return overRawSstFiles(sstFiles, readAheadSizePerFile,
+        LatestVersionMergeComparators.INSTANCE, LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile, VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) throws IOException {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    Objects.requireNonNull(comparators, "comparators cannot be null");
+    Objects.requireNonNull(emitter, "emitter cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(sstFiles.size());
+    for (Path file : sstFiles) {
+      sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+    }
+    return new VersionedKWayMergeIterator(options, sources, comparators, emitter);
+  }
+
+  @VisibleForTesting
+  VersionedKWayMergeIterator(List<ClosableIterator<? extends VersionedMergeEntry>> iterators) {
+    this(null, iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators) {
+    return forTest(iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators,
+      VersionedMergeComparators comparators, VersionedMergeEmitter emitter) {
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(iterators.size());
+    sources.addAll(iterators);
+    return new VersionedKWayMergeIterator(null, sources, comparators, emitter);
+  }
+
+  private VersionedKWayMergeIterator(
+      ManagedOptions options,
+      List<ClosableIterator<? extends VersionedMergeEntry>> iterators,
+      VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) {
+    this.options = options;
+    this.iterators = new ArrayList<>(Objects.requireNonNull(iterators, "iterators cannot be null"));
+    this.comparators = Objects.requireNonNull(comparators, "comparators cannot be null");
+    this.emitter = Objects.requireNonNull(emitter, "emitter cannot be null");
+    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 = comparators.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();
+    }
+
+    VersionedMergeEntry latestValue = null;
+    long latestValueSeq = -1L;
+    VersionedMergeEntry latestTombstone = null;
+    long latestTombstoneSeq = -1L;
+
+    while (hasUserKey(valueHeap, nextKey) || hasUserKey(tombstoneHeap, nextKey)) {
+      DrainedVersion valueRound = drainHeapForUserKey(valueHeap, nextKey);
+      if (valueRound.entry != null && valueRound.sequence > latestValueSeq) {
+        latestValue = valueRound.entry;
+        latestValueSeq = valueRound.sequence;
+      }
+      DrainedVersion tombstoneRound = drainHeapForUserKey(tombstoneHeap, nextKey);
+      if (tombstoneRound.entry != null && tombstoneRound.sequence > latestTombstoneSeq) {
+        latestTombstone = tombstoneRound.entry;
+        latestTombstoneSeq = tombstoneRound.sequence;
+      }
+    }
+
+    emitter.emit(latestValue, latestTombstone, emitQueue);
+  }
+
+  private boolean hasUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey) {
+    return !heap.isEmpty()
+        && comparators.compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0;
+  }
+
+  private DrainedVersion drainHeapForUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey)
+      throws IOException {
+    VersionedMergeEntry latest = null;
+    long latestSeq = -1L;
+
+    while (true) {
+      List<HeapEntry> polled = new ArrayList<>();
+      while (!heap.isEmpty()
+          && comparators.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) {
+        entry.advance();
+        if (entry.current != null) {
+          offerToHeap(entry);
+        }
+      }
+    }
+
+    return new DrainedVersion(latest, latestSeq);
+  }
+
+  private void offerToHeap(HeapEntry entry) {
+    if (entry.current.isTombstone()) {
+      tombstoneHeap.offer(entry);
+    } else {
+      valueHeap.offer(entry);
+    }
+  }
+
+  private void initHeaps() throws IOException {
+    for (int idx = 0; idx < iterators.size(); idx++) {
+      ClosableIterator<? extends VersionedMergeEntry> iterator = iterators.get(idx);
+      HeapEntry entry = new HeapEntry(idx, iterator);
+      if (entry.current != null) {
+        offerToHeap(entry);
+      }
+    }
+  }
+
+  @Override
+  public void close() {
+    IOUtils.closeQuietly(iterators);
+    if (options != null) {
+      options.close();
+    }
+  }
+
+  static MergedKeyValue toMergedKeyValue(VersionedMergeEntry entry) {
+    if (entry instanceof MergedKeyValue) {
+      return (MergedKeyValue) entry;
+    }
+    if (entry instanceof RawSstHeapHead) {
+      return ((RawSstHeapHead) entry).toMergedKeyValue();
+    }
+    throw new IllegalStateException("Unexpected entry type: " + entry.getClass());
+  }
+
+  private static final class RawSstHeapHead implements VersionedMergeEntry {
+    private final byte[] key;
+    private final long sequence;
+    private final int type;
+    private final CodecBuffer valueBuffer;
+
+    RawSstHeapHead(byte[] key, long sequence, int type, CodecBuffer valueBuffer) {
+      this.key = Objects.requireNonNull(key, "key cannot be null");
+      this.sequence = sequence;
+      this.type = type;
+      this.valueBuffer = valueBuffer;
+    }
+
+    @Override
+    public byte[] getUserKey() {
+      return key;
+    }
+
+    @Override
+    public long getSequence() {
+      return sequence;
+    }
+
+    @Override
+    public int getValueType() {
+      return type;
+    }
+
+    MergedKeyValue toMergedKeyValue() {
+      byte[] value = null;
+      if (!isTombstone() && valueBuffer != null) {
+        value = copyBuffer(valueBuffer);
+      }
+      return new MergedKeyValue(key, UnsignedLong.fromLongBits(sequence), type, value);
+    }
+  }
+
+  private static final class DrainedVersion {
+    private final VersionedMergeEntry entry;
+    private final long sequence;
+
+    private DrainedVersion(VersionedMergeEntry entry, long sequence) {
+      this.entry = entry;
+      this.sequence = sequence;
+    }
+  }
+
+  private final class HeapEntry implements Comparable<HeapEntry> {
+    private final int index;
+    private final ClosableIterator<? extends VersionedMergeEntry> iterator;
+    private VersionedMergeEntry current;
+
+    private HeapEntry(int index, ClosableIterator<? extends VersionedMergeEntry> iterator)
+        throws IOException {
+      this.index = index;
+      this.iterator = iterator;
+      advance();
+    }
+
+    private void advance() throws IOException {
+      if (iterator.hasNext()) {
+        current = iterator.next();
+      } else {
+        current = null;
+        iterator.close();

Review Comment:
   This closes the iterator when it's exhausted, but VersionedKWayMergeIterator.close() closes the same iterators again. RawSstIterator.close() calls native close paths and does not guard against repeated calls. Can we either make RawSstIterator.close() idempotent, or stop closing exhausted iterators a second time?



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3463430814


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/VersionedMergeComparators.java:
##########


Review Comment:
   Done



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3532932903


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,545 @@
+/*
+ * 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.

Review Comment:
   Is dual-heap needed? Single heap could achieve the same goal IIUC?



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3532866887


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,553 @@
+/*
+ * 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);
+    }

Review Comment:
   It looks to me `throws IOException` on advance() , processNextUserKey() , drainHeapForUserKey() , initHeaps() and on HeapEntry constructor are unnecessary. And then this can be simplified to:
   
   ```suggestion
       return advance()
   ```



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3555334628


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,545 @@
+/*
+ * 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.

Review Comment:
   Yes, since we drain all the entries of a key we can use a single heap to track the latest value and latest tombstone. This would make the patch less verbose. I made the change in the latest commit. Please review.



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3556052340


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,495 @@
+/*
+ * 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.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;
+
+/**
+ * K-way merge over RocksDB SST files for snapshot diff.
+ * <p>
+ * A single min-heap orders source heads by user key. For each user key, all versions
+ * are drained and the latest value and latest tombstone are tracked, 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> sourceHeads;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles) {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE, null);
+  }
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) {
+    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) {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends MergeHead>> sources = new ArrayList<>(sstFiles.size());
+    try {
+      for (Path file : sstFiles) {
+        sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+      }
+      return new LatestVersionedKWayMergeIterator(options, sources, exclusiveMinSequenceNumber);
+    } catch (RuntimeException e) {
+      IOUtils.closeQuietly(sources);
+      options.close();
+      throw e;
+    }
+  }
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      long exclusiveMinSequenceNumber) {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE, exclusiveMinSequenceNumber);
+  }
+
+  @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.sourceHeads = new PriorityQueue<>(Math.max(this.iterators.size(), 1));
+    this.emitQueue = new ArrayList<>();
+  }
+
+  @Override
+  public boolean hasNext() {
+    if (!emitQueue.isEmpty()) {
+      return true;
+    }
+    return advance();
+  }
+
+  @Override
+  public MergedKeyValue next() {
+    if (!hasNext()) {
+      throw new NoSuchElementException("No more elements found.");
+    }
+    return emitQueue.remove(0);
+  }
+
+  private boolean advance() {
+    if (!initialized) {
+      initHeap();
+      initialized = true;
+    }
+
+    while (emitQueue.isEmpty() && !sourceHeads.isEmpty()) {
+      processNextUserKey();
+    }
+
+    return !emitQueue.isEmpty();
+  }
+
+  private void processNextUserKey() {
+    if (sourceHeads.isEmpty()) {
+      return;
+    }
+
+    byte[] nextKey = sourceHeads.peek().current.getUserKey();
+    MergeHead latestValue = null;
+    long latestValueSeq = -1L;
+    MergeHead latestTombstone = null;
+    long latestTombstoneSeq = -1L;
+
+    while (heapHasUserKey(nextKey)) {
+      List<HeapEntry> polled = new ArrayList<>();
+      while (heapHasUserKey(nextKey)) {
+        HeapEntry entry = sourceHeads.poll();
+        MergeHead head = entry.current;
+        if (head.isTombstone()) {
+          if (head.getSequence() > latestTombstoneSeq) {
+            latestTombstone = head;
+            latestTombstoneSeq = head.getSequence();
+          }
+        } else if (head.getSequence() > latestValueSeq) {
+          latestValue = head;
+          latestValueSeq = head.getSequence();
+        }
+        polled.add(entry);
+      }
+      for (HeapEntry entry : polled) {
+        if (entry.current == latestValue && entry.current instanceof RawSstHeapHead) {
+          ((RawSstHeapHead) entry.current).snapshotValue();
+        }
+        entry.advance();
+        if (entry.current != null) {
+          sourceHeads.offer(entry);
+        }
+      }
+    }
+
+    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 heapHasUserKey(byte[] userKey) {
+    return !sourceHeads.isEmpty()
+        && compareUserKeys(sourceHeads.peek().current.getUserKey(), userKey) == 0;
+  }
+
+  private void initHeap() {
+    for (int idx = 0; idx < iterators.size(); idx++) {
+      ClosableIterator<? extends MergeHead> iterator = iterators.get(idx);
+      HeapEntry entry = new HeapEntry(idx, iterator);
+      if (entry.current != null) {
+        sourceHeads.offer(entry);
+      }
+    }
+  }
+
+  @Override
+  public void close() {
+    IOUtils.closeQuietly(iterators);
+    if (options != null) {
+      options.close();
+    }
+  }
+
+  private static int compareUserKeys(byte[] left, byte[] right) {
+    if (left == right) {
+      return 0;
+    }
+    if (left == null) {
+      return -1;
+    }
+    if (right == null) {
+      return 1;
+    }
+    int minLength = Math.min(left.length, right.length);
+    for (int i = 0; i < minLength; i++) {
+      int l = left[i] & 0xff;
+      int r = right[i] & 0xff;
+      if (l != r) {
+        return Integer.compare(l, r);
+      }
+    }
+    return Integer.compare(left.length, right.length);
+  }
+
+  private static int compareHeapOrder(MergeHead left, int leftIndex,
+      MergeHead right, int rightIndex) {
+    int keyCompare = compareUserKeys(left.getUserKey(), right.getUserKey());
+    if (keyCompare != 0) {
+      return keyCompare;
+    }
+    int seqCompare = Long.compare(right.getSequence(), left.getSequence());
+    if (seqCompare != 0) {
+      return seqCompare;
+    }
+    int tombstoneCompare = Boolean.compare(right.isTombstone(), left.isTombstone());
+    if (tombstoneCompare != 0) {
+      return tombstoneCompare;
+    }
+    return Integer.compare(leftIndex, rightIndex);
+  }
+
+  private interface MergeHead {
+    byte[] getUserKey();
+
+    long getSequence();
+
+    boolean isTombstone();
+
+    MergedKeyValue toMergedKeyValue();
+  }
+
+  private static final class RawSstHeapHead implements MergeHead {
+    private final byte[] key;
+    private final long sequence;
+    private final int type;
+    private final CodecBuffer valueBuffer;
+    private byte[] snapshottedValue;
+
+    RawSstHeapHead(byte[] key, long sequence, int type, CodecBuffer valueBuffer) {
+      this.key = Objects.requireNonNull(key, "key cannot be null");
+      this.sequence = sequence;
+      this.type = type;
+      this.valueBuffer = valueBuffer;
+    }
+
+    void snapshotValue() {
+      if (snapshottedValue != null || isTombstone() || valueBuffer == null) {
+        return;
+      }
+      snapshottedValue = copyBuffer(valueBuffer);
+    }
+
+    @Override
+    public byte[] getUserKey() {
+      return key;
+    }
+
+    @Override
+    public long getSequence() {
+      return sequence;
+    }
+
+    @Override
+    public boolean isTombstone() {
+      return type != ROCKS_TYPE_VALUE;
+    }
+
+    @Override
+    public MergedKeyValue toMergedKeyValue() {
+      byte[] value = snapshottedValue;
+      if (value == null && !isTombstone() && valueBuffer != null) {
+        value = copyBuffer(valueBuffer);
+      }
+      return new MergedKeyValue(key, UnsignedLong.fromLongBits(sequence), type, value);
+    }
+  }
+
+  private final class HeapEntry implements Comparable<HeapEntry> {
+    private final int index;
+    private final ClosableIterator<? extends MergeHead> iterator;
+    private MergeHead current;
+
+    private HeapEntry(int index, ClosableIterator<? extends MergeHead> iterator) {
+      this.index = index;
+      this.iterator = iterator;
+      advance();
+    }
+
+    private void advance() {
+      while (true) {
+        if (!iterator.hasNext()) {
+          current = null;
+          iterator.close();
+          return;
+        }
+        MergeHead next = iterator.next();
+        if (exclusiveMinSequenceNumber == null
+            || next.getSequence() > exclusiveMinSequenceNumber) {
+          current = next;
+          return;
+        }
+      }
+    }
+
+    @Override
+    public int compareTo(HeapEntry other) {
+      return compareHeapOrder(
+          this.current, this.index, other.current, other.index);
+    }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) {
+        return true;
+      }
+      if (!(o instanceof HeapEntry)) {
+        return false;
+      }
+      HeapEntry other = (HeapEntry) o;
+      return index == other.index;
+    }
+
+    @Override
+    public int hashCode() {
+      return index;
+    }
+  }
+
+  private static final class RawSstIterator implements ClosableIterator<RawSstHeapHead> {
+    private final ManagedRawSSTFileReader reader;
+    private final ManagedRawSSTFileIterator<ManagedRawSSTFileIterator.KeyValue> iterator;
+    private boolean closed;
+
+    private RawSstIterator(ManagedOptions options, Path file, int readAheadSize) {
+      this.reader = new ManagedRawSSTFileReader(
+          options, file.toAbsolutePath().toString(), readAheadSize);
+      this.iterator = reader.newIterator(kv -> kv, null, null, IteratorType.KEY_AND_VALUE);

Review Comment:
   If newIterator() throws, `this.reader` was created but this RawSstIterator never gets added to sources, so the catch in `overRawSstFiles` won't close it and the native reader handle leaks.
   
   ```suggestion
         ManagedRawSSTFileReader r = new ManagedRawSSTFileReader(options,       file.toAbsolutePath().toString(), readAheadSize);
         try {
           this.iterator = r.newIterator(kv -> kv, null, null, IteratorType.KEY_AND_VALUE);
         } catch (RuntimeException e) {
           r.close();
           throw e;
         }
         this.reader = r;
   ```



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/ManagedRawSSTFileIterator.java:
##########
@@ -81,6 +81,24 @@ public T next() {
     return this.transformer.apply(keyValue);
   }
 
+  /**
+   * Reads the key at the current native iterator position without advancing.
+   * After {@link #next()}, this is the key of the next record to be returned.
+   */
+  byte[] peekKeyBytes() {
+    if (!hasNext() || !type.readKey()) {
+      return null;
+    }
+    CodecBuffer key = keyBuffer.getFromDb();
+    if (key == null) {
+      return null;
+    }
+    ByteBuffer byteBuffer = key.asReadOnlyByteBuffer();
+    byte[] bytes = new byte[byteBuffer.remaining()];
+    byteBuffer.get(bytes);
+    return bytes;
+  }
+

Review Comment:
   dead code?
   
   ```suggestion
   ```



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,495 @@
+/*
+ * 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.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;
+
+/**
+ * K-way merge over RocksDB SST files for snapshot diff.
+ * <p>
+ * A single min-heap orders source heads by user key. For each user key, all versions
+ * are drained and the latest value and latest tombstone are tracked, 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> sourceHeads;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles) {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE, null);
+  }
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) {
+    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) {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends MergeHead>> sources = new ArrayList<>(sstFiles.size());
+    try {
+      for (Path file : sstFiles) {
+        sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+      }
+      return new LatestVersionedKWayMergeIterator(options, sources, exclusiveMinSequenceNumber);
+    } catch (RuntimeException e) {
+      IOUtils.closeQuietly(sources);
+      options.close();
+      throw e;
+    }
+  }
+
+  public static LatestVersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      long exclusiveMinSequenceNumber) {

Review Comment:
   Consider a different name for this overload to differentiate from the `overRawSstFiles(Collection, int)` above to avoid accidental misuse
   
   ```suggestion
     public static LatestVersionedKWayMergeIterator overRawSstFilesFromSequence(Collection<Path> sstFiles,
         long exclusiveMinSequenceNumber) {
   ```



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3532817118


##########
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:
   nextRecordHasSameUserKey is now unused. it is failing CI pmd:
   
   https://github.com/SaketaChalamchala/ozone/actions/runs/28824554990/job/85484385738
   
   should the helper be removed?



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala merged PR #10484:
URL: https://github.com/apache/ozone/pull/10484


-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3463434885


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.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;
+
+/**
+ * Generic dual-heap k-way merge over versioned key streams.
+ * <p>
+ * Two heaps track non-tombstones and tombstones separately. For each user key,
+ * all versions are drained from both heaps, then {@link VersionedMergeEmitter}
+ * decides what to output. {@link VersionedMergeComparators} controls user-key
+ * grouping and heap ordering.
+ * <p>
+ * Snapshot diff uses {@link LatestVersionMergeComparators} and
+ * {@link LatestVersionMergeEmitter} to capture delete-recreate patterns.
+ */
+public final class VersionedKWayMergeIterator implements ClosableIterator<VersionedKWayMergeIterator.MergedKeyValue> {
+
+  public static final int ROCKS_TYPE_VALUE = VersionedMergeEntry.ROCKS_TYPE_VALUE;
+  private static final int DEFAULT_READ_AHEAD_SIZE = 2 * 1024 * 1024;
+
+  private final ManagedOptions options;
+  private final List<ClosableIterator<? extends VersionedMergeEntry>> iterators;
+  private final VersionedMergeComparators comparators;
+  private final VersionedMergeEmitter emitter;
+
+  private final PriorityQueue<HeapEntry> valueHeap;
+  private final PriorityQueue<HeapEntry> tombstoneHeap;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles)
+      throws IOException {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) throws IOException {
+    return overRawSstFiles(sstFiles, readAheadSizePerFile,
+        LatestVersionMergeComparators.INSTANCE, LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile, VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) throws IOException {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    Objects.requireNonNull(comparators, "comparators cannot be null");
+    Objects.requireNonNull(emitter, "emitter cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(sstFiles.size());
+    for (Path file : sstFiles) {
+      sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+    }
+    return new VersionedKWayMergeIterator(options, sources, comparators, emitter);
+  }
+
+  @VisibleForTesting
+  VersionedKWayMergeIterator(List<ClosableIterator<? extends VersionedMergeEntry>> iterators) {
+    this(null, iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators) {
+    return forTest(iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators,
+      VersionedMergeComparators comparators, VersionedMergeEmitter emitter) {
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(iterators.size());
+    sources.addAll(iterators);
+    return new VersionedKWayMergeIterator(null, sources, comparators, emitter);
+  }
+
+  private VersionedKWayMergeIterator(
+      ManagedOptions options,
+      List<ClosableIterator<? extends VersionedMergeEntry>> iterators,
+      VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) {
+    this.options = options;
+    this.iterators = new ArrayList<>(Objects.requireNonNull(iterators, "iterators cannot be null"));
+    this.comparators = Objects.requireNonNull(comparators, "comparators cannot be null");
+    this.emitter = Objects.requireNonNull(emitter, "emitter cannot be null");
+    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 = comparators.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();
+    }
+
+    VersionedMergeEntry latestValue = null;
+    long latestValueSeq = -1L;
+    VersionedMergeEntry latestTombstone = null;
+    long latestTombstoneSeq = -1L;
+
+    while (hasUserKey(valueHeap, nextKey) || hasUserKey(tombstoneHeap, nextKey)) {
+      DrainedVersion valueRound = drainHeapForUserKey(valueHeap, nextKey);
+      if (valueRound.entry != null && valueRound.sequence > latestValueSeq) {
+        latestValue = valueRound.entry;
+        latestValueSeq = valueRound.sequence;
+      }
+      DrainedVersion tombstoneRound = drainHeapForUserKey(tombstoneHeap, nextKey);
+      if (tombstoneRound.entry != null && tombstoneRound.sequence > latestTombstoneSeq) {
+        latestTombstone = tombstoneRound.entry;
+        latestTombstoneSeq = tombstoneRound.sequence;
+      }
+    }
+
+    emitter.emit(latestValue, latestTombstone, emitQueue);
+  }
+
+  private boolean hasUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey) {
+    return !heap.isEmpty()
+        && comparators.compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0;
+  }
+
+  private DrainedVersion drainHeapForUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey)
+      throws IOException {
+    VersionedMergeEntry latest = null;
+    long latestSeq = -1L;
+
+    while (true) {
+      List<HeapEntry> polled = new ArrayList<>();
+      while (!heap.isEmpty()
+          && comparators.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) {
+        entry.advance();
+        if (entry.current != null) {
+          offerToHeap(entry);
+        }
+      }
+    }
+
+    return new DrainedVersion(latest, latestSeq);
+  }
+
+  private void offerToHeap(HeapEntry entry) {
+    if (entry.current.isTombstone()) {
+      tombstoneHeap.offer(entry);
+    } else {
+      valueHeap.offer(entry);
+    }
+  }
+
+  private void initHeaps() throws IOException {
+    for (int idx = 0; idx < iterators.size(); idx++) {
+      ClosableIterator<? extends VersionedMergeEntry> iterator = iterators.get(idx);
+      HeapEntry entry = new HeapEntry(idx, iterator);
+      if (entry.current != null) {
+        offerToHeap(entry);
+      }
+    }
+  }
+
+  @Override
+  public void close() {
+    IOUtils.closeQuietly(iterators);
+    if (options != null) {
+      options.close();
+    }
+  }
+
+  static MergedKeyValue toMergedKeyValue(VersionedMergeEntry entry) {
+    if (entry instanceof MergedKeyValue) {
+      return (MergedKeyValue) entry;
+    }
+    if (entry instanceof RawSstHeapHead) {
+      return ((RawSstHeapHead) entry).toMergedKeyValue();
+    }
+    throw new IllegalStateException("Unexpected entry type: " + entry.getClass());
+  }
+
+  private static final class RawSstHeapHead implements VersionedMergeEntry {
+    private final byte[] key;
+    private final long sequence;
+    private final int type;
+    private final CodecBuffer valueBuffer;
+
+    RawSstHeapHead(byte[] key, long sequence, int type, CodecBuffer valueBuffer) {
+      this.key = Objects.requireNonNull(key, "key cannot be null");
+      this.sequence = sequence;
+      this.type = type;
+      this.valueBuffer = valueBuffer;
+    }
+
+    @Override
+    public byte[] getUserKey() {
+      return key;
+    }
+
+    @Override
+    public long getSequence() {
+      return sequence;
+    }
+
+    @Override
+    public int getValueType() {
+      return type;
+    }
+
+    MergedKeyValue toMergedKeyValue() {
+      byte[] value = null;
+      if (!isTombstone() && valueBuffer != null) {
+        value = copyBuffer(valueBuffer);
+      }
+      return new MergedKeyValue(key, UnsignedLong.fromLongBits(sequence), type, value);
+    }
+  }
+
+  private static final class DrainedVersion {
+    private final VersionedMergeEntry entry;
+    private final long sequence;
+
+    private DrainedVersion(VersionedMergeEntry entry, long sequence) {
+      this.entry = entry;
+      this.sequence = sequence;
+    }
+  }
+
+  private final class HeapEntry implements Comparable<HeapEntry> {
+    private final int index;
+    private final ClosableIterator<? extends VersionedMergeEntry> iterator;
+    private VersionedMergeEntry current;
+
+    private HeapEntry(int index, ClosableIterator<? extends VersionedMergeEntry> iterator)
+        throws IOException {
+      this.index = index;
+      this.iterator = iterator;
+      advance();
+    }
+
+    private void advance() throws IOException {
+      if (iterator.hasNext()) {
+        current = iterator.next();
+      } else {
+        current = null;
+        iterator.close();
+      }
+    }
+
+    @Override
+    public int compareTo(HeapEntry other) {
+      return comparators.compareHeapOrder(
+          this.current, this.index, other.current, other.index);
+    }
+  }
+
+  private static final class RawSstIterator implements ClosableIterator<RawSstHeapHead> {
+    private final ManagedRawSSTFileReader reader;
+    private final ManagedRawSSTFileIterator<ManagedRawSSTFileIterator.KeyValue> iterator;
+
+    private RawSstIterator(ManagedOptions options, Path file, int readAheadSize) {
+      this.reader = new ManagedRawSSTFileReader(
+          options, file.toAbsolutePath().toString(), readAheadSize);
+      this.iterator = reader.newIterator(kv -> kv, null, null, IteratorType.KEY_AND_VALUE);
+    }
+
+    @Override
+    public boolean hasNext() {
+      return iterator.hasNext();
+    }
+
+    @Override
+    public RawSstHeapHead next() {
+      ManagedRawSSTFileIterator.KeyValue keyValue = iterator.next();
+      int type = keyValue.getType();
+      CodecBuffer valueBuffer = type == ROCKS_TYPE_VALUE ? keyValue.getValue() : null;

Review Comment:
   Made the change to copy the value buffer for the winner candidates before entries are advanced for each SST file. 



##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,432 @@
+/*
+ * 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.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;
+
+/**
+ * Generic dual-heap k-way merge over versioned key streams.
+ * <p>
+ * Two heaps track non-tombstones and tombstones separately. For each user key,
+ * all versions are drained from both heaps, then {@link VersionedMergeEmitter}
+ * decides what to output. {@link VersionedMergeComparators} controls user-key
+ * grouping and heap ordering.
+ * <p>
+ * Snapshot diff uses {@link LatestVersionMergeComparators} and
+ * {@link LatestVersionMergeEmitter} to capture delete-recreate patterns.
+ */
+public final class VersionedKWayMergeIterator implements ClosableIterator<VersionedKWayMergeIterator.MergedKeyValue> {
+
+  public static final int ROCKS_TYPE_VALUE = VersionedMergeEntry.ROCKS_TYPE_VALUE;
+  private static final int DEFAULT_READ_AHEAD_SIZE = 2 * 1024 * 1024;
+
+  private final ManagedOptions options;
+  private final List<ClosableIterator<? extends VersionedMergeEntry>> iterators;
+  private final VersionedMergeComparators comparators;
+  private final VersionedMergeEmitter emitter;
+
+  private final PriorityQueue<HeapEntry> valueHeap;
+  private final PriorityQueue<HeapEntry> tombstoneHeap;
+
+  private List<MergedKeyValue> emitQueue;
+  private boolean initialized;
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles)
+      throws IOException {
+    return overRawSstFiles(sstFiles, DEFAULT_READ_AHEAD_SIZE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile) throws IOException {
+    return overRawSstFiles(sstFiles, readAheadSizePerFile,
+        LatestVersionMergeComparators.INSTANCE, LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  public static VersionedKWayMergeIterator overRawSstFiles(Collection<Path> sstFiles,
+      int readAheadSizePerFile, VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) throws IOException {
+    Objects.requireNonNull(sstFiles, "sstFiles cannot be null");
+    Objects.requireNonNull(comparators, "comparators cannot be null");
+    Objects.requireNonNull(emitter, "emitter cannot be null");
+    ManagedOptions options = new ManagedOptions();
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(sstFiles.size());
+    for (Path file : sstFiles) {
+      sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
+    }
+    return new VersionedKWayMergeIterator(options, sources, comparators, emitter);
+  }
+
+  @VisibleForTesting
+  VersionedKWayMergeIterator(List<ClosableIterator<? extends VersionedMergeEntry>> iterators) {
+    this(null, iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators) {
+    return forTest(iterators, LatestVersionMergeComparators.INSTANCE,
+        LatestVersionMergeEmitter.INSTANCE);
+  }
+
+  @VisibleForTesting
+  public static VersionedKWayMergeIterator forTest(
+      List<ClosableIterator<MergedKeyValue>> iterators,
+      VersionedMergeComparators comparators, VersionedMergeEmitter emitter) {
+    List<ClosableIterator<? extends VersionedMergeEntry>> sources = new ArrayList<>(iterators.size());
+    sources.addAll(iterators);
+    return new VersionedKWayMergeIterator(null, sources, comparators, emitter);
+  }
+
+  private VersionedKWayMergeIterator(
+      ManagedOptions options,
+      List<ClosableIterator<? extends VersionedMergeEntry>> iterators,
+      VersionedMergeComparators comparators,
+      VersionedMergeEmitter emitter) {
+    this.options = options;
+    this.iterators = new ArrayList<>(Objects.requireNonNull(iterators, "iterators cannot be null"));
+    this.comparators = Objects.requireNonNull(comparators, "comparators cannot be null");
+    this.emitter = Objects.requireNonNull(emitter, "emitter cannot be null");
+    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 = comparators.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();
+    }
+
+    VersionedMergeEntry latestValue = null;
+    long latestValueSeq = -1L;
+    VersionedMergeEntry latestTombstone = null;
+    long latestTombstoneSeq = -1L;
+
+    while (hasUserKey(valueHeap, nextKey) || hasUserKey(tombstoneHeap, nextKey)) {
+      DrainedVersion valueRound = drainHeapForUserKey(valueHeap, nextKey);
+      if (valueRound.entry != null && valueRound.sequence > latestValueSeq) {
+        latestValue = valueRound.entry;
+        latestValueSeq = valueRound.sequence;
+      }
+      DrainedVersion tombstoneRound = drainHeapForUserKey(tombstoneHeap, nextKey);
+      if (tombstoneRound.entry != null && tombstoneRound.sequence > latestTombstoneSeq) {
+        latestTombstone = tombstoneRound.entry;
+        latestTombstoneSeq = tombstoneRound.sequence;
+      }
+    }
+
+    emitter.emit(latestValue, latestTombstone, emitQueue);
+  }
+
+  private boolean hasUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey) {
+    return !heap.isEmpty()
+        && comparators.compareUserKeys(heap.peek().current.getUserKey(), userKey) == 0;
+  }
+
+  private DrainedVersion drainHeapForUserKey(PriorityQueue<HeapEntry> heap, byte[] userKey)
+      throws IOException {
+    VersionedMergeEntry latest = null;
+    long latestSeq = -1L;
+
+    while (true) {
+      List<HeapEntry> polled = new ArrayList<>();
+      while (!heap.isEmpty()
+          && comparators.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) {
+        entry.advance();
+        if (entry.current != null) {
+          offerToHeap(entry);
+        }
+      }
+    }
+
+    return new DrainedVersion(latest, latestSeq);
+  }
+
+  private void offerToHeap(HeapEntry entry) {
+    if (entry.current.isTombstone()) {
+      tombstoneHeap.offer(entry);
+    } else {
+      valueHeap.offer(entry);
+    }
+  }
+
+  private void initHeaps() throws IOException {
+    for (int idx = 0; idx < iterators.size(); idx++) {
+      ClosableIterator<? extends VersionedMergeEntry> iterator = iterators.get(idx);
+      HeapEntry entry = new HeapEntry(idx, iterator);
+      if (entry.current != null) {
+        offerToHeap(entry);
+      }
+    }
+  }
+
+  @Override
+  public void close() {
+    IOUtils.closeQuietly(iterators);
+    if (options != null) {
+      options.close();
+    }
+  }
+
+  static MergedKeyValue toMergedKeyValue(VersionedMergeEntry entry) {
+    if (entry instanceof MergedKeyValue) {
+      return (MergedKeyValue) entry;
+    }
+    if (entry instanceof RawSstHeapHead) {
+      return ((RawSstHeapHead) entry).toMergedKeyValue();
+    }
+    throw new IllegalStateException("Unexpected entry type: " + entry.getClass());
+  }
+
+  private static final class RawSstHeapHead implements VersionedMergeEntry {
+    private final byte[] key;
+    private final long sequence;
+    private final int type;
+    private final CodecBuffer valueBuffer;
+
+    RawSstHeapHead(byte[] key, long sequence, int type, CodecBuffer valueBuffer) {
+      this.key = Objects.requireNonNull(key, "key cannot be null");
+      this.sequence = sequence;
+      this.type = type;
+      this.valueBuffer = valueBuffer;
+    }
+
+    @Override
+    public byte[] getUserKey() {
+      return key;
+    }
+
+    @Override
+    public long getSequence() {
+      return sequence;
+    }
+
+    @Override
+    public int getValueType() {
+      return type;
+    }
+
+    MergedKeyValue toMergedKeyValue() {
+      byte[] value = null;
+      if (!isTombstone() && valueBuffer != null) {
+        value = copyBuffer(valueBuffer);
+      }
+      return new MergedKeyValue(key, UnsignedLong.fromLongBits(sequence), type, value);
+    }
+  }
+
+  private static final class DrainedVersion {
+    private final VersionedMergeEntry entry;
+    private final long sequence;
+
+    private DrainedVersion(VersionedMergeEntry entry, long sequence) {
+      this.entry = entry;
+      this.sequence = sequence;
+    }
+  }
+
+  private final class HeapEntry implements Comparable<HeapEntry> {
+    private final int index;
+    private final ClosableIterator<? extends VersionedMergeEntry> iterator;
+    private VersionedMergeEntry current;
+
+    private HeapEntry(int index, ClosableIterator<? extends VersionedMergeEntry> iterator)
+        throws IOException {
+      this.index = index;
+      this.iterator = iterator;
+      advance();
+    }
+
+    private void advance() throws IOException {
+      if (iterator.hasNext()) {
+        current = iterator.next();
+      } else {
+        current = null;
+        iterator.close();

Review Comment:
   Made close idempotent.



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "SaketaChalamchala (via GitHub)" <gi...@apache.org>.
SaketaChalamchala commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3532190272


##########
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:
   Thanks for catching this @smengcl. The `!entry.nextRecordHasSameUserKey(userKey)` conditional was not meant to be there.



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org


Re: [PR] HDDS-15388. K way merge iterator over native SST file reader to emit latest tombstone and latest value of a key. [ozone]

Posted by "smengcl (via GitHub)" <gi...@apache.org>.
smengcl commented on code in PR #10484:
URL: https://github.com/apache/ozone/pull/10484#discussion_r3532834266


##########
hadoop-hdds/rocks-native/src/main/java/org/apache/hadoop/hdds/utils/db/LatestVersionedKWayMergeIterator.java:
##########
@@ -0,0 +1,553 @@
+/*
+ * 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));
+    }

Review Comment:
   If new RawSstIterator() throws (e.g. due to missing/corrupt SST), those opened readers and options would leak. Can we wrap it with try-catch like:
   
   ```java
   try {
     for (Path file : sstFiles) {
       sources.add(new RawSstIterator(options, file, readAheadSizePerFile));
     }
   } catch (RuntimeException e) {
     IOUtils.closeQuietly(sources);
     options.close();
     throw e;
   }
   ```



-- 
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: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org