Skip to content

Apache Lucene open-source search software

Validate vector values in columnar addBatch (#16708)

Mayya Sharipova8d999e9487df
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 531fa28435f..cbc3f79c325 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -431,6 +431,10 @@ Improvements
* GITHUB#16718: Modernize ThaiAnalyzer default stopwords list based on contemporary Thai corpus
frequency analysis and linguistically validated stop words. (Kamthorn Krairaksa)
+* GITHUB#16708: IndexWriter#addBatch now rejects non-finite float vector values and, with cosine
+ similarity, zero vectors in VectorColumns, matching the checks done by KnnFloatVectorField and
+ KnnByteVectorField. (Mayya Sharipova)
+
* GITHUB#16298: Store doc values DISI data into a separate file. (Sagar Upadhyaya)
* GITHUB#16247: Introduce CachingCollectorManager to parallelize search when using CachingCollector.
diff --git a/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java b/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java
index 276f3d80a44..20c9e91df2a 100644
--- a/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java
+++ b/lucene/core/src/java/org/apache/lucene/document/KnnFloat16VectorField.java
@@ -47,6 +47,10 @@ public class KnnFloat16VectorField extends Field {
if (similarityFunction == null) {
throw new IllegalArgumentException("similarity function must not be null");
}
+ if (similarityFunction == VectorSimilarityFunction.COSINE
+ && VectorUtil.isZeroVectorFloat16(v)) {
+ throw new IllegalArgumentException("zero vector not allowed with cosine similarity function");
+ }
FieldType type = new FieldType();
type.setVectorAttributes(dimension, VectorEncoding.FLOAT16, similarityFunction);
type.freeze();
@@ -86,6 +90,10 @@ public class KnnFloat16VectorField extends Field {
throw new IllegalArgumentException(
"value length " + value.length + " must match field dimension " + type.vectorDimension());
}
+ if (type.vectorSimilarityFunction() == VectorSimilarityFunction.COSINE
+ && VectorUtil.isZeroVectorFloat16(value)) {
+ throw new IllegalArgumentException("zero vector not allowed with cosine similarity function");
+ }
fieldsData = VectorUtil.checkFiniteFloat16(value);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java b/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
index 2d62e81a311..1d5973a2351 100644
--- a/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
+++ b/lucene/core/src/java/org/apache/lucene/document/column/ColumnValidation.java
@@ -20,6 +20,8 @@ import org.apache.lucene.document.StoredValue;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexableFieldType;
+import org.apache.lucene.index.VectorSimilarityFunction;
+import org.apache.lucene.util.VectorUtil;
/**
* Static validation and bounds-checking helpers for the columnar indexing path. These helpers are
@@ -348,4 +350,87 @@ public final class ColumnValidation {
+ batchDocID);
}
}
+
+ /**
+ * Throws if a float vector has a non-finite component, or is a zero vector while {@code
+ * similarityFunction} is {@link VectorSimilarityFunction#COSINE COSINE}. Mirrors the checks done
+ * by {@link org.apache.lucene.document.KnnFloatVectorField}.
+ */
+ public static void checkFloatVectorValue(
+ VectorColumn<?> column,
+ float[] vector,
+ VectorSimilarityFunction similarityFunction,
+ int batchDocID) {
+ boolean isZero = true;
+ for (int i = 0; i < vector.length; i++) {
+ if (Float.isFinite(vector[i]) == false) {
+ throw new IllegalArgumentException(
+ "VectorColumn \""
+ + column.name()
+ + "\" has non-finite value at vector["
+ + i
+ + "]="
+ + vector[i]
+ + " at batch doc "
+ + batchDocID);
+ }
+ isZero = isZero & (vector[i] == 0);
+ }
+ if (isZero && similarityFunction == VectorSimilarityFunction.COSINE) {
+ throw zeroCosineVector(column, batchDocID);
+ }
+ }
+
+ /**
+ * Throws if a byte vector is a zero vector while {@code similarityFunction} is {@link
+ * VectorSimilarityFunction#COSINE COSINE}. Mirrors the checks done by {@link
+ * org.apache.lucene.document.KnnByteVectorField}.
+ */
+ public static void checkByteVectorValue(
+ VectorColumn<?> column,
+ byte[] vector,
+ VectorSimilarityFunction similarityFunction,
+ int batchDocID) {
+ if (similarityFunction == VectorSimilarityFunction.COSINE && VectorUtil.isZeroVector(vector)) {
+ throw zeroCosineVector(column, batchDocID);
+ }
+ }
+
+ /**
+ * Throws if a float16 vector, encoded as {@code short[]}, has a non-finite component, or is a
+ * zero vector while {@code similarityFunction} is {@link VectorSimilarityFunction#COSINE COSINE}.
+ * Mirrors the checks done by {@link org.apache.lucene.document.KnnFloat16VectorField}.
+ */
+ public static void checkFloat16VectorValue(
+ VectorColumn<?> column,
+ short[] vector,
+ VectorSimilarityFunction similarityFunction,
+ int batchDocID) {
+ for (int i = 0; i < vector.length; i++) {
+ if ((vector[i] & 0x7C00) == 0x7C00) {
+ throw new IllegalArgumentException(
+ "VectorColumn \""
+ + column.name()
+ + "\" has non-finite float16 value at vector["
+ + i
+ + "]="
+ + Float.float16ToFloat(vector[i])
+ + " at batch doc "
+ + batchDocID);
+ }
+ }
+ if (similarityFunction == VectorSimilarityFunction.COSINE
+ && VectorUtil.isZeroVectorFloat16(vector)) {
+ throw zeroCosineVector(column, batchDocID);
+ }
+ }
+
+ private static IllegalArgumentException zeroCosineVector(VectorColumn<?> column, int batchDocID) {
+ return new IllegalArgumentException(
+ "VectorColumn \""
+ + column.name()
+ + "\" has a zero vector at batch doc "
+ + batchDocID
+ + ", which is not allowed with cosine similarity function");
+ }
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
index 03dab23d76b..bb38b9cd0a3 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexingChain.java
@@ -1260,6 +1260,7 @@ final class IndexingChain implements Accountable {
throws IOException {
final VectorEncoding encoding = fieldType.vectorEncoding();
final int dimension = fieldType.vectorDimension();
+ final VectorSimilarityFunction similarityFunction = fieldType.vectorSimilarityFunction();
final ObjectTupleCursor<?> cursor = column.tuples();
int prevBatchDocID = -1;
int consumed = 0;
@@ -1273,6 +1274,7 @@ final class IndexingChain implements Accountable {
ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
byte[] vec = (byte[]) cursor.value();
ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
+ ColumnValidation.checkByteVectorValue(column, vec, similarityFunction, batchDocID);
writer.addValue(baseDocID + batchDocID, vec);
prevBatchDocID = batchDocID;
consumed++;
@@ -1286,6 +1288,7 @@ final class IndexingChain implements Accountable {
ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
short[] vec = (short[]) cursor.value();
ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
+ ColumnValidation.checkFloat16VectorValue(column, vec, similarityFunction, batchDocID);
writer.addValue(baseDocID + batchDocID, vec);
prevBatchDocID = batchDocID;
consumed++;
@@ -1299,6 +1302,7 @@ final class IndexingChain implements Accountable {
ColumnValidation.checkVectorDocIDStrictlyIncreasing(column, batchDocID, prevBatchDocID);
float[] vec = (float[]) cursor.value();
ColumnValidation.checkVectorDimension(column, vec.length, dimension, batchDocID);
+ ColumnValidation.checkFloatVectorValue(column, vec, similarityFunction, batchDocID);
writer.addValue(baseDocID + batchDocID, vec);
prevBatchDocID = batchDocID;
consumed++;
diff --git a/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java b/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
index 614d8aa8239..4d89ac68dcd 100644
--- a/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
+++ b/lucene/core/src/java/org/apache/lucene/util/VectorUtil.java
@@ -522,6 +522,19 @@ public final class VectorUtil {
return true;
}
+ /**
+ * Returns true if all dimensions of provided float16 vector, encoded as {@code short[]}, are zero
+ * (either {@code +0} or {@code -0}), false otherwise.
+ */
+ public static boolean isZeroVectorFloat16(short[] v) {
+ for (short value : v) {
+ if ((value & 0x7FFF) != 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
/** Returns true if all dimensions of provided vector are zero, false otherwise. */
public static boolean isZeroVector(byte[] v) {
for (byte value : v) {
diff --git a/lucene/core/src/test/org/apache/lucene/document/TestField.java b/lucene/core/src/test/org/apache/lucene/document/TestField.java
index 26dcb96a051..4ee31e7fd4a 100644
--- a/lucene/core/src/test/org/apache/lucene/document/TestField.java
+++ b/lucene/core/src/test/org/apache/lucene/document/TestField.java
@@ -842,6 +842,32 @@ public class TestField extends LuceneTestCase {
field.setVectorValue(new short[] {two, one, Float.floatToFloat16(4f)});
}
+ public void testKnnFloat16FieldZeroVectors() {
+ short zero = Float.floatToFloat16(0f);
+ short negZero = Float.floatToFloat16(-0f);
+ short[] zeroVector = {zero, negZero, zero};
+
+ IllegalArgumentException zeroError =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> new KnnFloat16VectorField("knnF16", zeroVector, VectorSimilarityFunction.COSINE));
+ assertTrue(zeroError.getMessage(), zeroError.getMessage().contains("zero vector not allowed"));
+
+ KnnFloat16VectorField cosineField =
+ new KnnFloat16VectorField(
+ "knnF16",
+ new short[] {Float.floatToFloat16(1f), zero, Float.floatToFloat16(2f)},
+ VectorSimilarityFunction.COSINE);
+ zeroError =
+ expectThrows(IllegalArgumentException.class, () -> cosineField.setVectorValue(zeroVector));
+ assertTrue(zeroError.getMessage(), zeroError.getMessage().contains("zero vector not allowed"));
+
+ // non-COSINE fields allow zero vectors
+ KnnFloat16VectorField euclideanField =
+ new KnnFloat16VectorField("knnF16Euc", zeroVector, VectorSimilarityFunction.EUCLIDEAN);
+ euclideanField.setVectorValue(zeroVector);
+ }
+
public void testKnnFloat16QueryNonFinite() {
short one = Float.floatToFloat16(1f);
diff --git a/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java b/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
index aa2ff860b98..b7c5ad2bbea 100644
--- a/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
+++ b/lucene/core/src/test/org/apache/lucene/document/column/ColumnBatchTestUtil.java
@@ -45,6 +45,13 @@ public class ColumnBatchTestUtil {
return type;
}
+ public static FieldType float16VectorType(int dimension, VectorSimilarityFunction sim) {
+ FieldType type = new FieldType();
+ type.setVectorAttributes(dimension, VectorEncoding.FLOAT16, sim);
+ type.freeze();
+ return type;
+ }
+
public static ColumnBatch simpleBatch(int numDocs, Column... columns) {
return new ColumnBatch() {
@Override
@@ -474,6 +481,34 @@ public class ColumnBatchTestUtil {
}
}
+ public static class ArrayDenseFloat16VectorColumn extends VectorColumn<short[]> {
+ private final short[][] values;
+
+ public ArrayDenseFloat16VectorColumn(
+ String name, IndexableFieldType fieldType, short[][] values) {
+ super(name, fieldType, Density.DENSE);
+ this.values = values;
+ }
+
+ @Override
+ public ObjectTupleCursor<short[]> tuples() {
+ return new ObjectTupleCursor<>() {
+ int pos = -1;
+
+ @Override
+ public int nextDoc() {
+ pos++;
+ return pos < values.length ? pos : DocIdSetIterator.NO_MORE_DOCS;
+ }
+
+ @Override
+ public short[] value() {
+ return values[pos];
+ }
+ };
+ }
+ }
+
// ---------------------------------------------------------------------------
// Throwing-cursor helpers: each variant throws the supplied RuntimeException
// at a designated cursor index so tests can exercise the failure-cleanup path
diff --git a/lucene/core/src/test/org/apache/lucene/document/column/TestColumnBatchVectorColumn.java b/lucene/core/src/test/org/apache/lucene/document/column/TestColumnBatchVectorColumn.java
index 777e659cca7..b6b39051d1d 100644
--- a/lucene/core/src/test/org/apache/lucene/document/column/TestColumnBatchVectorColumn.java
+++ b/lucene/core/src/test/org/apache/lucene/document/column/TestColumnBatchVectorColumn.java
@@ -19,10 +19,12 @@ package org.apache.lucene.document.column;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayBinaryColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayByteVectorColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDenseByteVectorColumn;
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDenseFloat16VectorColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayDenseFloatVectorColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayFloatVectorColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.ArrayLongColumn;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.byteVectorType;
+import static org.apache.lucene.document.column.ColumnBatchTestUtil.float16VectorType;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.floatVectorType;
import static org.apache.lucene.document.column.ColumnBatchTestUtil.simpleBatch;
@@ -196,6 +198,106 @@ public class TestColumnBatchVectorColumn extends LuceneTestCase {
dir.close();
}
+ public void testFloatVectorValueValidation() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType euclidean = floatVectorType(2, VectorSimilarityFunction.EUCLIDEAN);
+ FieldType cosine = floatVectorType(2, VectorSimilarityFunction.COSINE);
+
+ // non-finite, dense
+ float bad = random().nextBoolean() ? Float.NaN : Float.POSITIVE_INFINITY;
+ float[][] denseVectors = {{1f, 2f}, {3f, bad}};
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(
+ 2, new ArrayDenseFloatVectorColumn("euc", euclidean, denseVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("non-finite value at vector[1]"));
+ assertTrue(e.getMessage(), e.getMessage().contains("at batch doc 1"));
+
+ // non-finite, sparse
+ int[] docIds = {0, 2};
+ float[][] sparseVectors = {{1f, 2f}, {Float.NEGATIVE_INFINITY, 4f}};
+ e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(
+ 3, new ArrayFloatVectorColumn("euc", euclidean, docIds, sparseVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("non-finite value at vector[0]"));
+ assertTrue(e.getMessage(), e.getMessage().contains("at batch doc 2"));
+
+ // zero vector with COSINE
+ float[][] zeroVectors = {{1f, 2f}, {0f, 0f}};
+ e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(2, new ArrayDenseFloatVectorColumn("cos", cosine, zeroVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("zero vector at batch doc 1"));
+
+ w.rollback();
+ dir.close();
+ }
+
+ public void testFloat16VectorValueValidation() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType euclidean = float16VectorType(2, VectorSimilarityFunction.EUCLIDEAN);
+ FieldType cosine = float16VectorType(2, VectorSimilarityFunction.COSINE);
+
+ // non-finite
+ short bad = Float.floatToFloat16(random().nextBoolean() ? Float.NaN : Float.NEGATIVE_INFINITY);
+ short[][] nonFiniteVectors = {{Float.floatToFloat16(1f), bad}};
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(
+ 1, new ArrayDenseFloat16VectorColumn("euc", euclidean, nonFiniteVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("non-finite float16 value at vector[1]"));
+
+ // zero vector with COSINE
+ short[][] zeroVectors = {
+ {Float.floatToFloat16(1f), Float.floatToFloat16(2f)},
+ {Float.floatToFloat16(0f), Float.floatToFloat16(-0f)}
+ };
+ e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(2, new ArrayDenseFloat16VectorColumn("cos", cosine, zeroVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("zero vector at batch doc 1"));
+
+ w.rollback();
+ dir.close();
+ }
+
+ public void testByteVectorValueValidation() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
+ FieldType cosine = byteVectorType(2, VectorSimilarityFunction.COSINE);
+
+ // zero vector with COSINE
+ byte[][] zeroVectors = {{0, 0}, {1, 2}};
+ IllegalArgumentException e =
+ expectThrows(
+ IllegalArgumentException.class,
+ () ->
+ w.addBatch(
+ simpleBatch(2, new ArrayDenseByteVectorColumn("cos", cosine, zeroVectors))));
+ assertTrue(e.getMessage(), e.getMessage().contains("zero vector at batch doc 0"));
+
+ w.rollback();
+ dir.close();
+ }
+
public void testZeroDimensionFieldTypeFails() {
FieldType bad = new FieldType();
// No vector attributes set -> vectorDimension() == 0