JingsongLi commented on code in PR #10569: URL: https://github.com/apache/paimon/pull/10569#discussion_r4306382978
########## paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/read/SparkDataEvolutionBatchVectorRead.java: ########## @@ -0,0 +1,297 @@ +/* + * 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.paimon.spark.read; + +import org.apache.paimon.globalindex.GlobalIndexReadThreadPool; +import org.apache.paimon.globalindex.GlobalIndexResult; +import org.apache.paimon.globalindex.GlobalIndexResultSerializer; +import org.apache.paimon.globalindex.GlobalIndexer; +import org.apache.paimon.globalindex.GlobalIndexerFactoryUtils; +import org.apache.paimon.globalindex.ScoredGlobalIndexResult; +import org.apache.paimon.index.IndexPathFactory; +import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.source.DataEvolutionBatchVectorRead; +import org.apache.paimon.table.source.IndexVectorSearchSplit; +import org.apache.paimon.table.source.RawVectorSearchSplit; +import org.apache.paimon.types.DataField; +import org.apache.paimon.utils.InstantiationUtil; +import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.RoaringNavigableMap64; +import org.apache.paimon.utils.SerializableFunction; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; + +/** + * Spark-aware {@link DataEvolutionBatchVectorRead}. Each Spark task evaluates every query vector + * against its split group, and the driver merges one result per query in input order. + */ +public class SparkDataEvolutionBatchVectorRead extends DataEvolutionBatchVectorRead { + + private static final long serialVersionUID = 1L; + + public SparkDataEvolutionBatchVectorRead( + FileStoreTable table, + @Nullable PartitionPredicate partitionFilter, + @Nullable Predicate filter, + int limit, + DataField vectorColumn, + float[][] vectors, + @Nullable Map<String, String> options) { + super(table, partitionFilter, filter, limit, vectorColumn, vectors, options); + } + + @Override + protected ScoredGlobalIndexResult[] readIndexedBatch( + List<IndexVectorSearchSplit> splits, GlobalIndexer globalIndexer) { + int parallelism = sparkParallelism(); + if (splits.size() < parallelism * 2) { + return super.readIndexedBatch(splits, globalIndexer); + } + + List<RoaringNavigableMap64> preFilters = preFilters(splits); + String indexType = vectorIndexType(splits); + int searchLimit = indexedSearchLimit(indexType); + int queryCount = vectors.length; + List<SparkVectorSearchSupport.SerializedSplit> serializedSplits = + new ArrayList<>(splits.size()); + for (int i = 0; i < splits.size(); i++) { + try { + IndexVectorSearchSplit split = splits.get(i); + RoaringNavigableMap64 preFilter = preFilters.isEmpty() ? null : preFilters.get(i); + serializedSplits.add( + new SparkVectorSearchSupport.SerializedSplit( + InstantiationUtil.serializeObject(split), + preFilter == null + ? null + : InstantiationUtil.serializeObject(preFilter))); + } catch (IOException e) { + throw new RuntimeException("Failed to serialize VectorSearchSplit", e); + } + } + List<List<SparkVectorSearchSupport.SerializedSplit>> splitGroups = + SparkVectorSearchSupport.splitGroups(serializedSplits, parallelism); + SerializableFunction<List<SparkVectorSearchSupport.SerializedSplit>, byte[][]> task = + group -> evaluateIndexGroup(group, indexType, searchLimit, queryCount, parallelism); + + List<byte[][]> remoteResults = mapInSpark(splitGroups, task, splitGroups.size()); + ScoredGlobalIndexResult[] merged = + mergeRemoteResults(remoteResults, queryCount, searchLimit); + // Avoid loading the indexer when refine is off; maybeRerankIndexedBatchResults repeats this + // check. + if (configuredRefineFactor(indexType) == 0) { + return merged; + } + GlobalIndexer rerankGlobalIndexer = + globalIndexer == null ? createGlobalIndexer(splits) : globalIndexer; + return maybeRerankIndexedBatchResults(merged, indexType, rerankGlobalIndexer); Review Comment: [P2] Propagate the persisted metric back before driver-side reranking In the distributed branch all `createReader` calls happen on newly constructed executor indexers, so the original driver indexer passed here never learns the metric persisted in an es-index shard. ESIndexGlobalIndexer only sets `readerVectorMetric` inside `createReader`; before that, `metric()` returns the current table configuration (cosine by default). The local batch path opens readers on this same indexer before reranking, and the existing `persistedMetricOverridesCurrentTableConfiguration` test explicitly covers persisted euclidean overriding configured cosine. With at least two shards at thread-num=1, an index built with euclidean supplied only to the build procedure, and refine-factor > 0, this line instead reranks those L2 candidates using cosine and can select a different top-1 (query [1,0], candidates [2,0] and [1,0.1]). The unchanged driver indexer is also used when merging uncovered raw rows, mixing incompatible scores. Please resolve/validate the effective metric from shard metadata on the driver, or return it with executor results, and cover a persisted metric that differs from the table default. ########## paimon-spark/paimon-spark-common/src/main/java/org/apache/paimon/spark/read/SparkDataEvolutionBatchVectorRead.java: ########## @@ -0,0 +1,297 @@ +/* + * 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.paimon.spark.read; + +import org.apache.paimon.globalindex.GlobalIndexReadThreadPool; +import org.apache.paimon.globalindex.GlobalIndexResult; +import org.apache.paimon.globalindex.GlobalIndexResultSerializer; +import org.apache.paimon.globalindex.GlobalIndexer; +import org.apache.paimon.globalindex.GlobalIndexerFactoryUtils; +import org.apache.paimon.globalindex.ScoredGlobalIndexResult; +import org.apache.paimon.index.IndexPathFactory; +import org.apache.paimon.partition.PartitionPredicate; +import org.apache.paimon.predicate.Predicate; +import org.apache.paimon.table.FileStoreTable; +import org.apache.paimon.table.source.DataEvolutionBatchVectorRead; +import org.apache.paimon.table.source.IndexVectorSearchSplit; +import org.apache.paimon.table.source.RawVectorSearchSplit; +import org.apache.paimon.types.DataField; +import org.apache.paimon.utils.InstantiationUtil; +import org.apache.paimon.utils.Range; +import org.apache.paimon.utils.RoaringNavigableMap64; +import org.apache.paimon.utils.SerializableFunction; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; + +/** + * Spark-aware {@link DataEvolutionBatchVectorRead}. Each Spark task evaluates every query vector + * against its split group, and the driver merges one result per query in input order. + */ +public class SparkDataEvolutionBatchVectorRead extends DataEvolutionBatchVectorRead { + + private static final long serialVersionUID = 1L; + + public SparkDataEvolutionBatchVectorRead( + FileStoreTable table, + @Nullable PartitionPredicate partitionFilter, + @Nullable Predicate filter, + int limit, + DataField vectorColumn, + float[][] vectors, + @Nullable Map<String, String> options) { + super(table, partitionFilter, filter, limit, vectorColumn, vectors, options); + } + + @Override + protected ScoredGlobalIndexResult[] readIndexedBatch( + List<IndexVectorSearchSplit> splits, GlobalIndexer globalIndexer) { + int parallelism = sparkParallelism(); + if (splits.size() < parallelism * 2) { + return super.readIndexedBatch(splits, globalIndexer); + } + + List<RoaringNavigableMap64> preFilters = preFilters(splits); + String indexType = vectorIndexType(splits); + int searchLimit = indexedSearchLimit(indexType); + int queryCount = vectors.length; + List<SparkVectorSearchSupport.SerializedSplit> serializedSplits = + new ArrayList<>(splits.size()); + for (int i = 0; i < splits.size(); i++) { + try { + IndexVectorSearchSplit split = splits.get(i); + RoaringNavigableMap64 preFilter = preFilters.isEmpty() ? null : preFilters.get(i); + serializedSplits.add( + new SparkVectorSearchSupport.SerializedSplit( + InstantiationUtil.serializeObject(split), + preFilter == null + ? null + : InstantiationUtil.serializeObject(preFilter))); + } catch (IOException e) { + throw new RuntimeException("Failed to serialize VectorSearchSplit", e); + } + } + List<List<SparkVectorSearchSupport.SerializedSplit>> splitGroups = + SparkVectorSearchSupport.splitGroups(serializedSplits, parallelism); + SerializableFunction<List<SparkVectorSearchSupport.SerializedSplit>, byte[][]> task = + group -> evaluateIndexGroup(group, indexType, searchLimit, queryCount, parallelism); + + List<byte[][]> remoteResults = mapInSpark(splitGroups, task, splitGroups.size()); + ScoredGlobalIndexResult[] merged = + mergeRemoteResults(remoteResults, queryCount, searchLimit); + // Avoid loading the indexer when refine is off; maybeRerankIndexedBatchResults repeats this + // check. + if (configuredRefineFactor(indexType) == 0) { + return merged; + } + GlobalIndexer rerankGlobalIndexer = + globalIndexer == null ? createGlobalIndexer(splits) : globalIndexer; + return maybeRerankIndexedBatchResults(merged, indexType, rerankGlobalIndexer); + } + + @Override + protected List<GlobalIndexResult> combineWithRaw( + ScoredGlobalIndexResult[] indexedResults, + List<RawVectorSearchSplit> rawSplits, + @Nullable GlobalIndexer globalIndexer, + @Nullable RoaringNavigableMap64 rawPreFilter) { + List<Range> rawRowRanges = rawRowRanges(rawSplits); + int parallelism = sparkParallelism(); + if (rawRowRanges.isEmpty() + || SparkVectorSearchSupport.rawRowCount(rawRowRanges) < parallelism * 2L) { + return super.combineWithRaw(indexedResults, rawSplits, globalIndexer, rawPreFilter); + } + + String metric = rawSearchMetric(rawSearchIndexer(rawSplits, globalIndexer)); + int queryCount = vectors.length; + List<List<Range>> rangeGroups = + SparkVectorSearchSupport.rangeGroups(rawRowRanges, parallelism); + List<SparkVectorSearchSupport.SerializedSplit> serializedSplits = + new ArrayList<>(rangeGroups.size()); + for (List<Range> rangeGroup : rangeGroups) { + try { + serializedSplits.add( + new SparkVectorSearchSupport.SerializedSplit( + InstantiationUtil.serializeObject(rangeGroup), + rawPreFilter == null + ? null + : InstantiationUtil.serializeObject(rawPreFilter))); + } catch (IOException e) { + throw new RuntimeException("Failed to serialize raw vector row ranges", e); + } + } + List<List<SparkVectorSearchSupport.SerializedSplit>> splitGroups = + SparkVectorSearchSupport.splitGroups(serializedSplits, parallelism); + SerializableFunction<List<SparkVectorSearchSupport.SerializedSplit>, byte[][]> task = + group -> evaluateRawGroup(group, metric, queryCount); + + List<byte[][]> remoteResults = mapInSpark(splitGroups, task, splitGroups.size()); + ScoredGlobalIndexResult[] rawResults = mergeRemoteResults(remoteResults, queryCount, limit); + List<GlobalIndexResult> results = new ArrayList<>(queryCount); + for (int i = 0; i < queryCount; i++) { + results.add(indexedResults[i].or(rawResults[i]).topK(limit)); + } + return results; + } + + private byte[][] evaluateIndexGroup( + List<SparkVectorSearchSupport.SerializedSplit> group, + String indexType, + int searchLimit, + int queryCount, + int parallelism) { + GlobalIndexer taskGlobalIndexer = + GlobalIndexerFactoryUtils.load(indexType) + .create( + Collections.singletonList(vectorColumn), Review Comment: [P2] Preserve every indexed field when rebuilding the executor indexer The normal batch path constructs its indexer from `GlobalIndexMeta.getIndexedFields(table.rowType())`, including `extraFieldIds`. This new executor path instead supplies only the vector column. A supported multi-field index (for example an es-index containing the vector and a scalar/text field) is therefore interpreted with the wrong field layout once `splits.size() >= 2 * global-index.thread-num`; ESIndexGlobalIndexReader rejects the mismatch against the persisted fields. I reproduced the regression with the existing multi-field test index factory, two committed shards, thread-num=1, and an actual Spark local[2] session: the local batch read succeeds, while SparkBatchVectorSearchBuilderImpl fails the stage with `IllegalArgumentException: Expected exactly one index file per shard` because the singleton field list selects its single-field reader. Please carry the complete indexed field list into the executor factory, and add a multi-field distributed batch/LATERAL regression. -- 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]
