xiangfu0 commented on code in PR #17994: URL: https://github.com/apache/pinot/pull/17994#discussion_r3004685183
########## pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/IvfFlatVectorIndexReader.java: ########## @@ -0,0 +1,330 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.segment.index.readers.vector; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.PriorityQueue; +import org.apache.pinot.segment.local.segment.index.vector.IvfFlatVectorIndexCreator; +import org.apache.pinot.segment.local.utils.VectorDistanceFunction; +import org.apache.pinot.segment.spi.V1Constants; +import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig; +import org.apache.pinot.segment.spi.index.reader.NprobeAware; +import org.apache.pinot.segment.spi.index.reader.VectorIndexReader; +import org.roaringbitmap.buffer.MutableRoaringBitmap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Reader for IVF_FLAT (Inverted File with flat vectors) index. + * + * <p>Loads the entire index into memory at construction time for fast search. + * The search algorithm: + * <ol> + * <li>Computes distance from the query to all centroids.</li> + * <li>Selects the {@code nprobe} closest centroids.</li> + * <li>Scans all vectors in those centroids' inverted lists.</li> + * <li>Returns the top-K doc IDs as a bitmap.</li> + * </ol> + * + * <h3>Thread safety</h3> + * <p>This class is thread-safe for concurrent reads. The loaded index data is immutable + * after construction. The only mutable state is {@code _nprobe}, which is volatile to + * allow query-time tuning from another thread. However, the typical pattern is + * single-threaded: set nprobe, then call getDocIds.</p> + */ +public class IvfFlatVectorIndexReader implements VectorIndexReader, NprobeAware { + private static final Logger LOGGER = LoggerFactory.getLogger(IvfFlatVectorIndexReader.class); + + /** Default nprobe value when not explicitly set. */ + static final int DEFAULT_NPROBE = 4; + + // Index data loaded from file + private final int _dimension; + private final int _numVectors; + private final int _nlist; + private final VectorIndexConfig.VectorDistanceFunction _distanceFunction; + private final float[][] _centroids; + private final int[][] _listDocIds; + private final float[][][] _listVectors; + private final String _column; + + /** Number of centroids to probe during search. */ + private volatile int _nprobe; + + /** + * Opens and loads an IVF_FLAT index from disk. + * + * @param column the column name + * @param indexDir the segment index directory + * @param config the vector index configuration + * @throws RuntimeException if the index file cannot be read or is corrupt + */ + public IvfFlatVectorIndexReader(String column, File indexDir, VectorIndexConfig config) { + _column = column; + + // Determine nprobe from config + int configuredNprobe = DEFAULT_NPROBE; + if (config.getProperties() != null && config.getProperties().containsKey("nprobe")) { + configuredNprobe = Integer.parseInt(config.getProperties().get("nprobe")); + } + + File indexFile = findIvfFlatIndexFile(indexDir, column); + if (indexFile == null) { + throw new IllegalStateException( + "Failed to find IVF_FLAT index file for column: " + column + " in dir: " + indexDir); + } + + try (DataInputStream in = new DataInputStream(new FileInputStream(indexFile))) { + // --- Header --- + int magic = in.readInt(); + Preconditions.checkState(magic == IvfFlatVectorIndexCreator.MAGIC, + "Invalid IVF_FLAT magic: 0x%s, expected 0x%s", + Integer.toHexString(magic), Integer.toHexString(IvfFlatVectorIndexCreator.MAGIC)); + + int version = in.readInt(); + Preconditions.checkState(version == IvfFlatVectorIndexCreator.FORMAT_VERSION, + "Unsupported IVF_FLAT format version: %s, expected: %s", + version, IvfFlatVectorIndexCreator.FORMAT_VERSION); + + _dimension = in.readInt(); + _numVectors = in.readInt(); + _nlist = in.readInt(); + int distanceFunctionOrdinal = in.readInt(); + _distanceFunction = VectorIndexConfig.VectorDistanceFunction.values()[distanceFunctionOrdinal]; + + // Clamp nprobe to valid range + _nprobe = Math.min(configuredNprobe, _nlist); + if (_nprobe <= 0) { + _nprobe = Math.min(DEFAULT_NPROBE, _nlist); + } + + // --- Centroids --- + _centroids = new float[_nlist][_dimension]; + for (int c = 0; c < _nlist; c++) { + for (int d = 0; d < _dimension; d++) { + _centroids[c][d] = in.readFloat(); + } + } + + // --- Inverted Lists --- + _listDocIds = new int[_nlist][]; + _listVectors = new float[_nlist][][]; + + for (int c = 0; c < _nlist; c++) { + int listSize = in.readInt(); + _listDocIds[c] = new int[listSize]; + for (int i = 0; i < listSize; i++) { + _listDocIds[c][i] = in.readInt(); + } + _listVectors[c] = new float[listSize][_dimension]; + for (int i = 0; i < listSize; i++) { + for (int d = 0; d < _dimension; d++) { + _listVectors[c][i][d] = in.readFloat(); + } + } + } + + // We skip reading the offset table and footer since we read sequentially + + LOGGER.info("Loaded IVF_FLAT index for column: {}: {} vectors, {} centroids, dim={}, nprobe={}, distance={}", + column, _numVectors, _nlist, _dimension, _nprobe, _distanceFunction); + } catch (IOException e) { + throw new RuntimeException( + "Failed to load IVF_FLAT index for column: " + column + " from file: " + indexFile, e); + } + } + + @Override + public MutableRoaringBitmap getDocIds(float[] searchQuery, int topK) { + Preconditions.checkArgument(searchQuery.length == _dimension, + "Query dimension mismatch: expected %s, got %s", _dimension, searchQuery.length); + Preconditions.checkArgument(topK > 0, "topK must be positive, got: %s", topK); + + if (_numVectors == 0 || _nlist == 0) { + return new MutableRoaringBitmap(); + } + + int effectiveNprobe = Math.min(_nprobe, _nlist); + + // Step 1: Find the nprobe closest centroids + int[] probeCentroids = findClosestCentroids(searchQuery, effectiveNprobe); + + // Step 2: Scan all vectors in the selected inverted lists, maintaining a max-heap of size topK + // Max-heap: the largest distance is at the top, so we can efficiently evict the worst candidate. + int effectiveTopK = Math.min(topK, _numVectors); + PriorityQueue<ScoredDoc> maxHeap = new PriorityQueue<>(effectiveTopK, + (a, b) -> Float.compare(b._distance, a._distance)); + + for (int probeIdx : probeCentroids) { + int[] docIds = _listDocIds[probeIdx]; + float[][] vectors = _listVectors[probeIdx]; + + for (int i = 0; i < docIds.length; i++) { + float dist = VectorDistanceFunction.computeDistance(searchQuery, vectors[i], _distanceFunction); + if (maxHeap.size() < effectiveTopK) { + maxHeap.offer(new ScoredDoc(docIds[i], dist)); + } else if (dist < maxHeap.peek()._distance) { + maxHeap.poll(); + maxHeap.offer(new ScoredDoc(docIds[i], dist)); + } + } + } + + // Step 3: Collect results into a bitmap + MutableRoaringBitmap result = new MutableRoaringBitmap(); + for (ScoredDoc doc : maxHeap) { + result.add(doc._docId); + } + return result; + } + + /** + * Sets the number of centroids to probe during search. + * This allows query-time tuning of the recall/speed tradeoff. + * + * @param nprobe number of centroids to probe (clamped to [1, nlist]) + */ + public void setNprobe(int nprobe) { + _nprobe = Math.max(1, Math.min(nprobe, _nlist)); + } + + /** + * Returns the current nprobe setting. + */ + public int getNprobe() { + return _nprobe; + } + + @Override + public void close() + throws IOException { + // No resources to release -- all data is in Java heap arrays + } + + // ----------------------------------------------------------------------- + // Internal helpers + // ----------------------------------------------------------------------- + + /** + * Finds the n closest centroids to the given query vector. + * + * @param query the query vector + * @param n number of centroids to return + * @return array of centroid indices sorted by increasing distance + */ + private int[] findClosestCentroids(float[] query, int n) { + // Compute distance to each centroid + float[] centroidDistances = new float[_nlist]; + for (int c = 0; c < _nlist; c++) { + centroidDistances[c] = VectorDistanceFunction.computeDistance(query, _centroids[c], _distanceFunction); + } + + // Find top-n using partial sort + // For simplicity, use an indexed sort on centroid distances + Integer[] indices = new Integer[_nlist]; + for (int i = 0; i < _nlist; i++) { + indices[i] = i; + } + Arrays.sort(indices, (a, b) -> Float.compare(centroidDistances[a], centroidDistances[b])); + + int[] result = new int[n]; + for (int i = 0; i < n; i++) { + result[i] = indices[i]; + } + return result; Review Comment: Fixed in commit cf217b9 — replaced Integer[] boxing + full sort with primitive top-N insertion sort using float[] arrays. ########## pinot-core/src/main/java/org/apache/pinot/core/operator/filter/VectorSimilarityFilterOperator.java: ########## @@ -120,6 +157,104 @@ protected void explainAttributes(ExplainAttributeBuilder attributeBuilder) { attributeBuilder.putString("vectorIdentifier", _predicate.getLhs().getIdentifier()); attributeBuilder.putString("vectorLiteral", Arrays.toString(_predicate.getValue())); attributeBuilder.putLongIdempotent("topKtoSearch", _predicate.getTopK()); + if (_searchParams.isExactRerank()) { + attributeBuilder.putString("exactRerank", "true"); + } + } + + /** + * Executes the vector search with backend-specific parameter dispatch and optional rerank. + */ + private ImmutableRoaringBitmap executeSearch() { + String column = _predicate.getLhs().getIdentifier(); + float[] queryVector = _predicate.getValue(); + int topK = _predicate.getTopK(); + + // 1. Configure backend-specific parameters via interfaces + configureBackendParams(column); + + // 2. Determine effective search count (higher if rerank is enabled) + int searchCount = topK; + if (_searchParams.isExactRerank()) { + searchCount = _searchParams.getEffectiveMaxCandidates(topK); + } + + // 3. Execute ANN search + ImmutableRoaringBitmap annResults = _vectorIndexReader.getDocIds(queryVector, searchCount); + int annCandidateCount = annResults.getCardinality(); + + LOGGER.debug("Vector search on column: {}, backend: {}, topK: {}, searchCount: {}, annCandidates: {}", + column, getBackendName(), topK, searchCount, annCandidateCount); + + // 4. Apply exact rerank if requested + if (_searchParams.isExactRerank() && _forwardIndexReader != null && annCandidateCount > 0) { + ImmutableRoaringBitmap reranked = applyExactRerank(annResults, queryVector, topK, column); + LOGGER.debug("Exact rerank on column: {}, candidates: {} -> final: {}", + column, annCandidateCount, reranked.getCardinality()); + return reranked; + } + + return annResults; + } + + /** + * Configures backend-specific search parameters on the reader if it supports them. + */ + private void configureBackendParams(String column) { + // Set nprobe on IVF_FLAT readers + if (_vectorIndexReader instanceof NprobeAware) { + int nprobe = _searchParams.getNprobe(); + ((NprobeAware) _vectorIndexReader).setNprobe(nprobe); + LOGGER.debug("Set nprobe={} on IVF_FLAT reader for column: {}", nprobe, column); + } + } + + /** + * Re-scores ANN candidates using exact distance from the forward index and returns top-K. + */ + @SuppressWarnings("unchecked") + private ImmutableRoaringBitmap applyExactRerank(ImmutableRoaringBitmap annResults, float[] queryVector, + int topK, String column) { + // Max-heap: largest distance on top for efficient eviction + PriorityQueue<DocDistance> maxHeap = new PriorityQueue<>(topK + 1, + (a, b) -> Float.compare(b._distance, a._distance)); + + ForwardIndexReader rawReader = _forwardIndexReader; + try (ForwardIndexReaderContext context = rawReader.createContext()) { + org.roaringbitmap.IntIterator it = annResults.getIntIterator(); + while (it.hasNext()) { + int docId = it.next(); + float[] docVector = rawReader.getFloatMV(docId, context); + if (docVector == null || docVector.length == 0) { + continue; + } + float distance = ExactVectorScanFilterOperator.computeL2SquaredDistance(queryVector, docVector); + if (maxHeap.size() < topK) { + maxHeap.add(new DocDistance(docId, distance)); Review Comment: Acknowledged. Added TODO in commit cf217b9. Multi-distance rerank will be addressed in phase 2. ########## pinot-core/src/main/java/org/apache/pinot/core/operator/filter/ExactVectorScanFilterOperator.java: ########## @@ -0,0 +1,227 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.core.operator.filter; + +import com.google.common.base.CaseFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.PriorityQueue; +import org.apache.pinot.common.request.context.predicate.VectorSimilarityPredicate; +import org.apache.pinot.core.common.BlockDocIdSet; +import org.apache.pinot.core.common.Operator; +import org.apache.pinot.core.operator.ExplainAttributeBuilder; +import org.apache.pinot.core.operator.docidsets.BitmapDocIdSet; +import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader; +import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext; +import org.apache.pinot.spi.data.FieldSpec; +import org.apache.pinot.spi.trace.FilterType; +import org.apache.pinot.spi.trace.InvocationRecording; +import org.apache.pinot.spi.trace.Tracing; +import org.roaringbitmap.buffer.ImmutableRoaringBitmap; +import org.roaringbitmap.buffer.MutableRoaringBitmap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Fallback operator that performs exact brute-force vector similarity search by scanning the forward index. + * + * <p>This operator is used when no ANN vector index exists on a segment for the target column + * (e.g., the segment was built before the vector index was added, or the index type is not + * supported). It reads all vectors from the forward index, computes exact distances to the + * query vector, and returns the top-K closest document IDs.</p> + * + * <p>The distance computation uses L2 (Euclidean) squared distance. For COSINE similarity, + * vectors should be pre-normalized. This matches the behavior of Lucene's HNSW implementation.</p> + * + * <p>This operator is intentionally simple and correct rather than fast -- it is a safety net. + * A warning is logged when this operator is used because it scans all documents in the segment.</p> + * + * <p>This class is thread-safe for single-threaded execution per query (same as other filter operators).</p> + */ +public class ExactVectorScanFilterOperator extends BaseFilterOperator { + private static final Logger LOGGER = LoggerFactory.getLogger(ExactVectorScanFilterOperator.class); + private static final String EXPLAIN_NAME = "VECTOR_SIMILARITY_EXACT_SCAN"; + + private final ForwardIndexReader<?> _forwardIndexReader; + private final VectorSimilarityPredicate _predicate; + private final String _column; + private ImmutableRoaringBitmap _matches; + + /** + * Creates an exact scan operator. + * + * @param forwardIndexReader the forward index reader for the vector column + * @param predicate the vector similarity predicate containing query vector and top-K + * @param column the column name (for logging and explain) + * @param numDocs the total number of documents in the segment + */ + public ExactVectorScanFilterOperator(ForwardIndexReader<?> forwardIndexReader, + VectorSimilarityPredicate predicate, String column, int numDocs) { + super(numDocs, false); + _forwardIndexReader = forwardIndexReader; + _predicate = predicate; + _column = column; + } + + @Override + protected BlockDocIdSet getTrues() { + if (_matches == null) { + _matches = computeExactTopK(); + } + return new BitmapDocIdSet(_matches, _numDocs); + } + + @Override + public int getNumMatchingDocs() { + if (_matches == null) { + _matches = computeExactTopK(); + } + return _matches.getCardinality(); + } + + @Override + public boolean canProduceBitmaps() { + return true; + } + + @Override + public BitmapCollection getBitmaps() { + if (_matches == null) { + _matches = computeExactTopK(); + } + record(_matches); + return new BitmapCollection(_numDocs, false, _matches); + } + + @Override + public List<Operator> getChildOperators() { + return Collections.emptyList(); + } + + @Override + public String toExplainString() { + return EXPLAIN_NAME + "(indexLookUp:exact_scan" + + ", operator:" + _predicate.getType() + + ", vector identifier:" + _column + + ", vector literal:" + Arrays.toString(_predicate.getValue()) + + ", topK to search:" + _predicate.getTopK() + + ')'; + } + + @Override + protected String getExplainName() { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, EXPLAIN_NAME); + } + + @Override + protected void explainAttributes(ExplainAttributeBuilder attributeBuilder) { + super.explainAttributes(attributeBuilder); + attributeBuilder.putString("indexLookUp", "exact_scan"); + attributeBuilder.putString("operator", _predicate.getType().name()); + attributeBuilder.putString("vectorIdentifier", _column); + attributeBuilder.putString("vectorLiteral", Arrays.toString(_predicate.getValue())); + attributeBuilder.putLongIdempotent("topKtoSearch", _predicate.getTopK()); + } + + /** + * Performs brute-force exact search over all documents in the segment. + * Uses a max-heap to maintain the top-K closest vectors. + */ + @SuppressWarnings("unchecked") + private ImmutableRoaringBitmap computeExactTopK() { + LOGGER.warn("Performing exact vector scan fallback on column: {} for segment with {} docs. " + + "This is expensive -- consider adding a vector index.", _column, _numDocs); + + float[] queryVector = _predicate.getValue(); + int topK = _predicate.getTopK(); + + // Max-heap: entry with largest distance is at the top so we can efficiently evict it + PriorityQueue<DocDistance> maxHeap = new PriorityQueue<>(topK + 1, + (a, b) -> Float.compare(b._distance, a._distance)); + + ForwardIndexReader rawReader = _forwardIndexReader; + try (ForwardIndexReaderContext context = rawReader.createContext()) { + for (int docId = 0; docId < _numDocs; docId++) { + float[] docVector = rawReader.getFloatMV(docId, context); + if (docVector == null || docVector.length == 0) { + continue; + } + float distance = computeL2SquaredDistance(queryVector, docVector); + if (maxHeap.size() < topK) { + maxHeap.add(new DocDistance(docId, distance)); + } else if (distance < maxHeap.peek()._distance) { + maxHeap.poll(); + maxHeap.add(new DocDistance(docId, distance)); + } + } + } catch (Exception e) { + throw new RuntimeException("Error during exact vector scan on column: " + _column, e); + } + + MutableRoaringBitmap result = new MutableRoaringBitmap(); + for (DocDistance dd : maxHeap) { + result.add(dd._docId); + } + + LOGGER.debug("Exact vector scan on column: {} returned {} results from {} docs", + _column, result.getCardinality(), _numDocs); + + return result; + } + + /** + * Computes the squared L2 (Euclidean) distance between two vectors. + * Uses squared distance to avoid the sqrt, which is monotonic so does not affect ranking. + */ + static float computeL2SquaredDistance(float[] a, float[] b) { + int len = Math.min(a.length, b.length); Review Comment: Fixed in commit cf217b9 — now delegates to VectorFunctions.euclideanDistance() which validates dimensions match. ########## pinot-core/src/main/java/org/apache/pinot/core/operator/filter/ExactVectorScanFilterOperator.java: ########## @@ -0,0 +1,227 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.core.operator.filter; + +import com.google.common.base.CaseFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.PriorityQueue; +import org.apache.pinot.common.request.context.predicate.VectorSimilarityPredicate; +import org.apache.pinot.core.common.BlockDocIdSet; +import org.apache.pinot.core.common.Operator; +import org.apache.pinot.core.operator.ExplainAttributeBuilder; +import org.apache.pinot.core.operator.docidsets.BitmapDocIdSet; +import org.apache.pinot.segment.spi.index.reader.ForwardIndexReader; +import org.apache.pinot.segment.spi.index.reader.ForwardIndexReaderContext; +import org.apache.pinot.spi.data.FieldSpec; +import org.apache.pinot.spi.trace.FilterType; +import org.apache.pinot.spi.trace.InvocationRecording; +import org.apache.pinot.spi.trace.Tracing; +import org.roaringbitmap.buffer.ImmutableRoaringBitmap; +import org.roaringbitmap.buffer.MutableRoaringBitmap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Fallback operator that performs exact brute-force vector similarity search by scanning the forward index. + * + * <p>This operator is used when no ANN vector index exists on a segment for the target column + * (e.g., the segment was built before the vector index was added, or the index type is not + * supported). It reads all vectors from the forward index, computes exact distances to the + * query vector, and returns the top-K closest document IDs.</p> + * + * <p>The distance computation uses L2 (Euclidean) squared distance. For COSINE similarity, + * vectors should be pre-normalized. This matches the behavior of Lucene's HNSW implementation.</p> + * + * <p>This operator is intentionally simple and correct rather than fast -- it is a safety net. + * A warning is logged when this operator is used because it scans all documents in the segment.</p> + * + * <p>This class is thread-safe for single-threaded execution per query (same as other filter operators).</p> + */ +public class ExactVectorScanFilterOperator extends BaseFilterOperator { + private static final Logger LOGGER = LoggerFactory.getLogger(ExactVectorScanFilterOperator.class); + private static final String EXPLAIN_NAME = "VECTOR_SIMILARITY_EXACT_SCAN"; + + private final ForwardIndexReader<?> _forwardIndexReader; + private final VectorSimilarityPredicate _predicate; + private final String _column; + private ImmutableRoaringBitmap _matches; + + /** + * Creates an exact scan operator. + * + * @param forwardIndexReader the forward index reader for the vector column + * @param predicate the vector similarity predicate containing query vector and top-K + * @param column the column name (for logging and explain) + * @param numDocs the total number of documents in the segment + */ + public ExactVectorScanFilterOperator(ForwardIndexReader<?> forwardIndexReader, + VectorSimilarityPredicate predicate, String column, int numDocs) { + super(numDocs, false); + _forwardIndexReader = forwardIndexReader; + _predicate = predicate; + _column = column; + } + + @Override + protected BlockDocIdSet getTrues() { + if (_matches == null) { + _matches = computeExactTopK(); + } + return new BitmapDocIdSet(_matches, _numDocs); + } + + @Override + public int getNumMatchingDocs() { + if (_matches == null) { + _matches = computeExactTopK(); + } + return _matches.getCardinality(); + } + + @Override + public boolean canProduceBitmaps() { + return true; + } + + @Override + public BitmapCollection getBitmaps() { + if (_matches == null) { + _matches = computeExactTopK(); + } + record(_matches); + return new BitmapCollection(_numDocs, false, _matches); + } + + @Override + public List<Operator> getChildOperators() { + return Collections.emptyList(); + } + + @Override + public String toExplainString() { + return EXPLAIN_NAME + "(indexLookUp:exact_scan" + + ", operator:" + _predicate.getType() + + ", vector identifier:" + _column + + ", vector literal:" + Arrays.toString(_predicate.getValue()) + + ", topK to search:" + _predicate.getTopK() + + ')'; + } + + @Override + protected String getExplainName() { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, EXPLAIN_NAME); + } + + @Override + protected void explainAttributes(ExplainAttributeBuilder attributeBuilder) { + super.explainAttributes(attributeBuilder); + attributeBuilder.putString("indexLookUp", "exact_scan"); + attributeBuilder.putString("operator", _predicate.getType().name()); + attributeBuilder.putString("vectorIdentifier", _column); + attributeBuilder.putString("vectorLiteral", Arrays.toString(_predicate.getValue())); + attributeBuilder.putLongIdempotent("topKtoSearch", _predicate.getTopK()); + } + + /** + * Performs brute-force exact search over all documents in the segment. + * Uses a max-heap to maintain the top-K closest vectors. + */ + @SuppressWarnings("unchecked") + private ImmutableRoaringBitmap computeExactTopK() { + LOGGER.warn("Performing exact vector scan fallback on column: {} for segment with {} docs. " + + "This is expensive -- consider adding a vector index.", _column, _numDocs); + + float[] queryVector = _predicate.getValue(); + int topK = _predicate.getTopK(); + + // Max-heap: entry with largest distance is at the top so we can efficiently evict it + PriorityQueue<DocDistance> maxHeap = new PriorityQueue<>(topK + 1, + (a, b) -> Float.compare(b._distance, a._distance)); + + ForwardIndexReader rawReader = _forwardIndexReader; + try (ForwardIndexReaderContext context = rawReader.createContext()) { + for (int docId = 0; docId < _numDocs; docId++) { + float[] docVector = rawReader.getFloatMV(docId, context); + if (docVector == null || docVector.length == 0) { + continue; + } + float distance = computeL2SquaredDistance(queryVector, docVector); Review Comment: Acknowledged. Exact scan fallback uses L2 only in phase 1. Multi-distance support tracked for phase 2. ########## pinot-segment-local/src/main/java/org/apache/pinot/segment/local/segment/index/readers/vector/IvfFlatVectorIndexReader.java: ########## @@ -0,0 +1,330 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.segment.index.readers.vector; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.io.DataInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.PriorityQueue; +import org.apache.pinot.segment.local.segment.index.vector.IvfFlatVectorIndexCreator; +import org.apache.pinot.segment.local.utils.VectorDistanceFunction; +import org.apache.pinot.segment.spi.V1Constants; +import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig; +import org.apache.pinot.segment.spi.index.reader.NprobeAware; +import org.apache.pinot.segment.spi.index.reader.VectorIndexReader; +import org.roaringbitmap.buffer.MutableRoaringBitmap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Reader for IVF_FLAT (Inverted File with flat vectors) index. + * + * <p>Loads the entire index into memory at construction time for fast search. + * The search algorithm: + * <ol> + * <li>Computes distance from the query to all centroids.</li> + * <li>Selects the {@code nprobe} closest centroids.</li> + * <li>Scans all vectors in those centroids' inverted lists.</li> + * <li>Returns the top-K doc IDs as a bitmap.</li> + * </ol> + * + * <h3>Thread safety</h3> + * <p>This class is thread-safe for concurrent reads. The loaded index data is immutable + * after construction. The only mutable state is {@code _nprobe}, which is volatile to + * allow query-time tuning from another thread. However, the typical pattern is + * single-threaded: set nprobe, then call getDocIds.</p> + */ +public class IvfFlatVectorIndexReader implements VectorIndexReader, NprobeAware { + private static final Logger LOGGER = LoggerFactory.getLogger(IvfFlatVectorIndexReader.class); + + /** Default nprobe value when not explicitly set. */ + static final int DEFAULT_NPROBE = 4; + + // Index data loaded from file + private final int _dimension; + private final int _numVectors; + private final int _nlist; + private final VectorIndexConfig.VectorDistanceFunction _distanceFunction; + private final float[][] _centroids; + private final int[][] _listDocIds; + private final float[][][] _listVectors; + private final String _column; + + /** Number of centroids to probe during search. */ + private volatile int _nprobe; + + /** + * Opens and loads an IVF_FLAT index from disk. + * + * @param column the column name + * @param indexDir the segment index directory + * @param config the vector index configuration + * @throws RuntimeException if the index file cannot be read or is corrupt + */ + public IvfFlatVectorIndexReader(String column, File indexDir, VectorIndexConfig config) { + _column = column; + + // Determine nprobe from config + int configuredNprobe = DEFAULT_NPROBE; + if (config.getProperties() != null && config.getProperties().containsKey("nprobe")) { + configuredNprobe = Integer.parseInt(config.getProperties().get("nprobe")); + } + Review Comment: Fixed in commit cf217b9 — removed config-based nprobe parsing. Reader initializes to DEFAULT_NPROBE; query-time tuning via NprobeAware#setNprobe. ########## pinot-segment-spi/src/main/java/org/apache/pinot/segment/spi/index/creator/VectorIndexConfigValidator.java: ########## @@ -0,0 +1,211 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.spi.index.creator; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + + +/** + * Validates {@link VectorIndexConfig} for backend-specific correctness. + * + * <p>This validator ensures that: + * <ul> + * <li>Required common fields (vectorDimension, vectorDistanceFunction) are present and valid.</li> + * <li>The vectorIndexType resolves to a known {@link VectorBackendType}.</li> + * <li>Backend-specific properties are valid for the resolved backend type.</li> + * <li>Properties belonging to a different backend are rejected with a clear error message.</li> + * </ul> + * + * <p>Thread-safe: this class is stateless and all methods are static.</p> + */ +public final class VectorIndexConfigValidator { + + // HNSW-specific property keys + static final Set<String> HNSW_PROPERTIES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList("maxCon", "beamWidth", "maxDimensions", "maxBufferSizeMB", + "useCompoundFile", "mode", "commit", "commitIntervalMs", "commitDocs"))); + + // IVF_FLAT-specific property keys + static final Set<String> IVF_FLAT_PROPERTIES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList("nlist", "trainSampleSize", "trainingSeed", "minRowsForIndex"))); + + // Common property keys that appear in the properties map (legacy format stores common fields there too) + private static final Set<String> COMMON_PROPERTIES = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList("vectorIndexType", "vectorDimension", "vectorDistanceFunction", "version"))); + + private VectorIndexConfigValidator() { + } + + /** + * Validates the given {@link VectorIndexConfig} for backend-specific correctness. + * + * @param config the config to validate + * @throws IllegalArgumentException if validation fails + */ + public static void validate(VectorIndexConfig config) { + if (config.isDisabled()) { + return; + } + + VectorBackendType backendType = resolveBackendType(config); + validateCommonFields(config); + validateBackendSpecificProperties(config, backendType); + } + + /** + * Resolves the {@link VectorBackendType} from the config. Defaults to HNSW if the + * vectorIndexType field is null or empty, preserving backward compatibility. + * + * @param config the config to resolve from + * @return the resolved backend type + * @throws IllegalArgumentException if the vectorIndexType is not recognized + */ + public static VectorBackendType resolveBackendType(VectorIndexConfig config) { + String typeString = config.getVectorIndexType(); + if (typeString == null || typeString.isEmpty()) { + return VectorBackendType.HNSW; + } + return VectorBackendType.fromString(typeString); + } + + /** + * Validates common fields shared across all backend types. + */ + private static void validateCommonFields(VectorIndexConfig config) { + if (config.getVectorDimension() <= 0) { + throw new IllegalArgumentException( + "vectorDimension must be a positive integer, got: " + config.getVectorDimension()); + } + + if (config.getVectorDistanceFunction() == null) { + throw new IllegalArgumentException("vectorDistanceFunction is required"); + } + } + + /** + * Validates that the properties map only contains keys valid for the resolved backend type, + * and that backend-specific property values are within acceptable ranges. + */ + private static void validateBackendSpecificProperties(VectorIndexConfig config, VectorBackendType backendType) { + Map<String, String> properties = config.getProperties(); + if (properties == null || properties.isEmpty()) { + return; + } + + switch (backendType) { + case HNSW: + validateNoForeignProperties(properties, HNSW_PROPERTIES, IVF_FLAT_PROPERTIES, "HNSW", "IVF_FLAT"); + validateHnswProperties(properties); + break; + case IVF_FLAT: + validateNoForeignProperties(properties, IVF_FLAT_PROPERTIES, HNSW_PROPERTIES, "IVF_FLAT", "HNSW"); + validateIvfFlatProperties(properties); + break; + default: + throw new IllegalArgumentException("Unsupported vector backend type: " + backendType); + } + } + + /** + * Ensures that properties belonging to a foreign backend are not present. + */ + private static void validateNoForeignProperties(Map<String, String> properties, + Set<String> ownProperties, Set<String> foreignProperties, + String ownType, String foreignType) { + for (String key : properties.keySet()) { + if (COMMON_PROPERTIES.contains(key)) { Review Comment: Fixed in commit cf217b9 — updated Javadoc. In commit 71cfd92 — removed unused ownProperties parameter entirely. ########## pinot-segment-local/src/main/java/org/apache/pinot/segment/local/utils/VectorDistanceFunction.java: ########## @@ -0,0 +1,212 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.pinot.segment.local.utils; + +import org.apache.pinot.segment.spi.index.creator.VectorIndexConfig; + + +/** + * Pure-Java implementations of vector distance functions used by the IVF_FLAT index. + * + * <p>All distance functions return a non-negative value where lower means more similar. + * This convention allows a single min-heap to be used for top-K selection regardless + * of the distance metric.</p> Review Comment: Resolved — VectorDistanceFunction.java was deleted in commit 403ec36. Distance computation now delegates to VectorFunctions. -- 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]
