Apache Lucene open-source search software
Fix Lucene104ScalarQuantizedVectorsWriter to skip deleted docs when recomputing merge centroid (#16764)
Pranshu Shukla31c4511e591a
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 279700c709d..11101d2152b 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -623,6 +623,11 @@ OptimizationsBug Fixes---------------------++* GITHUB#16764: Fix Lucene104ScalarQuantizedVectorsWriter to exclude deleted docs when recomputing the+ merge centroid and correct the vector count so that it reflects the live docs after deletions, preventing+ query-side data from being prepared for merged fields that are too small to build a graph. (Pranshu Shukla)+* GITHUB#10153: Allow configurable buffer size in SegmentingTokenizerBase and recognize whitespace as safe boundary in ThaiTokenizer to avoid splitting words across buffer boundaries. (Kamthorn Krairaksa)* GITHUB#16620: Make HNSW merges abortable during graph initialization and repair, so that thediff --git a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.javaindex 80ef51c612b..1367fa73222 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/hnsw/FlatVectorsWriter.java@@ -79,9 +79,9 @@ public abstract class FlatVectorsWriter extends KnnVectorsWriter {** @param fieldInfo field to merge* @param mergeState merge state- * @param needsMergeScorer whether to prepare scorer data for a vector count. The writer tests- * this predicate against the count before deletions, which can exceed the number of vectors- * written.+ * @param needsMergeScorer whether to prepare scorer data for a vector count. The writer applies+ * this predicate to the number of live vectors written after deletions, so it does not+ * prepare data for a merged field that is too small to build a graph.* @return prepared data that the caller must close, or {@code null} if none was prepared, which* is what the default implementation returns and what any writer returns for a field it* cannot prepare for. The caller then builds the scorer itself.diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.javaindex 874718371ed..6be97e0ebe5 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene104/Lucene104ScalarQuantizedVectorsWriter.java@@ -55,6 +55,7 @@ import org.apache.lucene.store.FileDataHint;import org.apache.lucene.store.FileTypeHint;import org.apache.lucene.store.IOContext;import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.util.Bits;import org.apache.lucene.util.IOUtils;import org.apache.lucene.util.RamUsageEstimator;import org.apache.lucene.util.VectorUtil;@@ -361,8 +362,7 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {QUANTIZED_VECTOR_COMPONENT, "Vectors' count:" + vectorCount);}// Only asymmetric encodings have query-side records, and both FLOAT16 and FLOAT32 fields- // score graphs with them. The predicate sees vectorCount before deletions, so it can- // request data even when the merged field is too small to build a graph.+ // score graphs with them.boolean prepareQueryData =encoding.isAsymmetric()&& fieldInfo.getVectorEncoding().isFloatingPoint()@@ -642,7 +642,7 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {for (int i = 0; i < mergeState.knnVectorsReaders.length; i++) {KnnVectorsReader knnVectorsReader = mergeState.knnVectorsReaders[i];if (knnVectorsReader == null) continue;- count += accumulateCentroid(knnVectorsReader, fieldInfo, centroid);+ count += accumulateCentroid(knnVectorsReader, fieldInfo, mergeState.liveDocs[i], centroid);}if (count == 0) {return count;@@ -657,7 +657,8 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {}private static int accumulateCentroid(- KnnVectorsReader reader, FieldInfo fieldInfo, float[] centroid) throws IOException {+ KnnVectorsReader reader, FieldInfo fieldInfo, Bits liveDocs, float[] centroid)+ throws IOException {FloatVectorValues vectorValues = floatingPointVectorValues(reader, fieldInfo);if (vectorValues == null) {return 0;@@ -665,6 +666,9 @@ public class Lucene104ScalarQuantizedVectorsWriter extends FlatVectorsWriter {int count = 0;KnnVectorValues.DocIndexIterator iterator = vectorValues.iterator();for (int doc = iterator.nextDoc(); doc != NO_MORE_DOCS; doc = iterator.nextDoc()) {+ if (liveDocs != null && liveDocs.get(doc) == false) {+ continue;+ }count++;float[] vector = vectorValues.vectorValue(iterator.index());for (int j = 0; j < vector.length; j++) {diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.javaindex f253adb05d3..8cd6eb0b28b 100644--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene104/TestLucene104ScalarQuantizedVectorsFormat.java@@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.oneOf;import java.io.IOException;import java.util.ArrayList;+import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Locale;@@ -35,8 +36,10 @@ import org.apache.lucene.codecs.KnnVectorsFormat;import org.apache.lucene.codecs.KnnVectorsReader;import org.apache.lucene.codecs.lucene95.OrdToDocDISIReaderConfiguration;import org.apache.lucene.document.Document;+import org.apache.lucene.document.Field;import org.apache.lucene.document.KnnFloat16VectorField;import org.apache.lucene.document.KnnFloatVectorField;+import org.apache.lucene.document.StringField;import org.apache.lucene.index.CodecReader;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.Float16VectorValues;@@ -47,6 +50,7 @@ import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.index.KnnVectorValues;import org.apache.lucene.index.LeafReader;import org.apache.lucene.index.NoMergePolicy;+import org.apache.lucene.index.Term;import org.apache.lucene.index.VectorSimilarityFunction;import org.apache.lucene.search.DocIdSetIterator;import org.apache.lucene.search.IndexSearcher;@@ -187,6 +191,100 @@ public class TestLucene104ScalarQuantizedVectorsFormat extends BaseKnnVectorsFor// visited limit is not respected, as it is brute force search}+ /**+ * Regression test: when source segments have deleted documents, the per-field centroid recomputed+ * during a merge must be the mean of the live full-precision vectors only. Deleted documents must+ * not contribute to the centroid.+ */+ public void testCentroidSkipsDeletedDocsOnMerge() throws IOException {+ String fieldName = "field";+ int dims = 8;+ // Use a non-normalizing similarity so the stored centroid is the plain mean of live vectors.+ VectorSimilarityFunction similarityFunction = VectorSimilarityFunction.EUCLIDEAN;++ // Two groups of vectors: "keep" vectors all equal to 1.0, "delete" vectors all equal to 100.0.+ // After deleting every "delete" doc, the merged centroid must equal the all-ones vector.+ // If deleted docs were (incorrectly) included, each component would be pulled toward 100.0.+ int numKeep = 20;+ int numDelete = 15;++ try (Directory dir = newDirectory()) {+ try (IndexWriter w = new IndexWriter(dir, newIndexWriterConfig())) {+ // "keep" docs get ids with a "keep-" prefix (value 1.0); "delete" docs get ids with a+ // "del-" prefix (value 100.0). We later delete every "del-" doc by term.+ int keepId = 0;+ int delId = 0;+ // Segment 1: half the keep docs and half the delete docs.+ for (int i = 0; i < numKeep / 2; i++) {+ w.addDocument(+ centroidDoc(+ fieldName, "keep-" + keepId++, constantVector(dims, 1.0f), similarityFunction));+ }+ for (int i = 0; i < numDelete / 2; i++) {+ w.addDocument(+ centroidDoc(+ fieldName, "del-" + delId++, constantVector(dims, 100.0f), similarityFunction));+ }+ w.commit();++ // Segment 2: the remaining keep and delete docs.+ for (int i = numKeep / 2; i < numKeep; i++) {+ w.addDocument(+ centroidDoc(+ fieldName, "keep-" + keepId++, constantVector(dims, 1.0f), similarityFunction));+ }+ for (int i = numDelete / 2; i < numDelete; i++) {+ w.addDocument(+ centroidDoc(+ fieldName, "del-" + delId++, constantVector(dims, 100.0f), similarityFunction));+ }+ w.commit();++ // Delete every "del-" doc (all the 100.0-valued vectors).+ for (int d = 0; d < numDelete; d++) {+ w.deleteDocuments(new Term("id", "del-" + d));+ }+ w.commit();++ // Force merge into a single segment: the centroid is recalculated over source segment(s)+ // that carry deletions, which must be skipped.+ w.forceMerge(1);++ try (IndexReader reader = DirectoryReader.open(w)) {+ LeafReader r = getOnlyLeafReader(reader);+ FloatVectorValues vectorValues = r.getFloatVectorValues(fieldName);+ assertEquals(numKeep, vectorValues.size());++ QuantizedByteVectorValues qvectorValues =+ ((Lucene104ScalarQuantizedVectorsReader.ScalarQuantizedVectorValues) vectorValues)+ .getQuantizedVectorValues();+ float[] centroid = qvectorValues.getCentroid();+ assertEquals(dims, centroid.length);++ // The correct centroid is exactly the all-ones vector.+ for (int j = 0; j < dims; j++) {+ assertEquals(+ "centroid component " + j + " must ignore deleted docs", 1.0f, centroid[j], 1e-4f);+ }+ }+ }+ }+ }++ private static Document centroidDoc(+ String fieldName, String id, float[] vector, VectorSimilarityFunction similarityFunction) {+ Document doc = new Document();+ doc.add(new StringField("id", id, Field.Store.NO));+ doc.add(new KnnFloatVectorField(fieldName, vector, similarityFunction));+ return doc;+ }++ private static float[] constantVector(int dims, float value) {+ float[] v = new float[dims];+ Arrays.fill(v, value);+ return v;+ }+public void testQuantizedVectorsWriteAndRead() throws IOException {String fieldName = "field";int numVectors = random().nextInt(99, 500);