This is an automated email from the ASF dual-hosted git repository.

xiangfu0 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new ded2f9db9a4 Use mmap for final immutable HNSW merges by default 
(#20299)
ded2f9db9a4 is described below

commit ded2f9db9a42d24256f29890065e3d0ee2d5a5e8
Author: Xiang Fu <[email protected]>
AuthorDate: Wed Nov 18 16:41:18 2026 -0800

    Use mmap for final immutable HNSW merges by default (#20299)
    
    * Use mmap for final immutable HNSW merges by default
    
    * Reuse vector scores during mmap HNSW merges
---
 .../impl/vector/HnswVectorIndexCreator.java        |   6 +-
 .../impl/vector/lucene99/HnswVectorsFormat.java    |  18 +
 .../impl/vector/lucene99/MmapHnswGraph.java        | 223 ++++++++++++
 .../impl/vector/lucene99/MmapHnswGraphBuilder.java | 404 +++++++++++++++++++++
 .../impl/vector/lucene99/MmapHnswNeighborList.java | 159 ++++++++
 .../vector/lucene99/MmapHnswVectorsWriter.java     | 229 ++++++++++++
 .../local/segment/store/VectorIndexUtils.java      |   9 +-
 .../index/creator/HnswVectorIndexCreatorTest.java  | 127 +++++++
 .../spi/index/creator/VectorIndexConfig.java       |  11 +
 .../index/creator/VectorIndexConfigValidator.java  |   9 +-
 .../creator/VectorIndexConfigValidatorTest.java    |  23 +-
 11 files changed, 1211 insertions(+), 7 deletions(-)

diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java
index 9703ca7b5b9..9dfa861a000 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java
@@ -39,8 +39,7 @@ import org.slf4j.LoggerFactory;
 
 
 /// This is used to create Lucene based HNSW index.
-/// Used for both offline from 
[org.apache.pinot.segment.local.segment.creator.impl.SegmentColumnarIndexCreator]
-/// and realtime from 
[org.apache.pinot.segment.local.realtime.impl.vector.MutableVectorIndex]
+/// Builds the HNSW index for immutable segments during generation and index 
rebuilds.
 public class HnswVectorIndexCreator implements VectorIndexCreator {
   private static final Logger LOGGER = 
LoggerFactory.getLogger(HnswVectorIndexCreator.class);
   public static final String VECTOR_INDEX_DOC_ID_COLUMN_NAME = "DocID";
@@ -74,7 +73,8 @@ public class HnswVectorIndexCreator implements 
VectorIndexCreator {
       indexDirectory = FSDirectory.open(_hnswIndexDir.toPath());
       LOGGER.info("Creating HNSW index for column: {} at path: {} with {} for 
segment: {}", column,
           _hnswIndexDir.getAbsolutePath(), vectorIndexConfig.getProperties(), 
segmentIndexDir.getAbsolutePath());
-      indexWriter = new IndexWriter(indexDirectory, 
VectorIndexUtils.getIndexWriterConfig(vectorIndexConfig));
+      indexWriter = new IndexWriter(indexDirectory, 
VectorIndexUtils.getIndexWriterConfig(vectorIndexConfig,
+          vectorIndexConfig.isMmapGraphOnMerge() ? _segmentIndexDir.toPath() : 
null));
     } catch (Exception e) {
       // IndexWriter does not close the Directory passed to it, so both need 
to be closed.
       try {
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/HnswVectorsFormat.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/HnswVectorsFormat.java
index e65f0b43ede..65ba420c8c7 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/HnswVectorsFormat.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/HnswVectorsFormat.java
@@ -19,12 +19,15 @@
 package org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99;
 
 import java.io.IOException;
+import java.nio.file.Path;
+import javax.annotation.Nullable;
 import org.apache.lucene.codecs.KnnVectorsFormat;
 import org.apache.lucene.codecs.KnnVectorsReader;
 import org.apache.lucene.codecs.KnnVectorsWriter;
 import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsFormat;
 import org.apache.lucene.index.SegmentReadState;
 import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.store.IOContext;
 
 
 /// Extend Lucene 9.5 vector format to support HNSW graph
@@ -37,6 +40,9 @@ public final class HnswVectorsFormat extends KnnVectorsFormat 
{
 
   private final int _maxDimensions;
   private final Lucene99HnswVectorsFormat _delegate;
+  private final int _maxConn;
+  private final int _beamWidth;
+  private final Path _mmapMergeDirectory;
 
   /// Constructs a format using the given graph construction parameters.
   ///
@@ -44,6 +50,11 @@ public final class HnswVectorsFormat extends 
KnnVectorsFormat {
   /// @param beamWidth     the size of the queue maintained during graph 
construction.
   /// @param maxDimensions the maximum number of dimensions supported by this 
format
   public HnswVectorsFormat(int maxConn, int beamWidth, int maxDimensions) {
+    this(maxConn, beamWidth, maxDimensions, null);
+  }
+
+  /// Constructs a format with an optional scratch directory for the final 
forced merge.
+  public HnswVectorsFormat(int maxConn, int beamWidth, int maxDimensions, 
@Nullable Path mmapMergeDirectory) {
     super("Lucene99HnswVectorsFormat");
     if (maxDimensions <= 0 || maxDimensions > DEFAULT_MAX_DIMENSIONS) {
       throw new IllegalArgumentException(
@@ -54,11 +65,18 @@ public final class HnswVectorsFormat extends 
KnnVectorsFormat {
     }
     _delegate = new Lucene99HnswVectorsFormat(maxConn, beamWidth);
     _maxDimensions = maxDimensions;
+    _maxConn = maxConn;
+    _beamWidth = beamWidth;
+    _mmapMergeDirectory = mmapMergeDirectory;
   }
 
   @Override
   public KnnVectorsWriter fieldsWriter(SegmentWriteState state)
       throws IOException {
+    if (_mmapMergeDirectory != null && state.context.context == 
IOContext.Context.MERGE
+        && state.context.mergeInfo.mergeMaxNumSegments == 1) {
+      return new MmapHnswVectorsWriter(state, _mmapMergeDirectory, _maxConn, 
_beamWidth);
+    }
     return _delegate.fieldsWriter(state);
   }
 
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraph.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraph.java
new file mode 100644
index 00000000000..7f2303aff60
--- /dev/null
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraph.java
@@ -0,0 +1,223 @@
+/**
+ * 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.pinot.segment.local.segment.creator.impl.vector.lucene99;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.foreign.Arena;
+import java.lang.foreign.MemorySegment;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.util.Arrays;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.hnsw.HnswGraph;
+import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
+
+
+/// Mutable merge graph with neighbor IDs and scores stored in a confined 
temporary mapping.
+final class MmapHnswGraph extends HnswGraph implements Closeable {
+  private static final int WINDOW_BYTES = 1 << 20;
+
+  private final FileChannel _channel;
+  private final ByteBuffer _reservationBuffer = ByteBuffer.allocate(64 << 10);
+  private final Arena _arena = Arena.ofConfined();
+  private final MmapHnswNeighborList[][] _nodes;
+  private final int _maxConn;
+
+  private int[] _levelCounts = new int[4];
+  private int[][] _upperLevelNodes;
+  private MemorySegment _window;
+  private int _windowPosition = WINDOW_BYTES;
+  private long _nextFileOffset;
+  private int _entryNode = -1;
+  private int _numLevels;
+  private MmapHnswNeighborList _current;
+  private int _currentNeighbor;
+
+  static MmapHnswGraph open(Path directory, int vectorCount, int maxConn)
+      throws IOException {
+    Path file;
+    try {
+      file = Files.createTempFile(directory, "hnsw-merge-", ".adjacency");
+    } catch (IOException e) {
+      throw scratchFailure(e);
+    }
+    FileChannel channel = null;
+    try {
+      channel = FileChannel.open(file, StandardOpenOption.READ, 
StandardOpenOption.WRITE,
+          StandardOpenOption.DELETE_ON_CLOSE);
+      return new MmapHnswGraph(channel, vectorCount, maxConn);
+    } catch (IOException | RuntimeException | Error e) {
+      IOUtils.closeWhileHandlingException(channel);
+      try {
+        Files.deleteIfExists(file);
+      } catch (IOException cleanup) {
+        e.addSuppressed(cleanup);
+      }
+      if (e instanceof IOException ioException) {
+        throw scratchFailure(ioException);
+      }
+      throw e;
+    }
+  }
+
+  private MmapHnswGraph(FileChannel channel, int vectorCount, int maxConn) {
+    _channel = channel;
+    _nodes = new MmapHnswNeighborList[vectorCount][];
+    _maxConn = maxConn;
+  }
+
+  boolean contains(int node) {
+    return _nodes[node] != null;
+  }
+
+  void addNode(int node, int topLevel)
+      throws IOException {
+    assert !contains(node);
+    if (topLevel >= _levelCounts.length) {
+      _levelCounts = Arrays.copyOf(_levelCounts, topLevel + 1);
+    }
+    MmapHnswNeighborList[] levels = new MmapHnswNeighborList[topLevel + 1];
+    for (int level = topLevel; level >= 0; level--) {
+      // Allow one unused slot for the candidate before pruning an overfull 
neighbor list.
+      levels[level] = allocate(neighborLimit(level) + 1);
+      _levelCounts[level]++;
+    }
+    _nodes[node] = levels;
+  }
+
+  void setEntryNode(int node, int level) {
+    _entryNode = node;
+    _numLevels = level + 1;
+  }
+
+  int neighborLimit(int level) {
+    return level == 0 ? 2 * _maxConn : _maxConn;
+  }
+
+  MmapHnswNeighborList neighbors(int level, int node) {
+    return _nodes[node][level];
+  }
+
+  @Override
+  public void seek(int level, int target) {
+    _current = neighbors(level, target);
+    _currentNeighbor = 0;
+  }
+
+  @Override
+  public int nextNeighbor() {
+    return _currentNeighbor < _current.size() ? 
_current.node(_currentNeighbor++) : DocIdSetIterator.NO_MORE_DOCS;
+  }
+
+  @Override
+  public int size() {
+    return _levelCounts[0];
+  }
+
+  @Override
+  public int maxNodeId() {
+    return _nodes.length - 1;
+  }
+
+  @Override
+  public int numLevels() {
+    return _numLevels;
+  }
+
+  @Override
+  public int entryNode() {
+    return _entryNode;
+  }
+
+  @Override
+  public NodesIterator getNodesOnLevel(int level) {
+    assert size() == _nodes.length : "graph build is incomplete";
+    if (level == 0) {
+      return new ArrayNodesIterator(_nodes.length);
+    }
+    if (_upperLevelNodes == null) {
+      _upperLevelNodes = new int[_numLevels][];
+      int[] offsets = new int[_numLevels];
+      for (int upperLevel = 1; upperLevel < _numLevels; upperLevel++) {
+        _upperLevelNodes[upperLevel] = new int[_levelCounts[upperLevel]];
+      }
+      for (int node = 0; node < _nodes.length; node++) {
+        for (int upperLevel = 1; upperLevel < _nodes[node].length; 
upperLevel++) {
+          _upperLevelNodes[upperLevel][offsets[upperLevel]++] = node;
+        }
+      }
+    }
+    return new ArrayNodesIterator(_upperLevelNodes[level], 
_levelCounts[level]);
+  }
+
+  private MmapHnswNeighborList allocate(int capacity)
+      throws IOException {
+    int bytes = capacity * MmapHnswNeighborList.EDGE_BYTES;
+    assert bytes <= WINDOW_BYTES;
+    if (_windowPosition + bytes > WINDOW_BYTES) {
+      try {
+        reserveWindow();
+        _window = _channel.map(FileChannel.MapMode.READ_WRITE, 
_nextFileOffset, WINDOW_BYTES, _arena);
+      } catch (IOException e) {
+        throw scratchFailure(e);
+      }
+      _nextFileOffset += WINDOW_BYTES;
+      _windowPosition = 0;
+    }
+    MmapHnswNeighborList list = new MmapHnswNeighborList(_window, 
_windowPosition, capacity);
+    _windowPosition += bytes;
+    return list;
+  }
+
+  private static IOException scratchFailure(IOException cause) {
+    return new IOException("Failed to allocate local HNSW merge scratch space. 
Check the build directory or set "
+        + VectorIndexConfig.MMAP_GRAPH_ON_MERGE + " to false", cause);
+  }
+
+  private void reserveWindow()
+      throws IOException {
+    // Write and force the range before mapping so disk allocation failure can 
surface as IOException.
+    long end = _nextFileOffset + WINDOW_BYTES;
+    for (long offset = _nextFileOffset; offset < end; ) {
+      _reservationBuffer.clear();
+      _reservationBuffer.limit((int) Math.min(_reservationBuffer.capacity(), 
end - offset));
+      while (_reservationBuffer.hasRemaining()) {
+        int written = _channel.write(_reservationBuffer, offset);
+        if (written == 0) {
+          throw new IOException("Failed to reserve HNSW merge adjacency at 
offset " + offset);
+        }
+        offset += written;
+      }
+    }
+    _channel.force(false);
+  }
+
+  @Override
+  public void close()
+      throws IOException {
+    try (_channel; _arena) {
+      // Resources close in reverse order, unmapping before the channel closes.
+    }
+  }
+}
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraphBuilder.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraphBuilder.java
new file mode 100644
index 00000000000..86b076fbae6
--- /dev/null
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswGraphBuilder.java
@@ -0,0 +1,404 @@
+/**
+ * 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.pinot.segment.local.segment.creator.impl.vector.lucene99;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.SplittableRandom;
+import javax.annotation.Nullable;
+import org.apache.lucene.codecs.KnnVectorsWriter.MergedVectorValues;
+import org.apache.lucene.codecs.hnsw.HnswGraphProvider;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.MergeState;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.util.Bits;
+import org.apache.lucene.util.FixedBitSet;
+import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.HnswGraph;
+import org.apache.lucene.util.hnsw.HnswGraphBuilder;
+import org.apache.lucene.util.hnsw.IncrementalHnswGraphMerger;
+import org.apache.lucene.util.hnsw.NeighborArray;
+import org.apache.lucene.util.hnsw.NeighborQueue;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+
+
+/// Serial Lucene 9.12 HNSW merge algorithm using mapped neighbor rows. Reuses 
Lucene's selection
+/// of a compatible source graph and mapping of its vector ordinals into the 
merged segment.
+final class MmapHnswGraphBuilder extends IncrementalHnswGraphMerger {
+  private static final int MIN_CACHED_VECTOR_DIMENSION = 256;
+
+  private final MmapHnswGraph _graph;
+  private final SplittableRandom _random = new 
SplittableRandom(HnswGraphBuilder.randSeed);
+  private final double _levelMultiplier;
+  private final FixedBitSet _visited;
+  private final NeighborQueue _frontier;
+  private final NeighborQueue _entryCandidates = new NeighborQueue(1, false);
+  private final NeighborQueue _beamCandidates;
+
+  static MmapHnswGraph build(Path scratchDir, FieldInfo fieldInfo, 
CloseableRandomVectorScorerSupplier scorerSupplier,
+      MergeState mergeState, int maxConn, int beamWidth)
+      throws IOException {
+    int count = scorerSupplier.totalVectorCount();
+    MmapHnswGraph graph = MmapHnswGraph.open(scratchDir, count, maxConn);
+    try {
+      new MmapHnswGraphBuilder(graph, fieldInfo, scorerSupplier, maxConn, 
beamWidth).build(mergeState, count);
+      return graph;
+    } catch (IOException | RuntimeException | Error e) {
+      try {
+        graph.close();
+      } catch (IOException | RuntimeException closeFailure) {
+        e.addSuppressed(closeFailure);
+      }
+      throw e;
+    }
+  }
+
+  private MmapHnswGraphBuilder(MmapHnswGraph graph, FieldInfo fieldInfo,
+      CloseableRandomVectorScorerSupplier scorerSupplier, int maxConn, int 
beamWidth) {
+    super(fieldInfo, fieldInfo.getVectorDimension() >= 
MIN_CACHED_VECTOR_DIMENSION
+        ? new ScoreCachingSupplier(scorerSupplier) : scorerSupplier, maxConn, 
beamWidth);
+    _graph = graph;
+    _levelMultiplier = maxConn == 1 ? 1 : 1 / Math.log(maxConn);
+    _visited = new FixedBitSet(graph.maxNodeId() + 1);
+    _frontier = new NeighborQueue(beamWidth, true);
+    _beamCandidates = new NeighborQueue(beamWidth, false);
+  }
+
+  private void build(MergeState mergeState, int count)
+      throws IOException {
+    for (int i = 0; i < mergeState.liveDocs.length; i++) {
+      if (MergedVectorValues.hasVectorValues(mergeState.fieldInfos[i], 
fieldInfo.name)) {
+        addReader(mergeState.knnVectorsReaders[i], mergeState.docMaps[i], 
mergeState.liveDocs[i]);
+      }
+    }
+    if (initReader != null) {
+      DocIdSetIterator mergedValues = switch (fieldInfo.getVectorEncoding()) {
+        case BYTE -> MergedVectorValues.mergeByteVectorValues(fieldInfo, 
mergeState);
+        case FLOAT32 -> MergedVectorValues.mergeFloatVectorValues(fieldInfo, 
mergeState);
+      };
+      initialize(((HnswGraphProvider) initReader).getGraph(fieldInfo.name),
+          getNewOrdMapping(mergedValues, new FixedBitSet(count)));
+    }
+    for (int node = 0; node < count; node++) {
+      if (!_graph.contains(node)) {
+        insert(node);
+      }
+    }
+    connectComponents();
+  }
+
+  private void initialize(HnswGraph source, int[] ordinalMap)
+      throws IOException {
+    for (int level = source.numLevels() - 1; level >= 0; level--) {
+      HnswGraph.NodesIterator nodes = source.getNodesOnLevel(level);
+      while (nodes.hasNext()) {
+        int oldNode = nodes.nextInt();
+        int node = ordinalMap[oldNode];
+        if (!_graph.contains(node)) {
+          _graph.addNode(node, level);
+        }
+        if (_graph.entryNode() == -1) {
+          _graph.setEntryNode(node, level);
+        }
+        MmapHnswNeighborList neighbors = _graph.neighbors(level, node);
+        source.seek(level, oldNode);
+        for (int oldNeighbor = source.nextNeighbor(); oldNeighbor != 
DocIdSetIterator.NO_MORE_DOCS;
+            oldNeighbor = source.nextNeighbor()) {
+          // Scores from the reused graph are computed lazily if this row 
needs pruning.
+          neighbors.appendAndPrune(ordinalMap[oldNeighbor], Float.NaN, node, 
scorerSupplier);
+        }
+      }
+    }
+  }
+
+  private void insert(int node)
+      throws IOException {
+    int nodeLevel = nextLevel();
+    _graph.addNode(node, nodeLevel);
+    if (_graph.entryNode() == -1) {
+      _graph.setEntryNode(node, nodeLevel);
+      return;
+    }
+
+    RandomVectorScorer scorer = scorerSupplier.scorer(node);
+    int highestLevel = _graph.numLevels() - 1;
+    int[] entryPoints = {_graph.entryNode()};
+    for (int level = highestLevel; level > nodeLevel; level--) {
+      searchLevel(scorer, level, entryPoints, _entryCandidates, 1, null);
+      entryPoints[0] = _entryCandidates.pop();
+    }
+    NeighborArray[] candidates = new NeighborArray[Math.min(highestLevel, 
nodeLevel) + 1];
+    for (int level = candidates.length - 1; level >= 0; level--) {
+      searchLevel(scorer, level, entryPoints, _beamCandidates, beamWidth, 
null);
+      entryPoints = _beamCandidates.nodes();
+      NeighborArray row = new NeighborArray(_beamCandidates.size(), false);
+      while (_beamCandidates.size() > 0) {
+        float score = _beamCandidates.topScore();
+        row.addInOrder(_beamCandidates.pop(), score);
+      }
+      candidates[level] = row;
+    }
+    for (int level = 0; level < candidates.length; level++) {
+      linkNeighbors(level, node, candidates[level]);
+    }
+    if (nodeLevel > highestLevel) {
+      _graph.setEntryNode(node, nodeLevel);
+    }
+  }
+
+  private int nextLevel() {
+    double sample;
+    do {
+      sample = _random.nextDouble();
+    } while (sample == 0);
+    return (int) (-Math.log(sample) * _levelMultiplier);
+  }
+
+  private void linkNeighbors(int level, int node, NeighborArray candidates)
+      throws IOException {
+    MmapHnswNeighborList neighbors = _graph.neighbors(level, node);
+    int limit = _graph.neighborLimit(level);
+    int[] nodeIds = candidates.nodes();
+    float[] scores = candidates.scores();
+    // Add outgoing edges first. A selected neighbor must be closer to this 
node than to any
+    // neighbor already selected.
+    int[] chosen = new int[Math.min(limit, candidates.size())];
+    int chosenCount = 0;
+    for (int i = candidates.size() - 1; i >= 0 && chosenCount < chosen.length; 
i--) {
+      if (isDiverse(nodeIds[i], scores[i], neighbors)) {
+        neighbors.appendInOrder(nodeIds[i], scores[i]);
+        chosen[chosenCount++] = i;
+      }
+    }
+    // Traverse the selected candidates in the original worst-to-best order 
for backlinks.
+    for (int i = chosenCount - 1; i >= 0; i--) {
+      int candidate = chosen[i];
+      int neighbor = nodeIds[candidate];
+      _graph.neighbors(level, neighbor).appendAndPrune(node, 
scores[candidate], neighbor, scorerSupplier);
+    }
+  }
+
+  private boolean isDiverse(int candidate, float score, MmapHnswNeighborList 
neighbors)
+      throws IOException {
+    RandomVectorScorer scorer = scorerSupplier.scorer(candidate);
+    for (int i = 0; i < neighbors.size(); i++) {
+      if (scorer.score(neighbors.node(i)) >= score) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private void searchLevel(RandomVectorScorer scorer, int level, int[] 
entryPoints, NeighborQueue results, int topK,
+      @Nullable FixedBitSet accept)
+      throws IOException {
+    _frontier.clear();
+    _visited.clear();
+    results.clear();
+    for (int entry : entryPoints) {
+      if (!_visited.getAndSet(entry)) {
+        float score = scorer.score(entry);
+        _frontier.add(entry, score);
+        if (accept == null || accept.get(entry)) {
+          results.insertWithOverflow(entry, score);
+        }
+      }
+    }
+    float minimum = results.size() == topK ? results.topScore() : 
Float.NEGATIVE_INFINITY;
+    while (_frontier.size() > 0) {
+      if (_frontier.topScore() < minimum) {
+        break;
+      }
+      MmapHnswNeighborList neighbors = _graph.neighbors(level, 
_frontier.pop());
+      for (int i = 0; i < neighbors.size(); i++) {
+        int neighbor = neighbors.node(i);
+        if (!_visited.getAndSet(neighbor)) {
+          float score = scorer.score(neighbor);
+          if (score > minimum) {
+            _frontier.add(neighbor, score);
+            if ((accept == null || accept.get(neighbor)) && 
results.insertWithOverflow(neighbor, score)
+                && results.size() == topK) {
+              minimum = results.topScore();
+            }
+          }
+        }
+      }
+    }
+  }
+
+  private void connectComponents()
+      throws IOException {
+    int[] stack = new int[_graph.size()];
+    FixedBitSet connected = new FixedBitSet(_graph.size());
+    FixedBitSet spare = new FixedBitSet(_graph.size());
+    NeighborQueue nearest = new NeighborQueue(2, false);
+    for (int level = 0; level < _graph.numLevels(); level++) {
+      connected.clear();
+      spare.clear();
+      List<Component> components = findComponents(level, connected, spare, 
stack);
+      Component largest = components.getFirst();
+      for (Component component : components) {
+        if (component.size() > largest.size()) {
+          largest = component;
+        }
+      }
+      if (components.size() == 1 || largest.entry() == 
DocIdSetIterator.NO_MORE_DOCS) {
+        continue;
+      }
+      int[] entryPoints = {largest.entry()};
+      for (Component component : components) {
+        if (component != largest && component.entry() != 
DocIdSetIterator.NO_MORE_DOCS) {
+          int entry = component.entry();
+          RandomVectorScorer scorer = scorerSupplier.scorer(entry);
+          searchLevel(scorer, 0, entryPoints, nearest, 2, spare);
+          while (nearest.size() > 0) {
+            float score = nearest.topScore();
+            int candidate = nearest.pop();
+            if (candidate != entry && spare.get(candidate)) {
+              addBridge(level, candidate, entry, score, spare);
+            }
+          }
+        }
+      }
+    }
+  }
+
+  private List<Component> findComponents(int level, FixedBitSet connected, 
FixedBitSet spare, int[] stack) {
+    // Nodes in the next higher level are entry points for this level's search.
+    HnswGraph.NodesIterator entries = level == _graph.numLevels() - 1
+        ? new HnswGraph.ArrayNodesIterator(new int[]{_graph.entryNode()}, 1) : 
_graph.getNodesOnLevel(level + 1);
+    int rootedSize = 0;
+    while (entries.hasNext()) {
+      rootedSize += markReachable(level, entries.nextInt(), connected, spare, 
stack);
+    }
+    List<Component> components = new ArrayList<>();
+    components.add(new Component(spare.nextSetBit(0), rootedSize));
+    HnswGraph.NodesIterator nodes = _graph.getNodesOnLevel(level);
+    while (nodes.hasNext()) {
+      int node = nodes.nextInt();
+      if (!connected.get(node)) {
+        components.add(new Component(node, markReachable(level, node, 
connected, spare, stack)));
+      }
+    }
+    return components;
+  }
+
+  private int markReachable(int level, int entry, FixedBitSet connected, 
FixedBitSet spare, int[] stack) {
+    if (connected.getAndSet(entry)) {
+      return 0;
+    }
+    stack[0] = entry;
+    int pending = 1;
+    int count = 0;
+    int limit = _graph.neighborLimit(level);
+    while (pending > 0) {
+      int node = stack[--pending];
+      count++;
+      MmapHnswNeighborList neighbors = _graph.neighbors(level, node);
+      if (neighbors.size() < limit) {
+        spare.set(node);
+      }
+      for (int i = 0; i < neighbors.size(); i++) {
+        int neighbor = neighbors.node(i);
+        if (!connected.getAndSet(neighbor)) {
+          stack[pending++] = neighbor;
+        }
+      }
+    }
+    return count;
+  }
+
+  private void addBridge(int level, int from, int to, float score, FixedBitSet 
spare) {
+    int limit = _graph.neighborLimit(level);
+    MmapHnswNeighborList forward = _graph.neighbors(level, from);
+    forward.append(to, score);
+    if (forward.size() == limit) {
+      spare.clear(from);
+    }
+    MmapHnswNeighborList reverse = _graph.neighbors(level, to);
+    if (reverse.size() < limit) {
+      reverse.append(from, score);
+      if (reverse.size() == limit) {
+        spare.clear(to);
+      }
+    }
+  }
+
+  private record Component(int entry, int size) {
+  }
+
+  /// A bounded cache local to one merge. Searching multiple levels, linking 
neighbors, and pruning
+  /// backlinks can all compare the same pair of vectors. Lucene's similarity 
functions are symmetric.
+  private static final class ScoreCachingSupplier implements 
RandomVectorScorerSupplier {
+    private static final int CACHE_BITS = 13;
+
+    private final RandomVectorScorerSupplier _delegate;
+    private final long[] _pairs = new long[1 << CACHE_BITS];
+    private final float[] _scores = new float[_pairs.length];
+
+    ScoreCachingSupplier(RandomVectorScorerSupplier delegate) {
+      _delegate = delegate;
+    }
+
+    @Override
+    public RandomVectorScorer scorer(int ord)
+        throws IOException {
+      RandomVectorScorer scorer = _delegate.scorer(ord);
+      return new RandomVectorScorer() {
+        @Override
+        public float score(int node)
+            throws IOException {
+          long pair = (((long) Math.min(ord, node) << Integer.SIZE) | 
Math.max(ord, node)) + 1;
+          int slot = (int) ((pair * 0x9E3779B97F4A7C15L) >>> (Long.SIZE - 
CACHE_BITS));
+          if (_pairs[slot] == pair) {
+            return _scores[slot];
+          }
+          float score = scorer.score(node);
+          _pairs[slot] = pair;
+          _scores[slot] = score;
+          return score;
+        }
+
+        @Override
+        public int maxOrd() {
+          return scorer.maxOrd();
+        }
+
+        @Override
+        public int ordToDoc(int ord) {
+          return scorer.ordToDoc(ord);
+        }
+
+        @Override
+        public Bits getAcceptOrds(Bits acceptDocs) {
+          return scorer.getAcceptOrds(acceptDocs);
+        }
+      };
+    }
+
+    @Override
+    public RandomVectorScorerSupplier copy()
+        throws IOException {
+      return new ScoreCachingSupplier(_delegate.copy());
+    }
+  }
+}
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswNeighborList.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswNeighborList.java
new file mode 100644
index 00000000000..6e1e0893b00
--- /dev/null
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswNeighborList.java
@@ -0,0 +1,159 @@
+/**
+ * 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.pinot.segment.local.segment.creator.impl.vector.lucene99;
+
+import java.io.IOException;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.ValueLayout;
+import java.util.Arrays;
+import org.apache.lucene.util.hnsw.RandomVectorScorer;
+import org.apache.lucene.util.hnsw.RandomVectorScorerSupplier;
+
+
+/// Fixed-capacity mapped neighbor row. Diversity pruning follows Lucene 9.12 
NeighborArray.
+final class MmapHnswNeighborList {
+  static final int EDGE_BYTES = Integer.BYTES + Float.BYTES;
+
+  private final MemorySegment _window;
+  private final int _baseOffset;
+  private final int _capacity;
+  private int _size;
+  private int _sortedSize;
+
+  MmapHnswNeighborList(MemorySegment window, int baseOffset, int capacity) {
+    _window = window;
+    _baseOffset = baseOffset;
+    _capacity = capacity;
+  }
+
+  int size() {
+    return _size;
+  }
+
+  int node(int index) {
+    return _window.get(ValueLayout.JAVA_INT, offset(index));
+  }
+
+  private float score(int index) {
+    return _window.get(ValueLayout.JAVA_FLOAT, offset(index) + Integer.BYTES);
+  }
+
+  void appendInOrder(int node, float score) {
+    assert _size == _sortedSize && (_size == 0 || score <= score(_size - 1));
+    append(node, score);
+    _sortedSize++;
+  }
+
+  void append(int node, float score) {
+    if (_size == _capacity) {
+      throw new IllegalStateException("HNSW neighbor list exceeds capacity " + 
_capacity);
+    }
+    set(_size++, node, score);
+  }
+
+  void appendAndPrune(int neighbor, float score, int owner, 
RandomVectorScorerSupplier supplier)
+      throws IOException {
+    append(neighbor, score);
+    if (_size == _capacity) {
+      int remove = findWorstNonDiverse(owner, supplier);
+      move(remove + 1, remove, _size - remove - 1);
+      _size--;
+      _sortedSize--;
+    }
+  }
+
+  private int findWorstNonDiverse(int owner, RandomVectorScorerSupplier 
supplier)
+      throws IOException {
+    int[] unchecked = sortPending(supplier.scorer(owner));
+    int cursor = unchecked.length - 1;
+    for (int candidate = _size - 1; candidate > 0 && cursor >= 0; candidate--) 
{
+      float minSimilarity = score(candidate);
+      RandomVectorScorer scorer = supplier.scorer(node(candidate));
+      if (candidate == unchecked[cursor]) {
+        for (int i = candidate - 1; i >= 0; i--) {
+          if (scorer.score(node(i)) >= minSimilarity) {
+            return candidate;
+          }
+        }
+        cursor--;
+      } else {
+        for (int i = cursor; i >= 0; i--) {
+          if (scorer.score(node(unchecked[i])) >= minSimilarity) {
+            return candidate;
+          }
+        }
+      }
+    }
+    return _size - 1;
+  }
+
+  private int[] sortPending(RandomVectorScorer scorer)
+      throws IOException {
+    int[] unchecked = new int[_size - _sortedSize];
+    for (int count = 0; _sortedSize < _size; count++) {
+      int neighbor = node(_sortedSize);
+      float score = score(_sortedSize);
+      if (Float.isNaN(score)) {
+        score = scorer.score(neighbor);
+      }
+      int insertion = insertionPoint(score);
+      move(insertion, insertion + 1, _sortedSize - insertion);
+      set(insertion, neighbor, score);
+      _sortedSize++;
+      for (int i = 0; i < count; i++) {
+        if (unchecked[i] >= insertion) {
+          unchecked[i]++;
+        }
+      }
+      unchecked[count] = insertion;
+    }
+    Arrays.sort(unchecked);
+    return unchecked;
+  }
+
+  private int insertionPoint(float score) {
+    int low = 0;
+    int high = _sortedSize;
+    while (low < high) {
+      int mid = (low + high) >>> 1;
+      if (score(mid) < score) {
+        high = mid;
+      } else {
+        low = mid + 1;
+      }
+    }
+    return low;
+  }
+
+  private void set(int index, int node, float score) {
+    long offset = offset(index);
+    _window.set(ValueLayout.JAVA_INT, offset, node);
+    _window.set(ValueLayout.JAVA_FLOAT, offset + Integer.BYTES, score);
+  }
+
+  private long offset(int index) {
+    return _baseOffset + index * EDGE_BYTES;
+  }
+
+  private void move(int from, int to, int length) {
+    if (length != 0) {
+      MemorySegment.copy(_window, offset(from), _window, offset(to), length * 
EDGE_BYTES);
+    }
+  }
+}
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswVectorsWriter.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswVectorsWriter.java
new file mode 100644
index 00000000000..233c51c6dd6
--- /dev/null
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/lucene99/MmapHnswVectorsWriter.java
@@ -0,0 +1,229 @@
+/**
+ * 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.pinot.segment.local.segment.creator.impl.vector.lucene99;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Arrays;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.KnnFieldVectorsWriter;
+import org.apache.lucene.codecs.KnnVectorsWriter;
+import org.apache.lucene.codecs.hnsw.FlatVectorScorerUtil;
+import org.apache.lucene.codecs.hnsw.FlatVectorsWriter;
+import org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsFormat;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.MergeState;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.index.Sorter;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.apache.lucene.util.hnsw.CloseableRandomVectorScorerSupplier;
+import org.apache.lucene.util.hnsw.HnswGraph;
+import org.apache.lucene.util.hnsw.HnswGraph.NodesIterator;
+import org.apache.lucene.util.packed.DirectMonotonicWriter;
+
+
+/// Writes a final merge in the Lucene99 HNSW format using temporary mmap 
storage for graph construction.
+/// Each instance belongs to one Lucene merge thread. Vector values are 
written by Lucene's flat vector writer.
+final class MmapHnswVectorsWriter extends KnnVectorsWriter {
+  // Match Lucene 9.12's Lucene99HnswVectorsFormat (version 0), which remains 
the reader.
+  private static final String META_CODEC_NAME = 
"Lucene99HnswVectorsFormatMeta";
+  private static final String INDEX_CODEC_NAME = 
"Lucene99HnswVectorsFormatIndex";
+  private static final int FORMAT_VERSION = 0;
+  private static final int DIRECT_MONOTONIC_BLOCK_SHIFT = 16;
+  private static final long SHALLOW_SIZE = 
RamUsageEstimator.shallowSizeOfInstance(MmapHnswVectorsWriter.class);
+
+  private final Path _scratchDirectory;
+  private final int _maxConn;
+  private final int _beamWidth;
+  private final FlatVectorsWriter _flatWriter;
+  private final IndexOutput _meta;
+  private final IndexOutput _index;
+
+  MmapHnswVectorsWriter(SegmentWriteState state, Path scratchDirectory, int 
maxConn, int beamWidth)
+      throws IOException {
+    _scratchDirectory = scratchDirectory;
+    _maxConn = maxConn;
+    _beamWidth = beamWidth;
+    FlatVectorsWriter flatWriter = new 
Lucene99FlatVectorsFormat(FlatVectorScorerUtil.getLucene99FlatVectorsScorer())
+        .fieldsWriter(state);
+    IndexOutput meta = null;
+    IndexOutput index = null;
+    boolean success = false;
+    try {
+      meta = state.directory.createOutput(
+          IndexFileNames.segmentFileName(state.segmentInfo.name, 
state.segmentSuffix, "vem"), state.context);
+      index = state.directory.createOutput(
+          IndexFileNames.segmentFileName(state.segmentInfo.name, 
state.segmentSuffix, "vex"), state.context);
+      byte[] segmentId = state.segmentInfo.getId();
+      CodecUtil.writeIndexHeader(meta, META_CODEC_NAME, FORMAT_VERSION, 
segmentId, state.segmentSuffix);
+      CodecUtil.writeIndexHeader(index, INDEX_CODEC_NAME, FORMAT_VERSION, 
segmentId, state.segmentSuffix);
+      success = true;
+    } finally {
+      if (!success) {
+        IOUtils.closeWhileHandlingException(meta, index, flatWriter);
+      }
+    }
+    _flatWriter = flatWriter;
+    _meta = meta;
+    _index = index;
+  }
+
+  @Override
+  public KnnFieldVectorsWriter<?> addField(FieldInfo fieldInfo) {
+    throw new UnsupportedOperationException("The mmap HNSW writer is only used 
for final merges");
+  }
+
+  @Override
+  public void flush(int maxDoc, Sorter.DocMap sortMap) {
+    throw new UnsupportedOperationException("The mmap HNSW writer is only used 
for final merges");
+  }
+
+  @Override
+  public void mergeOneField(FieldInfo field, MergeState mergeState)
+      throws IOException {
+    try (CloseableRandomVectorScorerSupplier scorers = 
_flatWriter.mergeOneFieldToIndex(field, mergeState)) {
+      int count = scorers.totalVectorCount();
+      long offset = _index.getFilePointer();
+      if (count == 0) {
+        writeFieldMeta(field, offset, 0, 0);
+        _meta.writeVInt(0);
+        return;
+      }
+      try (MmapHnswGraph graph =
+          MmapHnswGraphBuilder.build(_scratchDirectory, field, scorers, 
mergeState, _maxConn, _beamWidth)) {
+        if (graph.size() != count) {
+          throw new IOException("Expected " + count + " HNSW nodes for " + 
field.name + ", got " + graph.size());
+        }
+        writeGraph(field, offset, graph);
+      }
+    }
+  }
+
+  private void writeGraph(FieldInfo field, long offset, HnswGraph graph)
+      throws IOException {
+    int count = graph.size();
+    int levels = graph.numLevels();
+    int[][] nodesByLevel = new int[levels][];
+    int[][] lengthsByLevel = new int[levels][];
+    int[] neighbors = new int[2 * _maxConn];
+    long totalNodes = 0;
+    for (int level = 0; level < levels; level++) {
+      // Level zero includes all vector ordinals. Higher levels are stored in 
ascending ordinal order.
+      int[] nodes = level == 0 ? null : 
NodesIterator.getSortedNodes(graph.getNodesOnLevel(level));
+      nodesByLevel[level] = nodes;
+      int nodesOnLevel = nodes == null ? count : nodes.length;
+      int[] lengths = new int[nodesOnLevel];
+      lengthsByLevel[level] = lengths;
+      totalNodes += nodesOnLevel;
+      for (int i = 0; i < nodesOnLevel; i++) {
+        long start = _index.getFilePointer();
+        int node = nodes == null ? i : nodes[i];
+        graph.seek(level, node);
+        int numNeighbors = 0;
+        for (int neighbor = graph.nextNeighbor(); neighbor != 
DocIdSetIterator.NO_MORE_DOCS;
+            neighbor = graph.nextNeighbor()) {
+          neighbors[numNeighbors++] = neighbor;
+        }
+        _index.writeVInt(numNeighbors);
+        Arrays.sort(neighbors, 0, numNeighbors);
+        writeDeltaEncoded(_index, neighbors, numNeighbors);
+        lengths[i] = Math.toIntExact(_index.getFilePointer() - start);
+      }
+    }
+
+    writeFieldMeta(field, offset, _index.getFilePointer() - offset, count);
+    _meta.writeVInt(levels);
+    for (int level = 1; level < levels; level++) {
+      int[] nodes = nodesByLevel[level];
+      _meta.writeVInt(nodes.length);
+      writeDeltaEncoded(_meta, nodes, nodes.length);
+    }
+    writeNodeOffsets(totalNodes, lengthsByLevel);
+  }
+
+  private static void writeDeltaEncoded(IndexOutput output, int[] values, int 
count)
+      throws IOException {
+    int previous = 0;
+    for (int i = 0; i < count; i++) {
+      int value = values[i];
+      output.writeVInt(value - previous);
+      previous = value;
+    }
+  }
+
+  private void writeFieldMeta(FieldInfo field, long offset, long length, int 
count)
+      throws IOException {
+    _meta.writeInt(field.number);
+    _meta.writeInt(field.getVectorEncoding().ordinal());
+    int similarityOrdinal = Lucene99HnswVectorsReader.SIMILARITY_FUNCTIONS
+        .indexOf(field.getVectorSimilarityFunction());
+    if (similarityOrdinal < 0) {
+      throw new IllegalArgumentException("Invalid vector similarity function: 
" + field.getVectorSimilarityFunction());
+    }
+    _meta.writeInt(similarityOrdinal);
+    _meta.writeVLong(offset);
+    _meta.writeVLong(length);
+    _meta.writeVInt(field.getVectorDimension());
+    _meta.writeInt(count);
+    _meta.writeVInt(_maxConn);
+  }
+
+  private void writeNodeOffsets(long totalNodes, int[][] lengthsByLevel)
+      throws IOException {
+    long start = _index.getFilePointer();
+    _meta.writeLong(start);
+    _meta.writeVInt(DIRECT_MONOTONIC_BLOCK_SHIFT);
+    DirectMonotonicWriter offsets =
+        DirectMonotonicWriter.getInstance(_meta, _index, totalNodes, 
DIRECT_MONOTONIC_BLOCK_SHIFT);
+    long offset = 0;
+    for (int[] lengths : lengthsByLevel) {
+      for (int length : lengths) {
+        offsets.add(offset);
+        offset += length;
+      }
+    }
+    offsets.finish();
+    _meta.writeLong(_index.getFilePointer() - start);
+  }
+
+  @Override
+  public void finish()
+      throws IOException {
+    _flatWriter.finish();
+    _meta.writeInt(-1);
+    CodecUtil.writeFooter(_meta);
+    CodecUtil.writeFooter(_index);
+  }
+
+  @Override
+  public long ramBytesUsed() {
+    return SHALLOW_SIZE + _flatWriter.ramBytesUsed();
+  }
+
+  @Override
+  public void close()
+      throws IOException {
+    IOUtils.close(_meta, _index, _flatWriter);
+  }
+}
diff --git 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/VectorIndexUtils.java
 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/VectorIndexUtils.java
index 326e1f428f0..c09a69034b6 100644
--- 
a/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/VectorIndexUtils.java
+++ 
b/pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/store/VectorIndexUtils.java
@@ -22,6 +22,7 @@ import com.google.common.annotations.VisibleForTesting;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
@@ -324,6 +325,11 @@ public class VectorIndexUtils {
   }
 
   public static IndexWriterConfig getIndexWriterConfig(VectorIndexConfig 
vectorIndexConfig) {
+    return getIndexWriterConfig(vectorIndexConfig, null);
+  }
+
+  public static IndexWriterConfig getIndexWriterConfig(VectorIndexConfig 
vectorIndexConfig,
+      @Nullable Path mmapMergeDirectory) {
     IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
 
     double maxBufferSizeMB = 
Double.parseDouble(vectorIndexConfig.getProperties()
@@ -343,8 +349,7 @@ public class VectorIndexUtils {
     int maxDimensions = Integer.parseInt(vectorIndexConfig.getProperties()
         .getOrDefault("maxDimensions", 
String.valueOf(HnswVectorsFormat.DEFAULT_MAX_DIMENSIONS)));
 
-    HnswVectorsFormat knnVectorsFormat =
-        new HnswVectorsFormat(maxCon, beamWidth, maxDimensions);
+    HnswVectorsFormat knnVectorsFormat = new HnswVectorsFormat(maxCon, 
beamWidth, maxDimensions, mmapMergeDirectory);
 
     Lucene912Codec.Mode mode = 
Lucene912Codec.Mode.valueOf(vectorIndexConfig.getProperties()
         .getOrDefault("mode", Lucene912Codec.Mode.BEST_SPEED.name()));
diff --git 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
index fc86c747495..0be4073ffca 100644
--- 
a/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
+++ 
b/pinot-segment-local/src/test/java/org/apache/pinot/segment/local/segment/index/creator/HnswVectorIndexCreatorTest.java
@@ -20,11 +20,36 @@ package 
org.apache.pinot.segment.local.segment.index.creator;
 
 import java.io.File;
 import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
+import java.util.Random;
 import org.apache.commons.io.FileUtils;
+import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.KnnVectorsWriter;
+import org.apache.lucene.codecs.hnsw.HnswGraphProvider;
+import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsWriter;
+import org.apache.lucene.codecs.perfield.PerFieldKnnVectorsFormat;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.FieldInfos;
+import org.apache.lucene.index.SegmentInfo;
+import org.apache.lucene.index.SegmentReader;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.store.ByteBuffersDirectory;
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.MergeInfo;
+import org.apache.lucene.util.InfoStream;
+import org.apache.lucene.util.StringHelper;
+import org.apache.lucene.util.Version;
+import org.apache.lucene.util.hnsw.HnswGraph;
 import 
org.apache.pinot.segment.local.segment.creator.impl.vector.HnswVectorIndexCreator;
+import 
org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99.HnswVectorsFormat;
 import 
org.apache.pinot.segment.local.segment.index.readers.vector.HnswVectorIndexReader;
+import org.apache.pinot.segment.spi.V1Constants;
 import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
 import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
 import org.roaringbitmap.buffer.MutableRoaringBitmap;
@@ -33,6 +58,11 @@ import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
 import org.testng.annotations.Test;
 
+import static org.apache.lucene.search.DocIdSetIterator.NO_MORE_DOCS;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+
 
 public class HnswVectorIndexCreatorTest {
   private static final File INDEX_DIR =
@@ -69,6 +99,103 @@ public class HnswVectorIndexCreatorTest {
     FileUtils.deleteDirectory(INDEX_DIR);
   }
 
+  @Test
+  public void testMmapWriterSelection()
+      throws IOException {
+    HnswVectorsFormat mmapFormat = new HnswVectorsFormat(16, 100, 1024, 
INDEX_DIR.toPath());
+    HnswVectorsFormat heapFormat = new HnswVectorsFormat(16, 100, 1024);
+    IOContext forcedMerge = new IOContext(new MergeInfo(4, 0, false, 1));
+    assertFalse(usesHeapWriter(mmapFormat, forcedMerge));
+    assertTrue(usesHeapWriter(heapFormat, forcedMerge));
+    assertTrue(usesHeapWriter(mmapFormat, IOContext.DEFAULT));
+    assertTrue(usesHeapWriter(mmapFormat, new IOContext(new MergeInfo(4, 0, 
false, -1))));
+  }
+
+  private static boolean usesHeapWriter(HnswVectorsFormat format, IOContext 
context)
+      throws IOException {
+    try (ByteBuffersDirectory directory = new ByteBuffersDirectory()) {
+      SegmentInfo segmentInfo = new SegmentInfo(directory, Version.LATEST, 
Version.LATEST, "_0", 4, false, false,
+          Codec.getDefault(), Map.of(), StringHelper.randomId(), Map.of(), 
null);
+      SegmentWriteState state = new SegmentWriteState(InfoStream.NO_OUTPUT, 
directory, segmentInfo, FieldInfos.EMPTY,
+          null, context);
+      try (KnnVectorsWriter writer = format.fieldsWriter(state)) {
+        return writer instanceof Lucene99HnswVectorsWriter;
+      }
+    }
+  }
+
+  @Test
+  public void testForcedMergeIndexCanBeRead()
+      throws IOException {
+    float[][] vectors = new float[128][1024];
+    Random random = new Random(42);
+    for (float[] vector : vectors) {
+      for (int dim = 0; dim < vector.length; dim++) {
+        vector[dim] = random.nextFloat() - 0.5f;
+      }
+    }
+    MergedIndex heapIndex = mergeAndReadGraph("embeddingHeap", vectors, true);
+    MergedIndex mmapIndex = mergeAndReadGraph("embeddingMmap", vectors, false);
+    assertEquals(mmapIndex.graph(), heapIndex.graph());
+    assertEquals(mmapIndex.nearestDocs(), heapIndex.nearestDocs());
+  }
+
+  private static MergedIndex mergeAndReadGraph(String column, float[][] 
vectors, boolean optOut)
+      throws IOException {
+    // A low connection limit exercises pruning during the final merge.
+    Map<String, String> properties = new HashMap<>(Map.of("vectorDimension", 
"1024", "maxCon", "4",
+        "maxBufferSizeMB", "0.15"));
+    if (optOut) {
+      properties.put(VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "false");
+    }
+    VectorIndexConfig config = new VectorIndexConfig(properties);
+    Path path = INDEX_DIR.toPath().resolve(column + 
V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION);
+    try (HnswVectorIndexCreator creator = new HnswVectorIndexCreator(column, 
INDEX_DIR, config);
+        FSDirectory directory = FSDirectory.open(path)) {
+      for (float[] vector : vectors) {
+        creator.add(vector);
+      }
+      long leaves = Arrays.stream(directory.listAll()).filter(name -> 
name.endsWith(".si")).count();
+      assertTrue(leaves > 1 && leaves < 10, "Expected multiple Lucene segments 
below the background merge threshold");
+      creator.seal();
+    }
+    int[] nearestDocs = new int[vectors.length];
+    try (HnswVectorIndexReader reader = new HnswVectorIndexReader(column, 
INDEX_DIR, vectors.length, config)) {
+      reader.setEfSearch(vectors.length);
+      for (int i = 0; i < vectors.length; i++) {
+        int[] matches = reader.getDocIds(vectors[i], 1).toArray();
+        assertEquals(matches.length, 1);
+        nearestDocs[i] = matches[0];
+      }
+    }
+    try (FSDirectory directory = FSDirectory.open(path); DirectoryReader 
reader = DirectoryReader.open(directory)) {
+      assertEquals(reader.leaves().size(), 1);
+      assertEquals(reader.numDocs(), vectors.length);
+      SegmentReader segment = (SegmentReader) 
reader.leaves().getFirst().reader();
+      PerFieldKnnVectorsFormat.FieldsReader fields = 
(PerFieldKnnVectorsFormat.FieldsReader) segment.getVectorReader();
+      HnswGraph graph = ((HnswGraphProvider) 
fields.getFieldReader(column)).getGraph(column);
+      List<Map<Integer, List<Integer>>> levels = new 
ArrayList<>(graph.numLevels());
+      for (int level = 0; level < graph.numLevels(); level++) {
+        Map<Integer, List<Integer>> edges = new HashMap<>();
+        HnswGraph.NodesIterator nodes = graph.getNodesOnLevel(level);
+        while (nodes.hasNext()) {
+          int node = nodes.nextInt();
+          graph.seek(level, node);
+          List<Integer> neighbors = new ArrayList<>();
+          for (int neighbor = graph.nextNeighbor(); neighbor != NO_MORE_DOCS; 
neighbor = graph.nextNeighbor()) {
+            neighbors.add(neighbor);
+          }
+          edges.put(node, neighbors);
+        }
+        levels.add(edges);
+      }
+      return new MergedIndex(levels, nearestDocs);
+    }
+  }
+
+  private record MergedIndex(List<Map<Integer, List<Integer>>> graph, int[] 
nearestDocs) {
+  }
+
   @Test
   public void testIndexWriterReaderWithTop3()
       throws IOException {
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfig.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfig.java
index 70e06650be0..c21dc2b7c06 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfig.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfig.java
@@ -58,6 +58,9 @@ public class VectorIndexConfig extends IndexConfig {
   public static final String STORE_IN_SEGMENT_FILE = "storeInSegmentFile";
   public static final boolean DEFAULT_STORE_IN_SEGMENT_FILE = false;
 
+  /// HNSW property controlling mmap-backed graph construction during the 
immutable index's final merge.
+  public static final String MMAP_GRAPH_ON_MERGE = "mmapGraphOnMerge";
+
   private String _vectorIndexType;
   private int _vectorDimension;
   private int _version;
@@ -170,6 +173,14 @@ public class VectorIndexConfig extends IndexConfig {
     return value == null ? DEFAULT_STORE_IN_SEGMENT_FILE : 
Boolean.parseBoolean(value);
   }
 
+  /// Whether to use mmap-backed graph construction during the immutable HNSW 
index's final merge.
+  /// Defaults to true and uses scratch space in the segment build directory. 
Set to false in the
+  /// `properties` map to use Lucene's heap-backed merge.
+  @JsonIgnore
+  public boolean isMmapGraphOnMerge() {
+    return _properties == null || 
Boolean.parseBoolean(_properties.getOrDefault(MMAP_GRAPH_ON_MERGE, "true"));
+  }
+
   /// Resolves the [VectorBackendType] for this config. If `vectorIndexType` 
is null or empty,
   /// defaults to [VectorBackendType#HNSW] for backward compatibility.
   ///
diff --git 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java
 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java
index cdcb70a803f..ee69fab72a8 100644
--- 
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java
+++ 
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java
@@ -43,7 +43,7 @@ public final class VectorIndexConfigValidator {
   static final Set<String> HNSW_PROPERTIES = Collections.unmodifiableSet(new 
HashSet<>(
       Arrays.asList("maxCon", "beamWidth", "maxDimensions", "maxBufferSizeMB",
           "useCompoundFile", "mode", "commit", "commitIntervalMs", 
"commitDocs",
-          "refreshMinIntervalMs", "refreshWaitTimeoutMs")));
+          "refreshMinIntervalMs", "refreshWaitTimeoutMs", 
VectorIndexConfig.MMAP_GRAPH_ON_MERGE)));
 
   // IVF_FLAT-specific property keys
   static final Set<String> IVF_FLAT_PROPERTIES = 
Collections.unmodifiableSet(new HashSet<>(
@@ -265,6 +265,13 @@ public final class VectorIndexConfigValidator {
     // created on the server, which would stop ingestion for the partition 
instead of failing the table config.
     validateLongProperty(properties, "refreshMinIntervalMs", "HNSW 
refreshMinIntervalMs", 0L);
     validateLongProperty(properties, "refreshWaitTimeoutMs", "HNSW 
refreshWaitTimeoutMs", 1L);
+    if (properties.containsKey(VectorIndexConfig.MMAP_GRAPH_ON_MERGE)) {
+      String value = properties.get(VectorIndexConfig.MMAP_GRAPH_ON_MERGE);
+      if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) 
{
+        throw new IllegalArgumentException(
+            "HNSW " + VectorIndexConfig.MMAP_GRAPH_ON_MERGE + " must be true 
or false, got: '" + value + "'");
+      }
+    }
   }
 
   /// Absent means "use the default"; anything present must parse and satisfy 
the bound.
diff --git 
a/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidatorTest.java
 
b/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidatorTest.java
index 95242e3d44b..e7629286030 100644
--- 
a/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidatorTest.java
+++ 
b/pinot-segment-spi/src/test/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidatorTest.java
@@ -23,7 +23,9 @@ import java.util.Map;
 import org.testng.annotations.Test;
 
 import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
 
 
 /// Tests for [VectorIndexConfigValidator].
@@ -66,8 +68,8 @@ public class VectorIndexConfigValidatorTest {
     properties.put("version", "1");
 
     VectorIndexConfig config = new VectorIndexConfig(properties);
-    // Must not throw
     VectorIndexConfigValidator.validate(config);
+    assertTrue(config.isMmapGraphOnMerge());
   }
 
   // ============================================================
@@ -82,10 +84,12 @@ public class VectorIndexConfigValidatorTest {
     properties.put("vectorDistanceFunction", "COSINE");
     properties.put("maxCon", "32");
     properties.put("beamWidth", "200");
+    properties.put(VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "true");
 
     VectorIndexConfig config = new VectorIndexConfig(properties);
     VectorIndexConfigValidator.validate(config);
     assertEquals(config.resolveBackendType(), VectorBackendType.HNSW);
+    assertTrue(config.isMmapGraphOnMerge());
   }
 
   @Test
@@ -100,9 +104,11 @@ public class VectorIndexConfigValidatorTest {
     properties.put("maxBufferSizeMB", "256.5");
     properties.put("useCompoundFile", "true");
     properties.put("mode", "BEST_SPEED");
+    properties.put(VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "false");
 
     VectorIndexConfig config = new VectorIndexConfig(properties);
     VectorIndexConfigValidator.validate(config);
+    assertFalse(config.isMmapGraphOnMerge());
   }
 
   @Test
@@ -111,6 +117,21 @@ public class VectorIndexConfigValidatorTest {
     VectorIndexConfig config = new VectorIndexConfig(false, "HNSW", 768, 1,
         VectorIndexConfig.VectorDistanceFunction.COSINE, null);
     VectorIndexConfigValidator.validate(config);
+    assertTrue(config.isMmapGraphOnMerge());
+  }
+
+  @Test(expectedExceptions = IllegalArgumentException.class,
+      expectedExceptionsMessageRegExp = ".*mmapGraphOnMerge must be true or 
false.*")
+  public void testRejectMalformedMmapGraphOnMerge() {
+    VectorIndexConfigValidator.validate(new 
VectorIndexConfig(Map.of("vectorDimension", "1024",
+        VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "yes")));
+  }
+
+  @Test(expectedExceptions = IllegalArgumentException.class,
+      expectedExceptionsMessageRegExp = ".*mmapGraphOnMerge.*cannot be used 
with vectorIndexType IVF_FLAT.*")
+  public void testRejectMmapGraphOnMergeOnIvfFlat() {
+    VectorIndexConfigValidator.validate(new 
VectorIndexConfig(Map.of("vectorIndexType", "IVF_FLAT", "vectorDimension",
+        "1024", VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "false")));
   }
 
   // ============================================================


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to