xiangfu0 commented on code in PR #20072:
URL: https://github.com/apache/pinot/pull/20072#discussion_r4655641107


##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java:
##########
@@ -74,6 +125,7 @@ public HnswVectorIndexCreator(String column, File 
segmentIndexDir, VectorIndexCo
       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,
+          _mergeExecutor != null ? _buildThreads : 1, _mergeExecutor,
           vectorIndexConfig.isMmapGraphOnMerge() ? _segmentIndexDir.toPath() : 
null));

Review Comment:
   `concurrentMerge=true` currently falls through to the single-threaded mmap 
writer for the final merge because `mmapGraphOnMerge` defaults to true. The 
concurrent test only checks search results. Please define the interaction, 
cover the effective writer with omitted and explicit mmap settings, and 
document the settings in `VectorBackendType.HNSW`.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java:
##########
@@ -100,32 +155,119 @@ public void add(Object[] values, @Nullable int[] 
dictIds) {
 
   @Override
   public void add(float[] document) {
+    if (_bufferedVectors != null) {
+      // Callers may reuse the array for the next row
+      _bufferedVectors.add(document.clone());
+      if (_bufferedVectors.size() <= _parallelBuildMaxDocs) {
+        return;
+      }
+      for (float[] buffered : _bufferedVectors) {
+        addDocument(buffered, _nextDocId++);
+      }
+      _bufferedVectors = null;
+      return;
+    }
+    addDocument(document, _nextDocId++);
+  }
+
+  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, int docId) {
     try {
-      _indexWriter.addDocument(docToIndex);
+      _indexWriter.addDocument(toDocument(vector, docId));
     } catch (Exception e) {
       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()
+      throws Exception {
+    int numDocs = _bufferedVectors.size();
+    int numThreads = Math.min(_buildThreads, Math.max(1, numDocs));
+    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
+    Directory[] partDirectories = new Directory[numThreads];
+    File[] partDirs = new File[numThreads];
+    try {
+      List<Future<?>> futures = new ArrayList<>(numThreads);
+      for (int t = 0; t < numThreads; t++) {
+        int from = (int) ((long) numDocs * t / numThreads);
+        int to = (int) ((long) numDocs * (t + 1) / numThreads);
+        partDirs[t] = new File(_segmentIndexDir, _vectorColumn + ".hnsw.part" 
+ t);
+        partDirectories[t] = FSDirectory.open(partDirs[t].toPath());
+        Directory partDirectory = partDirectories[t];
+        futures.add(executor.submit(() -> {
+          // CREATE: a part directory left by a build that crashed before 
cleaning up must not add its documents
+          try (IndexWriter partWriter = new IndexWriter(partDirectory,
+              
VectorIndexUtils.getIndexWriterConfig(_vectorIndexConfig).setOpenMode(OpenMode.CREATE)))
 {
+            for (int docId = from; docId < to; docId++) {
+              partWriter.addDocument(toDocument(_bufferedVectors.get(docId), 
docId));
+            }
+            partWriter.commit();
+          }
+          return null;
+        }));
+      }
+      for (Future<?> future : futures) {
+        future.get();
+      }
+      _indexWriter.addIndexes(partDirectories);
+    } finally {
+      // On failure the other part writers may still be running: wait for them 
before closing and deleting their
+      // directories, so no files are written after the cleanup
+      executor.shutdownNow();
+      if (!executor.awaitTermination(PART_SHUTDOWN_TIMEOUT_SECONDS, 
TimeUnit.SECONDS)) {
+        LOGGER.warn("HNSW part writers for column: {} did not stop within 
{}s", _vectorColumn,
+            PART_SHUTDOWN_TIMEOUT_SECONDS);
+      }
+      IOUtils.close(partDirectories);
+      for (File partDir : partDirs) {

Review Comment:
   The part paths are recorded before the build owns them. An existing regular 
file at `bar.hnsw.part1` makes `FSDirectory.open` fail, and this cleanup then 
deletes that file. A timeout also lets cleanup close a directory while a writer 
still uses it, while an interruption in `awaitTermination` skips cleanup 
entirely. Use owned scratch space, cancel and join all workers before closing 
it, and preserve the original error. Keep the merge executor usable until its 
IndexWriter finishes closing.



##########
pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java:
##########
@@ -261,6 +266,15 @@ private static void validateHnswProperties(Map<String, 
String> properties) {
     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
+    Integer buildThreads = parsePositiveIntProperty(properties, 
"buildThreads", "HNSW buildThreads");

Review Comment:
   An explicit `buildThreads: null` passes `parsePositiveIntProperty`, then 
`Integer.parseInt(properties.getOrDefault(...))` fails during segment 
generation. Make validation and construction agree on null and cover that input.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java:
##########
@@ -100,32 +155,119 @@ public void add(Object[] values, @Nullable int[] 
dictIds) {
 
   @Override
   public void add(float[] document) {
+    if (_bufferedVectors != null) {
+      // Callers may reuse the array for the next row
+      _bufferedVectors.add(document.clone());
+      if (_bufferedVectors.size() <= _parallelBuildMaxDocs) {
+        return;
+      }
+      for (float[] buffered : _bufferedVectors) {
+        addDocument(buffered, _nextDocId++);
+      }
+      _bufferedVectors = null;
+      return;
+    }
+    addDocument(document, _nextDocId++);
+  }
+
+  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, int docId) {
     try {
-      _indexWriter.addDocument(docToIndex);
+      _indexWriter.addDocument(toDocument(vector, docId));
     } catch (Exception e) {
       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()
+      throws Exception {
+    int numDocs = _bufferedVectors.size();
+    int numThreads = Math.min(_buildThreads, Math.max(1, numDocs));
+    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
+    Directory[] partDirectories = new Directory[numThreads];
+    File[] partDirs = new File[numThreads];
+    try {
+      List<Future<?>> futures = new ArrayList<>(numThreads);
+      for (int t = 0; t < numThreads; t++) {
+        int from = (int) ((long) numDocs * t / numThreads);
+        int to = (int) ((long) numDocs * (t + 1) / numThreads);
+        partDirs[t] = new File(_segmentIndexDir, _vectorColumn + ".hnsw.part" 
+ t);
+        partDirectories[t] = FSDirectory.open(partDirs[t].toPath());
+        Directory partDirectory = partDirectories[t];
+        futures.add(executor.submit(() -> {
+          // CREATE: a part directory left by a build that crashed before 
cleaning up must not add its documents
+          try (IndexWriter partWriter = new IndexWriter(partDirectory,
+              
VectorIndexUtils.getIndexWriterConfig(_vectorIndexConfig).setOpenMode(OpenMode.CREATE)))
 {
+            for (int docId = from; docId < to; docId++) {
+              partWriter.addDocument(toDocument(_bufferedVectors.get(docId), 
docId));
+            }
+            partWriter.commit();
+          }
+          return null;
+        }));
+      }
+      for (Future<?> future : futures) {
+        future.get();
+      }
+      _indexWriter.addIndexes(partDirectories);
+    } finally {
+      // On failure the other part writers may still be running: wait for them 
before closing and deleting their
+      // directories, so no files are written after the cleanup
+      executor.shutdownNow();
+      if (!executor.awaitTermination(PART_SHUTDOWN_TIMEOUT_SECONDS, 
TimeUnit.SECONDS)) {
+        LOGGER.warn("HNSW part writers for column: {} did not stop within 
{}s", _vectorColumn,
+            PART_SHUTDOWN_TIMEOUT_SECONDS);
+      }
+      IOUtils.close(partDirectories);
+      for (File partDir : partDirs) {
+        if (partDir != null) {
+          FileUtils.deleteQuietly(partDir);
+        }
+      }
+    }
+    _nextDocId = numDocs;
+    _bufferedVectors.clear();
+  }
+
   @Override
   public void seal() {
     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();
+      }
+      if (_forceMerge) {
+        _indexWriter.forceMerge(1);
+      }
     } catch (Exception e) {
       throw new RuntimeException("Caught exception while sealing the HNSW 
index for column: " + _vectorColumn, e);
+    } finally {
+      shutDownMergeExecutor();
+    }
+  }
+
+  private void shutDownMergeExecutor() {
+    if (_mergeExecutor != null) {
+      _mergeExecutor.shutdownNow();
     }
   }
 
   @Override
   public void close()

Review Comment:
   `VectorIndexHandler` uses try-with-resources, so a worker failure in 
`seal()` is followed by `close()`. With `storeInSegmentFile=true`, close can 
then commit and pack an empty or partial index. A buffered zero-length vector 
triggers the worker failure. Roll back failed construction and pack only a 
successfully sealed build.



##########
pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/creator/impl/vector/HnswVectorIndexCreator.java:
##########
@@ -100,32 +155,119 @@ public void add(Object[] values, @Nullable int[] 
dictIds) {
 
   @Override
   public void add(float[] document) {
+    if (_bufferedVectors != null) {
+      // Callers may reuse the array for the next row
+      _bufferedVectors.add(document.clone());
+      if (_bufferedVectors.size() <= _parallelBuildMaxDocs) {
+        return;
+      }
+      for (float[] buffered : _bufferedVectors) {
+        addDocument(buffered, _nextDocId++);
+      }
+      _bufferedVectors = null;
+      return;
+    }
+    addDocument(document, _nextDocId++);
+  }
+
+  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, int docId) {
     try {
-      _indexWriter.addDocument(docToIndex);
+      _indexWriter.addDocument(toDocument(vector, docId));
     } catch (Exception e) {
       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()
+      throws Exception {
+    int numDocs = _bufferedVectors.size();
+    int numThreads = Math.min(_buildThreads, Math.max(1, numDocs));
+    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
+    Directory[] partDirectories = new Directory[numThreads];
+    File[] partDirs = new File[numThreads];
+    try {
+      List<Future<?>> futures = new ArrayList<>(numThreads);
+      for (int t = 0; t < numThreads; t++) {
+        int from = (int) ((long) numDocs * t / numThreads);
+        int to = (int) ((long) numDocs * (t + 1) / numThreads);
+        partDirs[t] = new File(_segmentIndexDir, _vectorColumn + ".hnsw.part" 
+ t);
+        partDirectories[t] = FSDirectory.open(partDirs[t].toPath());
+        Directory partDirectory = partDirectories[t];
+        futures.add(executor.submit(() -> {
+          // CREATE: a part directory left by a build that crashed before 
cleaning up must not add its documents
+          try (IndexWriter partWriter = new IndexWriter(partDirectory,
+              
VectorIndexUtils.getIndexWriterConfig(_vectorIndexConfig).setOpenMode(OpenMode.CREATE)))
 {

Review Comment:
   Each part writer inherits Lucene’s background merge scheduler. With a small 
RAM buffer it can start extra graph builds beyond the configured worker limit. 
`addIndexes` also calls `maybeMerge`, which can merge imported parts even with 
`forceMerge=false`. Bound the part writers’ merge work and cover retained leaf 
counts when enough parts are eligible for an automatic merge.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to