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 59740fd250a Opt-in parallel HNSW graph build for small segments
(#20072)
59740fd250a is described below
commit 59740fd250acaf6c07dc534602ece1c8158d202c
Author: RAGHVENDRA KUMAR YADAV <[email protected]>
AuthorDate: Sat Nov 21 17:56:21 2026 -0800
Opt-in parallel HNSW graph build for small segments (#20072)
* Build HNSW graphs in one pass and in parallel for small segments
* Test that every HNSW build mode keeps row doc ids and removes its
per-thread directories
* Validate and bound the HNSW build properties, merge graphs concurrently,
and wait for part writers on failure
- VectorIndexConfigValidator accepts buildThreads (1-32), forceMerge
(true/false) and parallelBuildMaxDocs, and
rejects bad values at table config time instead of at segment build; the
creator also clamps buildThreads
- The default parallelBuildMaxDocs is now as many vectors as fit in 64 MB
(at most 50,000)
- With forceMerge=true the final merge uses buildThreads Lucene merge
workers
- On a failed part, wait for the other part writers before closing and
deleting their directories
* Merge parallel-built HNSW graphs on one thread by default, behind
concurrentMerge
A concurrent merge makes the merged graph depend on thread timing, so
replicas that each build the index can return
different top-K for the same query. Keep the default forceMerge
deterministic and make the concurrent merge opt-in.
* Wrap long lines in HnswVectorIndexCreator
* Wrap the last long javadoc line in HnswVectorIndexCreator
* Open HNSW part writers with OpenMode.CREATE
A part directory left by a build that crashed after committing a part was
appended to by the next build, so its documents were added to the index
again. Opening the part writers with CREATE starts each part empty.
* Fix indentation in HnswVectorIndexCreator constructor
* Honor HNSW merge settings and roll back failed parallel builds
---------
Co-authored-by: Xiang Fu <[email protected]>
---
.../impl/vector/HnswVectorIndexCreator.java | 197 +++++++++++++++++++--
.../impl/vector/lucene99/HnswVectorsFormat.java | 21 ++-
.../local/segment/store/VectorIndexUtils.java | 37 +++-
.../index/creator/HnswVectorIndexCreatorTest.java | 127 ++++++++++++-
.../spi/index/creator/VectorBackendType.java | 13 ++
.../spi/index/creator/VectorIndexConfig.java | 29 ++-
.../index/creator/VectorIndexConfigValidator.java | 35 +++-
.../creator/VectorIndexConfigValidatorTest.java | 34 ++++
8 files changed, 457 insertions(+), 36 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 9dfa861a000..fbc8c29084f 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
@@ -18,17 +18,29 @@
*/
package org.apache.pinot.segment.local.segment.creator.impl.vector;
+import com.google.common.io.Closer;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.MergePolicy;
+import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.VectorSimilarityFunction;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.ThreadInterruptedException;
import
org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99.HnswVectorIndexCombined;
import org.apache.pinot.segment.local.segment.store.VectorIndexUtils;
import org.apache.pinot.segment.spi.V1Constants;
@@ -43,6 +55,10 @@ import org.slf4j.LoggerFactory;
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";
+ /// Default heap budget for vectors buffered for a parallel build, so the
default doc limit shrinks as the dimension
+ /// grows (about 10k docs at 1536 dims) instead of holding a fixed number of
vectors of any size.
+ private static final long DEFAULT_PARALLEL_BUILD_MAX_BYTES = 64L * 1024 *
1024;
+ private static final int DEFAULT_PARALLEL_BUILD_MAX_DOCS = 50_000;
private final String _vectorColumn;
private final VectorSimilarityFunction _vectorSimilarityFunction;
@@ -54,7 +70,23 @@ public class HnswVectorIndexCreator implements
VectorIndexCreator {
private final Directory _indexDirectory;
private final IndexWriter _indexWriter;
+ private final int _buildThreads;
+ private final boolean _forceMerge;
+ private final boolean _concurrentMerge;
+ private final VectorIndexConfig _vectorIndexConfig;
+ /// Above this many vectors the buffered ones are indexed on the calling
thread and buffering stops, so large
+ /// segments keep the single-writer path. Defaults to as many vectors as fit
in 64 MB, at most 50,000. While
+ /// buffering, the build holds the vectors on heap plus up to one
`maxBufferSizeMB` per thread.
+ private final int _parallelBuildMaxDocs;
+ /// Runs the graph merge workers on seal, when building in parallel with
`forceMerge=true` and `concurrentMerge=true`
+ @Nullable
+ private final ExecutorService _mergeExecutor;
+ @Nullable
+ private List<float[]> _bufferedVectors;
+
private int _nextDocId = 0;
+ private boolean _sealed;
+ private boolean _failed;
public HnswVectorIndexCreator(String column, File segmentIndexDir,
VectorIndexConfig vectorIndexConfig) {
_vectorColumn = column;
@@ -62,6 +94,17 @@ public class HnswVectorIndexCreator implements
VectorIndexCreator {
_vectorSimilarityFunction =
VectorIndexUtils.toSimilarityFunction(vectorIndexConfig.getVectorDistanceFunction());
_storeInSegmentFile = vectorIndexConfig.isStoreInSegmentFile();
_segmentIndexDir = segmentIndexDir;
+ Map<String, String> properties = vectorIndexConfig.getProperties();
+ _buildThreads = vectorIndexConfig.getHnswBuildThreads();
+ _forceMerge = vectorIndexConfig.isHnswForceMerge();
+ _concurrentMerge = vectorIndexConfig.isHnswConcurrentMerge();
+ String parallelBuildMaxDocs = properties != null ?
properties.get("parallelBuildMaxDocs") : null;
+ _parallelBuildMaxDocs = parallelBuildMaxDocs != null ?
Integer.parseInt(parallelBuildMaxDocs)
+ : (int) Math.max(1, Math.min(DEFAULT_PARALLEL_BUILD_MAX_DOCS,
+ DEFAULT_PARALLEL_BUILD_MAX_BYTES / ((long) Float.BYTES *
_vectorDimension)));
+ _bufferedVectors = _buildThreads > 1 ? new ArrayList<>() : null;
+ _mergeExecutor = _concurrentMerge ?
Executors.newFixedThreadPool(_buildThreads) : null;
+ _vectorIndexConfig = vectorIndexConfig;
// Segment generation is always in V1 and later we convert (as part of
post creation processing) to V3 if
// segmentVersion is set to V3 in SegmentGeneratorConfig.
_hnswIndexDir =
@@ -73,8 +116,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,
- vectorIndexConfig.isMmapGraphOnMerge() ? _segmentIndexDir.toPath() :
null));
+ indexWriter = new IndexWriter(indexDirectory,
VectorIndexUtils.getImmutableIndexWriterConfig(vectorIndexConfig,
+ _segmentIndexDir.toPath(), _mergeExecutor));
} catch (Exception e) {
// IndexWriter does not close the Directory passed to it, so both need
to be closed.
try {
@@ -82,6 +125,9 @@ public class HnswVectorIndexCreator implements
VectorIndexCreator {
} catch (Exception closeEx) {
e.addSuppressed(closeEx);
}
+ if (_mergeExecutor != null) {
+ _mergeExecutor.shutdownNow();
+ }
throw new RuntimeException(
"Caught exception while instantiating the HnswVectorIndexCreator for
column: " + column, e);
}
@@ -100,38 +146,159 @@ public class HnswVectorIndexCreator implements
VectorIndexCreator {
@Override
public void add(float[] document) {
+ if (_failed || _sealed) {
+ throw new IllegalStateException("Cannot add to a failed or sealed HNSW
index for column: " + _vectorColumn);
+ }
+ if (_bufferedVectors != null) {
+ if (_bufferedVectors.size() < _parallelBuildMaxDocs) {
+ // Callers may reuse the array for the next row.
+ _bufferedVectors.add(document.clone());
+ return;
+ }
+ for (float[] buffered : _bufferedVectors) {
+ addDocument(buffered);
+ }
+ _bufferedVectors = null;
+ }
+ addDocument(document);
+ }
+
+ private Document toDocument(float[] vector, int docId) {
Document docToIndex = new Document();
- XKnnFloatVectorField xKnnFloatVectorField =
- new XKnnFloatVectorField(_vectorColumn, document,
_vectorSimilarityFunction);
- docToIndex.add(xKnnFloatVectorField);
- docToIndex.add(new StoredField(VECTOR_INDEX_DOC_ID_COLUMN_NAME,
_nextDocId++));
+ docToIndex.add(new XKnnFloatVectorField(_vectorColumn, vector,
_vectorSimilarityFunction));
+ docToIndex.add(new StoredField(VECTOR_INDEX_DOC_ID_COLUMN_NAME, docId));
+ return docToIndex;
+ }
+
+ private void addDocument(float[] vector) {
try {
- _indexWriter.addDocument(docToIndex);
+ _indexWriter.addDocument(toDocument(vector, _nextDocId));
+ _nextDocId++;
+ } catch (ThreadInterruptedException e) {
+ _failed = true;
+ Thread.currentThread().interrupt();
+ throw e;
} catch (Exception e) {
+ _failed = true;
throw new RuntimeException(
"Caught exception while adding a new document to the HNSW index for
column: " + _vectorColumn, e);
}
}
+ /// Indexes the buffered vectors from `_buildThreads` threads, each a
contiguous range of doc ids written by its own
+ /// IndexWriter, so each graph is also finished (flushed) on its own thread;
the per-thread indexes are then attached
+ /// to the main index as separate Lucene segments without rebuilding them.
+ private void addBufferedInParallel(List<float[]> vectors)
+ throws Exception {
+ int numDocs = vectors.size();
+ int numThreads = Math.min(_buildThreads, numDocs);
+ if (numThreads == 0) {
+ return;
+ }
+ // Recovery deletes the unfinished main index, including scratch left by a
process crash.
+ try (Closer parts = Closer.create()) {
+ Path scratch = Files.createTempDirectory(_hnswIndexDir.toPath(),
"hnsw-parts-");
+ parts.register(() -> IOUtils.rm(scratch));
+ Directory[] directories = new Directory[numThreads];
+ for (int t = 0; t < numThreads; t++) {
+ directories[t] =
parts.register(FSDirectory.open(scratch.resolve(Integer.toString(t))));
+ }
+ try (ExecutorService executor =
Executors.newFixedThreadPool(numThreads)) {
+ ExecutorCompletionService<Void> completed = new
ExecutorCompletionService<>(executor);
+ try {
+ for (int t = 0; t < numThreads; t++) {
+ int from = (int) ((long) numDocs * t / numThreads);
+ int to = (int) ((long) numDocs * (t + 1) / numThreads);
+ Directory directory = directories[t];
+ completed.submit(() -> {
+ writePart(directory, vectors, from, to);
+ return null;
+ });
+ }
+ for (int t = 0; t < numThreads; t++) {
+ completed.take().get();
+ }
+ } finally {
+ // Cancel outstanding work on failure. ExecutorService.close() joins
every worker before scratch is released.
+ executor.shutdownNow();
+ }
+ }
+ if (Thread.interrupted()) {
+ throw new InterruptedException("HNSW part build interrupted");
+ }
+ // addIndexes calls maybeMerge. Keep all parts intact until the optional
final forced merge.
+ MergePolicy mergePolicy = _indexWriter.getConfig().getMergePolicy();
+ _indexWriter.getConfig().setMergePolicy(NoMergePolicy.INSTANCE);
+ _indexWriter.addIndexes(directories);
+ if (_forceMerge) {
+ _indexWriter.getConfig().setMergePolicy(mergePolicy);
+ }
+ }
+ }
+
+ private void writePart(Directory directory, List<float[]> vectors, int from,
int to)
+ throws IOException, InterruptedException {
+ try (IndexWriter writer = new IndexWriter(directory,
VectorIndexUtils.getIndexWriterConfig(_vectorIndexConfig)
+ .setMergePolicy(NoMergePolicy.INSTANCE).setCommitOnClose(false))) {
+ for (int docId = from; docId < to; docId++) {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new InterruptedException("HNSW part build interrupted");
+ }
+ writer.addDocument(toDocument(vectors.get(docId), docId));
+ }
+ writer.commit();
+ }
+ }
+
@Override
public void seal() {
+ if (_sealed) {
+ return;
+ }
+ if (_failed) {
+ throw new IllegalStateException("Previous HNSW build failed for column:
" + _vectorColumn);
+ }
try {
- LOGGER.info("Sealing HNSW index for column: {}", _vectorColumn);
- _indexWriter.forceMerge(1);
+ LOGGER.info("Sealing HNSW index for column: {} (buildThreads: {},
forceMerge: {}, concurrentMerge: {})",
+ _vectorColumn, _buildThreads, _forceMerge, _concurrentMerge);
+ if (_bufferedVectors != null) {
+ addBufferedInParallel(_bufferedVectors);
+ }
+ if (_forceMerge) {
+ _indexWriter.forceMerge(1);
+ }
+ _sealed = true;
+ } catch (InterruptedException | ThreadInterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException("Interrupted while sealing the HNSW index for
column: " + _vectorColumn, e);
} catch (Exception e) {
throw new RuntimeException("Caught exception while sealing the HNSW
index for column: " + _vectorColumn, e);
+ } finally {
+ _failed = !_sealed;
+ _bufferedVectors = null;
}
}
@Override
public void close()
throws IOException {
- try {
- // Based on the commit flag set in IndexWriterConfig, closing the writer
will decide to commit or not.
- // IndexWriter does not close the Directory passed to it, so both need
to be closed.
- IOUtils.close(_indexWriter, _indexDirectory);
- } catch (Exception e) {
- throw new RuntimeException("Caught exception while closing the HNSW
index for column: " + _vectorColumn, e);
+ _bufferedVectors = null;
+ boolean abort = _failed || (_buildThreads > 1 && !_sealed);
+ // Rollback must finish even when seal restored the caller's interrupt.
+ boolean interrupted = abort && Thread.interrupted();
+ try (_indexDirectory) {
+ if (abort) {
+ _indexWriter.rollback();
+ return;
+ }
+ _indexWriter.close();
+ } finally {
+ if (_mergeExecutor != null) {
+ _mergeExecutor.close();
+ }
+ if (interrupted) {
+ Thread.currentThread().interrupt();
+ }
}
if (_storeInSegmentFile) {
// Pack the Lucene directory into a single combined file so the V2→V3
converter can absorb it
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 65ba420c8c7..f787527a1f2 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
@@ -20,6 +20,7 @@ package
org.apache.pinot.segment.local.segment.creator.impl.vector.lucene99;
import java.io.IOException;
import java.nio.file.Path;
+import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import org.apache.lucene.codecs.KnnVectorsFormat;
import org.apache.lucene.codecs.KnnVectorsReader;
@@ -40,6 +41,7 @@ public final class HnswVectorsFormat extends KnnVectorsFormat
{
private final int _maxDimensions;
private final Lucene99HnswVectorsFormat _delegate;
+ private final Lucene99HnswVectorsFormat _finalMergeDelegate;
private final int _maxConn;
private final int _beamWidth;
private final Path _mmapMergeDirectory;
@@ -50,11 +52,18 @@ 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);
+ this(maxConn, beamWidth, maxDimensions, 1, null, 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) {
+ this(maxConn, beamWidth, maxDimensions, 1, null, mmapMergeDirectory);
+ }
+
+ /// A final forced merge can use the supplied executor for heap-backed graph
construction or a scratch
+ /// directory for mmap-backed construction. Ordinary merges use the default
Lucene format.
+ public HnswVectorsFormat(int maxConn, int beamWidth, int maxDimensions, int
numMergeWorkers,
+ @Nullable ExecutorService mergeExec, @Nullable Path mmapMergeDirectory) {
super("Lucene99HnswVectorsFormat");
if (maxDimensions <= 0 || maxDimensions > DEFAULT_MAX_DIMENSIONS) {
throw new IllegalArgumentException(
@@ -64,6 +73,8 @@ public final class HnswVectorsFormat extends KnnVectorsFormat
{
+ maxDimensions);
}
_delegate = new Lucene99HnswVectorsFormat(maxConn, beamWidth);
+ _finalMergeDelegate = numMergeWorkers > 1
+ ? new Lucene99HnswVectorsFormat(maxConn, beamWidth, numMergeWorkers,
mergeExec) : _delegate;
_maxDimensions = maxDimensions;
_maxConn = maxConn;
_beamWidth = beamWidth;
@@ -73,9 +84,11 @@ public final class HnswVectorsFormat extends
KnnVectorsFormat {
@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);
+ if (state.context.context == IOContext.Context.MERGE &&
state.context.mergeInfo.mergeMaxNumSegments == 1) {
+ if (_mmapMergeDirectory != null) {
+ return new MmapHnswVectorsWriter(state, _mmapMergeDirectory, _maxConn,
_beamWidth);
+ }
+ return _finalMergeDelegate.fieldsWriter(state);
}
return _delegate.fieldsWriter(state);
}
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 c09a69034b6..c7647a58b56 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
@@ -26,7 +26,9 @@ import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.ExecutorService;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.codecs.lucene912.Lucene912Codec;
@@ -325,33 +327,50 @@ public class VectorIndexUtils {
}
public static IndexWriterConfig getIndexWriterConfig(VectorIndexConfig
vectorIndexConfig) {
- return getIndexWriterConfig(vectorIndexConfig, null);
+ return getIndexWriterConfig(vectorIndexConfig, 1, null, null);
}
public static IndexWriterConfig getIndexWriterConfig(VectorIndexConfig
vectorIndexConfig,
@Nullable Path mmapMergeDirectory) {
+ return getIndexWriterConfig(vectorIndexConfig, 1, null,
mmapMergeDirectory);
+ }
+
+ /// Configures the main immutable writer with the final merge mode selected
by the table configuration.
+ public static IndexWriterConfig
getImmutableIndexWriterConfig(VectorIndexConfig vectorIndexConfig, Path
segmentDir,
+ @Nullable ExecutorService mergeExecutor) {
+ return getIndexWriterConfig(vectorIndexConfig, mergeExecutor != null ?
vectorIndexConfig.getHnswBuildThreads() : 1,
+ mergeExecutor, vectorIndexConfig.isMmapGraphOnMerge() ? segmentDir :
null);
+ }
+
+ private static IndexWriterConfig getIndexWriterConfig(VectorIndexConfig
vectorIndexConfig, int numMergeWorkers,
+ @Nullable ExecutorService mergeExec, @Nullable Path mmapMergeDirectory) {
IndexWriterConfig indexWriterConfig = new IndexWriterConfig();
- double maxBufferSizeMB =
Double.parseDouble(vectorIndexConfig.getProperties()
+ Map<String, String> properties = vectorIndexConfig.getProperties();
+ if (properties == null) {
+ properties = Map.of();
+ }
+ double maxBufferSizeMB = Double.parseDouble(properties
.getOrDefault("maxBufferSizeMB",
String.valueOf(IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB)));
- boolean commit = Boolean.parseBoolean(vectorIndexConfig.getProperties()
+ boolean commit = Boolean.parseBoolean(properties
.getOrDefault("commit",
String.valueOf(IndexWriterConfig.DEFAULT_COMMIT_ON_CLOSE)));
- boolean useCompoundFile =
Boolean.parseBoolean(vectorIndexConfig.getProperties()
+ boolean useCompoundFile = Boolean.parseBoolean(properties
.getOrDefault("useCompoundFile",
String.valueOf(IndexWriterConfig.DEFAULT_USE_COMPOUND_FILE_SYSTEM)));
indexWriterConfig.setRAMBufferSizeMB(maxBufferSizeMB);
indexWriterConfig.setCommitOnClose(commit);
indexWriterConfig.setUseCompoundFile(useCompoundFile);
- int maxCon = Integer.parseInt(vectorIndexConfig.getProperties()
+ int maxCon = Integer.parseInt(properties
.getOrDefault("maxCon",
String.valueOf(Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN)));
- int beamWidth = Integer.parseInt(vectorIndexConfig.getProperties()
+ int beamWidth = Integer.parseInt(properties
.getOrDefault("beamWidth",
String.valueOf(Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH)));
- int maxDimensions = Integer.parseInt(vectorIndexConfig.getProperties()
+ int maxDimensions = Integer.parseInt(properties
.getOrDefault("maxDimensions",
String.valueOf(HnswVectorsFormat.DEFAULT_MAX_DIMENSIONS)));
- HnswVectorsFormat knnVectorsFormat = new HnswVectorsFormat(maxCon,
beamWidth, maxDimensions, mmapMergeDirectory);
+ HnswVectorsFormat knnVectorsFormat =
+ new HnswVectorsFormat(maxCon, beamWidth, maxDimensions,
numMergeWorkers, mergeExec, mmapMergeDirectory);
- Lucene912Codec.Mode mode =
Lucene912Codec.Mode.valueOf(vectorIndexConfig.getProperties()
+ Lucene912Codec.Mode mode = Lucene912Codec.Mode.valueOf(properties
.getOrDefault("mode", Lucene912Codec.Mode.BEST_SPEED.name()));
indexWriterConfig.setCodec(new HnswCodec(mode, knnVectorsFormat));
return indexWriterConfig;
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 0be4073ffca..056f3da39d3 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
@@ -18,8 +18,10 @@
*/
package org.apache.pinot.segment.local.segment.index.creator;
+import com.google.common.base.Throwables;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
@@ -27,8 +29,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.KnnVectorsFormat;
import org.apache.lucene.codecs.KnnVectorsWriter;
import org.apache.lucene.codecs.hnsw.HnswGraphProvider;
import org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsWriter;
@@ -39,6 +44,7 @@ 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.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.MergeInfo;
@@ -47,8 +53,10 @@ 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.HnswCodec;
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.local.segment.store.VectorIndexUtils;
import org.apache.pinot.segment.spi.V1Constants;
import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig;
import org.roaringbitmap.buffer.ImmutableRoaringBitmap;
@@ -56,12 +64,14 @@ import org.roaringbitmap.buffer.MutableRoaringBitmap;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
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;
+import static org.testng.Assert.expectThrows;
public class HnswVectorIndexCreatorTest {
@@ -111,7 +121,28 @@ public class HnswVectorIndexCreatorTest {
assertTrue(usesHeapWriter(mmapFormat, new IOContext(new MergeInfo(4, 0,
false, -1))));
}
- private static boolean usesHeapWriter(HnswVectorsFormat format, IOContext
context)
+ @Test
+ public void testConcurrentMergeWriterSelection()
+ throws IOException {
+ Map<String, String> properties = new HashMap<>(Map.of("vectorDimension",
"8", "buildThreads", "2",
+ "concurrentMerge", "true"));
+ IOContext forcedMerge = new IOContext(new MergeInfo(4, 0, false, 1));
+ try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
+ for (String mmap : new String[]{null, "false", "true"}) {
+ if (mmap != null) {
+ properties.put(VectorIndexConfig.MMAP_GRAPH_ON_MERGE, mmap);
+ }
+ VectorIndexConfig config = new VectorIndexConfig(properties);
+ boolean expectConcurrent = !"true".equals(mmap);
+ assertEquals(config.isHnswConcurrentMerge(), expectConcurrent);
+ HnswCodec codec = (HnswCodec)
VectorIndexUtils.getImmutableIndexWriterConfig(config, INDEX_DIR.toPath(),
+ config.isHnswConcurrentMerge() ? executor : null).getCodec();
+ assertEquals(usesHeapWriter(codec.getKnnVectorsFormatForField("foo"),
forcedMerge), expectConcurrent);
+ }
+ }
+ }
+
+ private static boolean usesHeapWriter(KnnVectorsFormat format, IOContext
context)
throws IOException {
try (ByteBuffersDirectory directory = new ByteBuffersDirectory()) {
SegmentInfo segmentInfo = new SegmentInfo(directory, Version.LATEST,
Version.LATEST, "_0", 4, false, false,
@@ -306,4 +337,98 @@ public class HnswVectorIndexCreatorTest {
"Debug info must report the reader's actual pre-filter capability,
not a hardcoded literal");
}
}
+
+ @DataProvider
+ public Object[][] parallelBuilds() {
+ // buildThreads, forceMerge, concurrentMerge, parallelBuildMaxDocs: the
last case outgrows the buffer and falls back
+ // to one writer
+ return new Object[][]{
+ {1, true, false, 50_000}, {4, true, false, 50_000}, {4, true, true,
50_000}, {16, false, false, 50_000},
+ {3, false, false, 100}
+ };
+ }
+
+ /// Every build mode, including the default single writer, must index each
row under its own doc id: searching for a
+ /// stored vector finds that row.
+ @Test(dataProvider = "parallelBuilds")
+ public void testParallelBuildKeepsDocIds(int buildThreads, boolean
forceMerge, boolean concurrentMerge,
+ int parallelBuildMaxDocs)
+ throws IOException {
+ File indexDir = new File(INDEX_DIR, "parallel");
+ FileUtils.forceMkdir(indexDir);
+ Path sentinel =
Files.writeString(indexDir.toPath().resolve("bar.hnsw.part0"), "unrelated
file");
+ Map<String, String> properties = new HashMap<>();
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "8");
+ properties.put("buildThreads", String.valueOf(buildThreads));
+ properties.put("forceMerge", String.valueOf(forceMerge));
+ properties.put("concurrentMerge", String.valueOf(concurrentMerge));
+ properties.put("parallelBuildMaxDocs",
String.valueOf(parallelBuildMaxDocs));
+ VectorIndexConfig config = new VectorIndexConfig(properties);
+ int numDocs = 1000;
+ float[][] vectors = new float[numDocs][8];
+ Random random = new Random(42);
+ try (HnswVectorIndexCreator creator = new HnswVectorIndexCreator("bar",
indexDir, config)) {
+ float[] reused = new float[8];
+ for (int i = 0; i < numDocs; i++) {
+ for (int d = 0; d < 8; d++) {
+ vectors[i][d] = random.nextFloat();
+ reused[d] = vectors[i][d];
+ }
+ // The creator must copy the row, since callers reuse the array
+ creator.add(reused);
+ }
+ creator.seal();
+ }
+ assertEquals(Files.readString(sentinel), "unrelated file");
+ try (HnswVectorIndexReader reader = new HnswVectorIndexReader("bar",
indexDir, numDocs, config)) {
+ int expectedLeaves = forceMerge || numDocs > parallelBuildMaxDocs ? 1 :
buildThreads;
+ assertEquals(reader.getIndexDebugInfo().get("luceneSegments"),
expectedLeaves);
+ for (int docId = 0; docId < numDocs; docId += 37) {
+ // k widens the HNSW search beam; with k = 1 the approximate search
can miss even an exact match
+ assertTrue(reader.getDocIds(vectors[docId], 10).contains(docId), "Doc
" + docId + " not found");
+ }
+ }
+ File index = new File(indexDir, "bar" +
V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION);
+ assertEquals(index.listFiles(File::isDirectory).length, 0, "Scratch
directories must be removed after seal");
+ assertEquals(indexDir.list().length, 3, "Expected only the index, its
doc-id mapping and the sentinel");
+ }
+
+ @DataProvider
+ public Object[][] sealFailures() {
+ return new Object[][]{{false}, {true}};
+ }
+
+ @Test(dataProvider = "sealFailures")
+ public void testFailedParallelSealCleansUp(boolean interrupt)
+ throws IOException {
+ File indexDir = new File(INDEX_DIR, "failed");
+ VectorIndexConfig config = new VectorIndexConfig(Map.of("vectorDimension",
"2", "buildThreads", "2",
+ VectorIndexConfig.STORE_IN_SEGMENT_FILE, "true"));
+ try (HnswVectorIndexCreator creator = new HnswVectorIndexCreator("bar",
indexDir, config)) {
+ creator.add(new float[]{1, 2});
+ creator.add(interrupt ? new float[]{3, 4} : new float[0]);
+ if (interrupt) {
+ Thread.currentThread().interrupt();
+ }
+ RuntimeException failure = expectThrows(RuntimeException.class,
creator::seal);
+ if (interrupt) {
+ assertTrue(Thread.currentThread().isInterrupted(), "Sealing must
preserve cancellation");
+ } else {
+ assertEquals(Throwables.getRootCause(failure).getMessage(), "cannot
index an empty vector");
+ }
+ } finally {
+ // Leave the TestNG worker ready for the next invocation.
+ Thread.interrupted();
+ }
+ File index = new File(indexDir, "bar" +
V1Constants.Indexes.VECTOR_V912_HNSW_INDEX_FILE_EXTENSION);
+ assertEquals(indexDir.listFiles(file -> !file.equals(index)).length, 0,
+ "A failed seal must leave neither scratch directories nor a packed
index");
+ if (index.exists()) {
+ assertEquals(index.listFiles(File::isDirectory).length, 0, "Scratch
directories must be removed on failure");
+ try (Directory directory = FSDirectory.open(index.toPath())) {
+ assertFalse(DirectoryReader.indexExists(directory), "A failed seal
must not commit a partial index");
+ }
+ }
+ }
}
diff --git
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorBackendType.java
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorBackendType.java
index f04f5d83c2b..b73f135695f 100644
---
a/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorBackendType.java
+++
b/pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorBackendType.java
@@ -42,6 +42,19 @@ public enum VectorBackendType {
/// - `maxBufferSizeMB` - Lucene RAM buffer size
/// - `useCompoundFile` - whether to use compound file format
/// - `mode` - Lucene codec mode (BEST_SPEED or BEST_COMPRESSION)
+ ///
+ /// Immutable segment build settings:
+ ///
+ /// - `buildThreads` - number of part writers (1 to 32, default 1). Each
writer has its own Lucene RAM buffer.
+ /// - `parallelBuildMaxDocs` - maximum vectors buffered for the parallel
build. The default is the smaller of
+ /// 50,000 and the number of vectors whose float values fit in 64 MiB.
Larger segments use a single writer.
+ /// - `forceMerge` - merge to one Lucene segment on seal (default true).
Disabling it can reduce build time and
+ /// increase query latency as searches visit each remaining segment. A
part can flush multiple segments.
+ /// - `concurrentMerge` - use heap-backed graph construction with
`buildThreads` workers during the final merge
+ /// when `buildThreads` exceeds 1 and `forceMerge` is true (default
false). Thread scheduling can change recall
+ /// and produce different nearest neighbors across replicas.
+ /// - `mmapGraphOnMerge` - use a single-threaded, mmap-backed final merge.
This is the default unless concurrent
+ /// merging is enabled. Setting this property explicitly to true takes
priority over `concurrentMerge`.
HNSW("Hierarchical Navigable Small World graph (Lucene-based)"),
/// Inverted File with flat (uncompressed) vectors.
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 c21dc2b7c06..241c67f6576 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
@@ -173,12 +173,35 @@ public class VectorIndexConfig extends IndexConfig {
return value == null ? DEFAULT_STORE_IN_SEGMENT_FILE :
Boolean.parseBoolean(value);
}
+ /// Number of part writers used when building an immutable HNSW index.
+ @JsonIgnore
+ public int getHnswBuildThreads() {
+ // Existing table configurations may have been stored before this property
was validated.
+ return _properties == null ? 1 :
Math.min(VectorIndexConfigValidator.MAX_HNSW_BUILD_THREADS,
+ Math.max(1, Integer.parseInt(_properties.getOrDefault("buildThreads",
"1"))));
+ }
+
+ /// Whether to force the immutable HNSW index into one Lucene segment at
seal time.
+ @JsonIgnore
+ public boolean isHnswForceMerge() {
+ return _properties == null ||
Boolean.parseBoolean(_properties.getOrDefault("forceMerge", "true"));
+ }
+
+ /// Whether the final forced merge uses Lucene's concurrent, heap-backed
graph construction.
+ /// An explicit mmap request takes priority.
+ @JsonIgnore
+ public boolean isHnswConcurrentMerge() {
+ return _properties != null &&
Boolean.parseBoolean(_properties.get("concurrentMerge"))
+ && !Boolean.parseBoolean(_properties.get(MMAP_GRAPH_ON_MERGE)) &&
isHnswForceMerge()
+ && getHnswBuildThreads() > 1;
+ }
+
/// 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.
+ /// The default uses scratch space in the segment build directory unless
concurrent graph construction is requested.
@JsonIgnore
public boolean isMmapGraphOnMerge() {
- return _properties == null ||
Boolean.parseBoolean(_properties.getOrDefault(MMAP_GRAPH_ON_MERGE, "true"));
+ return _properties == null ||
(Boolean.parseBoolean(_properties.getOrDefault(MMAP_GRAPH_ON_MERGE, "true"))
+ && !isHnswConcurrentMerge());
}
/// Resolves the [VectorBackendType] for this config. If `vectorIndexType`
is null or empty,
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 ee69fab72a8..069cc175f9f 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,12 @@ 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",
VectorIndexConfig.MMAP_GRAPH_ON_MERGE)));
+ "refreshMinIntervalMs", "refreshWaitTimeoutMs",
VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "buildThreads",
+ "forceMerge", "concurrentMerge", "parallelBuildMaxDocs")));
+
+ /// Upper bound for the HNSW `buildThreads` property: each thread opens its
own Lucene IndexWriter and directory
+ /// during segment build, so an unbounded value can exhaust threads and file
handles.
+ public static final int MAX_HNSW_BUILD_THREADS = 32;
// IVF_FLAT-specific property keys
static final Set<String> IVF_FLAT_PROPERTIES =
Collections.unmodifiableSet(new HashSet<>(
@@ -261,6 +266,15 @@ public final class VectorIndexConfigValidator {
validatePositiveIntProperty(properties, "beamWidth", "HNSW beamWidth");
validatePositiveIntProperty(properties, "maxDimensions", "HNSW
maxDimensions");
validatePositiveDoubleProperty(properties, "maxBufferSizeMB", "HNSW
maxBufferSizeMB");
+ // Parsed at segment build (commit or reload), where a bad value would
fail the build instead of the table config
+ int buildThreads =
parsePositiveInt(properties.getOrDefault("buildThreads", "1"), "HNSW
buildThreads");
+ if (buildThreads > MAX_HNSW_BUILD_THREADS) {
+ throw new IllegalArgumentException(
+ "HNSW buildThreads must be <= " + MAX_HNSW_BUILD_THREADS + ", got: "
+ buildThreads);
+ }
+ validatePositiveIntProperty(properties, "parallelBuildMaxDocs", "HNSW
parallelBuildMaxDocs");
+ validateBooleanProperty(properties, "forceMerge", "HNSW forceMerge");
+ validateBooleanProperty(properties, "concurrentMerge", "HNSW
concurrentMerge");
// Rejected here rather than only in MutableVectorIndex: the constructor
guard runs when a consuming segment is
// created on the server, which would stop ingestion for the partition
instead of failing the table config.
validateLongProperty(properties, "refreshMinIntervalMs", "HNSW
refreshMinIntervalMs", 0L);
@@ -361,6 +375,18 @@ public final class VectorIndexConfigValidator {
parsePositiveIntProperty(properties, key, displayName);
}
+ /// Validates that an optional property, if present, is `true` or `false`
(any case), the only values
+ /// `Boolean.parseBoolean` does not silently read as `false`.
+ private static void validateBooleanProperty(Map<String, String> properties,
String key, String displayName) {
+ if (!properties.containsKey(key)) {
+ return;
+ }
+ String value = properties.get(key);
+ if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
+ throw new IllegalArgumentException(displayName + " must be true or
false, got: '" + value + "'");
+ }
+ }
+
/// Validates that an optional property, if present, is a positive double.
private static void validatePositiveDoubleProperty(Map<String, String>
properties, String key, String displayName) {
String value = properties.get(key);
@@ -379,9 +405,10 @@ public final class VectorIndexConfigValidator {
private static Integer parsePositiveIntProperty(Map<String, String>
properties, String key, String displayName) {
String value = properties.get(key);
- if (value == null) {
- return null;
- }
+ return value == null ? null : parsePositiveInt(value, displayName);
+ }
+
+ private static int parsePositiveInt(String value, String displayName) {
try {
int intValue = Integer.parseInt(value);
if (intValue <= 0) {
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 e7629286030..199ec68e914 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
@@ -20,12 +20,14 @@ package org.apache.pinot.segment.spi.index.creator;
import java.util.HashMap;
import java.util.Map;
+import org.testng.annotations.DataProvider;
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;
+import static org.testng.Assert.fail;
/// Tests for [VectorIndexConfigValidator].
@@ -105,12 +107,44 @@ public class VectorIndexConfigValidatorTest {
properties.put("useCompoundFile", "true");
properties.put("mode", "BEST_SPEED");
properties.put(VectorIndexConfig.MMAP_GRAPH_ON_MERGE, "false");
+ properties.put("buildThreads", "4");
+ properties.put("forceMerge", "FALSE");
+ properties.put("concurrentMerge", "true");
+ properties.put("parallelBuildMaxDocs", "20000");
VectorIndexConfig config = new VectorIndexConfig(properties);
VectorIndexConfigValidator.validate(config);
assertFalse(config.isMmapGraphOnMerge());
}
+ @DataProvider
+ public Object[][] invalidHnswBuildProperties() {
+ return new Object[][]{
+ {"buildThreads", null, ".*buildThreads must be a valid integer.*"},
+ {"buildThreads", "four", ".*buildThreads must be a valid integer.*"},
+ {"buildThreads", "0", ".*buildThreads must be a positive integer.*"},
+ {"buildThreads", "2000", ".*buildThreads must be <= 32.*"},
+ {"parallelBuildMaxDocs", "-1", ".*parallelBuildMaxDocs must be a
positive integer.*"},
+ {"forceMerge", "yes", ".*forceMerge must be true or false.*"},
+ {"concurrentMerge", "1", ".*concurrentMerge must be true or false.*"}
+ };
+ }
+
+ @Test(dataProvider = "invalidHnswBuildProperties")
+ public void testRejectsInvalidHnswBuildProperty(String key, String value,
String messageRegex) {
+ Map<String, String> properties = new HashMap<>();
+ properties.put("vectorIndexType", "HNSW");
+ properties.put("vectorDimension", "128");
+ properties.put("vectorDistanceFunction", "COSINE");
+ properties.put(key, value);
+ try {
+ VectorIndexConfigValidator.validate(new VectorIndexConfig(properties));
+ fail("Expected " + key + "=" + value + " to be rejected");
+ } catch (IllegalArgumentException e) {
+ assertTrue(e.getMessage().matches(messageRegex), e.getMessage());
+ }
+ }
+
@Test
public void testValidHnswConfigMinimal() {
// Minimal config: only required fields
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]