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


##########
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:
   The creator and writer factory now use the effective merge settings. With 
multiple workers and a forced merge, concurrentMerge=true selects the heap 
writer when mmap is omitted or false. Explicit mmapGraphOnMerge=true selects 
the single-threaded mmap writer. The writer-selection test covers all three 
cases and VectorBackendType.HNSW documents precedence and the replica recall 
tradeoff. [Fix and 
tests](https://github.com/apache/pinot/pull/20072/commits/c387b2b02ef3507c7ce0b4e09b703156441e439c)



##########
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 creator creates a unique scratch directory under its own index, cancels 
outstanding workers at the first observed failure and joins them before 
cleanup. The main writer closes before its merge executor. The creator tests 
preserve an unrelated bar.hnsw.part0 sentinel and verify cleanup on worker 
failure and interruption. [Fix and 
tests](https://github.com/apache/pinot/pull/20072/commits/c387b2b02ef3507c7ce0b4e09b703156441e439c)



##########
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:
   Part writers disable Lucene’s automatic merges. The main writer suspends its 
merge policy while it imports the parts. The 16-part regression verifies all 16 
leaves remain with forceMerge=false. A separate Lucene 9.12 probe recorded zero 
tasks on the dedicated executor for an ordinary merge and one task for the 
final forced merge. [Fix and 
tests](https://github.com/apache/pinot/pull/20072/commits/c387b2b02ef3507c7ce0b4e09b703156441e439c)



##########
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:
   A failed or interrupted build rolls back the writer and skips packing. The 
regression tests inject an invalid buffered vector and interrupt seal, then 
close the creator as VectorIndexHandler does. They check for a committed 
partial index, a combined file, and leftover scratch. The interruption case 
also verifies the caller’s interrupt flag. [Fix and 
tests](https://github.com/apache/pinot/pull/20072/commits/c387b2b02ef3507c7ce0b4e09b703156441e439c)



##########
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:
   The validator now rejects an explicit null buildThreads with a table-config 
error and defaults an omitted key to one. The validator suite includes the null 
case alongside the existing malformed, zero, and over-limit values. [Fix and 
tests](https://github.com/apache/pinot/pull/20072/commits/c387b2b02ef3507c7ce0b4e09b703156441e439c)



-- 
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