This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git


The following commit(s) were added to refs/heads/master by this push:
     new d90a902d0a [core] Post-filter DE vector candidates without scalar 
index support (#11227)
d90a902d0a is described below

commit d90a902d0a4f11d8c8512b8f3ccd6d6a4e92e89a
Author: Jingsong Lee <[email protected]>
AuthorDate: Wed Nov 18 09:09:41 2026 +0800

    [core] Post-filter DE vector candidates without scalar index support 
(#11227)
---
 docs/docs/multimodal-table/global-index/vector.mdx |  21 +-
 docs/generated/core_configuration.html             |   6 +
 .../main/java/org/apache/paimon/CoreOptions.java   |  12 +
 .../source/AbstractDataEvolutionVectorRead.java    | 108 +++++-
 .../table/source/DataEvolutionVectorScan.java      |  64 +++-
 .../table/source/VectorSearchPostFilter.java       | 151 ++++++++
 .../table/source/VectorSearchPostFilterTest.java   | 228 ++++++++++++
 .../source/VectorSearchRowFilterExactnessTest.java | 389 ++++++++++++++++++++-
 8 files changed, 942 insertions(+), 37 deletions(-)

diff --git a/docs/docs/multimodal-table/global-index/vector.mdx 
b/docs/docs/multimodal-table/global-index/vector.mdx
index 0f52f5fee2..b9997d63ef 100644
--- a/docs/docs/multimodal-table/global-index/vector.mdx
+++ b/docs/docs/multimodal-table/global-index/vector.mdx
@@ -310,9 +310,24 @@ result = (
 )
 ```
 
-The scalar filter is evaluated with matching scalar global indexes before 
vector search. Build a
-BTree index for frequently used metadata filters, such as `category`, 
`tenant_id`, or `event_time`,
-so vector search can restrict the candidate row ids before running ANN search.
+Exact scalar global-index answers pre-filter the vector search. If scalar 
indexes cannot
+evaluate the predicate, each shard runs ANN once and checks only its 
candidates against the
+filter columns of the same pinned snapshot. The coordinator merges the 
filtered results;
+it does not perform a full-table scalar scan or a raw scan to fill missing 
matches.
+
+`vector-index.post-filter.candidates-factor` is a positive integer, defaulting 
to `10`.
+The candidate count is `max(original Top-K * factor, required reranking 
limit)`, capped by
+the shard size and the backend integer limit. For example, Top-K 10 normally 
requests 100
+candidates. Batch execution may split large inputs into memory-bounded chunks; 
every query
+still runs ANN once. Post-filtering may return fewer than Top-K rows, 
including zero even
+when matches exist outside the candidates. Increasing the factor trades more 
ANN/scalar
+work for more candidates. Post-filtering does not retry or scan raw data to 
fill Top-K.
+Raw work outside vector coverage still follows the configured index search 
modes. When a
+scalar index can evaluate the predicate but covers only some rows, scalar 
`full`/`detail`
+modes also plan raw scans for its uncovered rows.
+
+Build a BTree index for frequently used metadata filters, such as `category`, 
`tenant_id`,
+or `event_time`, to restrict candidate row IDs before ANN.
 
 An index answer that is only a candidate set — `contains`, ends-with or `LIKE` 
on a BTree index,
 or a conjunction with a member no index can evaluate — is never ranked as if 
it matched, because
diff --git a/docs/generated/core_configuration.html 
b/docs/generated/core_configuration.html
index 46a3327c1e..4bbc4e082c 100644
--- a/docs/generated/core_configuration.html
+++ b/docs/generated/core_configuration.html
@@ -2029,6 +2029,12 @@ The size strategy ranges by the data size allocated to 
each sorting task, which
             <td>String</td>
             <td>Specifies column names that should be stored as vector type. 
This is used when you want to treat a ARRAY column as a VECTOR.</td>
         </tr>
+        <tr>
+            <td><h5>vector-index.post-filter.candidates-factor</h5></td>
+            <td style="word-wrap: break-word;">10</td>
+            <td>Integer</td>
+            <td>Positive multiplier of the original Top-K for a single ANN 
query when scalar indexes cannot evaluate a DE vector search filter. The 
candidate count is at least the reranking limit and capped by the shard size 
and integer limit. Candidates are checked against the pinned data; fewer than 
Top-K matches are returned without retry or raw scoring of indexed ranges.</td>
+        </tr>
         <tr>
             <td><h5>vector-index.search-mode</h5></td>
             <td style="word-wrap: break-word;">fast</td>
diff --git a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java 
b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
index a1a0abefed..e399318ed3 100644
--- a/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
+++ b/paimon-api/src/main/java/org/apache/paimon/CoreOptions.java
@@ -3204,6 +3204,18 @@ public class CoreOptions implements Serializable {
                     .defaultValue(GlobalIndexSearchMode.FAST)
                     .withDescription("Search mode for full-text index 
queries.");
 
+    public static final ConfigOption<Integer> 
VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR =
+            key("vector-index.post-filter.candidates-factor")
+                    .intType()
+                    .defaultValue(10)
+                    .withDescription(
+                            "Positive multiplier of the original Top-K for a 
single ANN query "
+                                    + "when scalar indexes cannot evaluate a 
DE vector search filter. "
+                                    + "The candidate count is at least the 
reranking limit and capped by "
+                                    + "the shard size and integer limit. 
Candidates are checked against "
+                                    + "the pinned data; fewer than Top-K 
matches are returned without retry "
+                                    + "or raw scoring of indexed ranges.");
+
     public static final ConfigOption<Boolean> 
GLOBAL_INDEX_FILTER_REFINE_FROM_DATA =
             key("global-index.filter.refine-from-data")
                     .booleanType()
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
index e3206db3de..451cd47799 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/AbstractDataEvolutionVectorRead.java
@@ -90,6 +90,9 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
     protected final int limit;
     protected final DataField vectorColumn;
     protected final Map<String, String> options;
+    private final int candidatesFactor;
+    // Serialized with Spark/Flink worker closures; reset for each new read.
+    private boolean postFiltering;
 
     /** Snapshot the plan was built against; pins filters and raw reads to it. 
*/
     @Nullable protected Snapshot planSnapshot;
@@ -121,6 +124,18 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
                 options == null
                         ? Collections.emptyMap()
                         : Collections.unmodifiableMap(new HashMap<>(options));
+        Map<String, String> mergedOptions =
+                new HashMap<>(table == null ? Collections.emptyMap() : 
table.options());
+        mergedOptions.putAll(this.options);
+        Options effectiveOptions = Options.fromMap(mergedOptions);
+        this.candidatesFactor =
+                
effectiveOptions.get(CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR);
+        if (candidatesFactor <= 0) {
+            throw new IllegalArgumentException(
+                    
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR.key()
+                            + " must be positive, got "
+                            + candidatesFactor);
+        }
     }
 
     protected GlobalIndexer createGlobalIndexer(List<IndexVectorSearchSplit> 
splits) {
@@ -147,15 +162,9 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
     }
 
     /**
-     * Splits the search splits into index and raw splits, then moves the 
index splits aside when
-     * the scalar index cannot evaluate {@link #filter}: the index path 
answers with all-or-nothing
-     * bitmaps, so with an unevaluable filter it can neither honor the filter 
(an empty bitmap
-     * silently drops every covered row) nor ignore it (the top-K would be 
polluted by non-matching
-     * rows). Instead, suppress the index splits and route their ranges 
through the raw search,
-     * where the exact final-read filter decides; the raw read merges ranges, 
so overlap with an
-     * existing raw split is deduplicated. Splits routed this way reuse the 
vector index type so raw
-     * scoring keeps its metric. The computed scalar pre-filter is cached for 
{@link #preFilters} to
-     * reuse.
+     * Prefer an exact scalar pre-filter. If it cannot be evaluated, retain 
index work for one ANN
+     * query followed by exact candidate filtering. Raw sources retain their 
requested exact
+     * scoring.
      */
     protected void prepareSplits(
             List<? extends VectorSearchSplit> splits,
@@ -163,6 +172,7 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
             List<RawVectorSearchSplit> rawSplits) {
         splitSearchSplits(splits, indexSplits, rawSplits);
         scalarPreFilter = null;
+        postFiltering = false;
         if (filter == null || indexSplits.isEmpty()) {
             return;
         }
@@ -171,15 +181,7 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
             scalarPreFilter = matchedRows;
             return;
         }
-        List<Range> ranges = new ArrayList<>();
-        List<IndexFileMeta> scalarIndexFiles = new ArrayList<>();
-        for (IndexVectorSearchSplit split : indexSplits) {
-            ranges.add(new Range(split.rowRangeStart(), split.rowRangeEnd()));
-            scalarIndexFiles.addAll(split.scalarIndexFiles());
-        }
-        rawSplits.add(
-                new RawVectorSearchSplit(ranges, scalarIndexFiles, 
vectorIndexType(indexSplits)));
-        indexSplits.clear();
+        postFiltering = true;
     }
 
     protected List<RoaringNavigableMap64> 
preFilters(List<IndexVectorSearchSplit> splits) {
@@ -192,7 +194,9 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
                 GlobalIndexLiveRowFilter.liveRows(
                         table, planSnapshot, partitionFilter, 
indexedRowRanges);
         RoaringNavigableMap64 matchedRows =
-                scalarPreFilter != null ? scalarPreFilter : 
scalarMatchedRows(splits);
+                postFiltering
+                        ? null
+                        : scalarPreFilter != null ? scalarPreFilter : 
scalarMatchedRows(splits);
 
         List<RoaringNavigableMap64> includeRowIds = new 
ArrayList<>(splits.size());
         boolean hasFilter = false;
@@ -337,6 +341,25 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
                         rowRangeEnd - rowRangeStart + 1,
                         null,
                         executor);
+        if (postFiltering) {
+            CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> batch =
+                    evalPostFilter(
+                            reader,
+                            rowRangeStart,
+                            rowRangeEnd,
+                            new float[][] {vector},
+                            searchLimit,
+                            includeRowIds);
+            CompletableFuture<Optional<ScoredGlobalIndexResult>> single =
+                    batch.thenApply(results -> results.get(0));
+            single.whenComplete(
+                    (result, failure) -> {
+                        if (single.isCancelled()) {
+                            batch.cancel(false);
+                        }
+                    });
+            return single;
+        }
         VectorSearch vectorSearch =
                 new VectorSearch(vector, searchLimit, vectorColumn.name(), 
options)
                         .withIncludeRowIds(includeRowIds);
@@ -374,11 +397,58 @@ public abstract class AbstractDataEvolutionVectorRead 
implements Serializable {
         BatchVectorSearch batchVectorSearch =
                 new BatchVectorSearch(vectors, searchLimit, 
vectorColumn.name(), options)
                         .withIncludeRowIds(includeRowIds);
+        if (postFiltering) {
+            return evalPostFilter(
+                    reader, rowRangeStart, rowRangeEnd, vectors, searchLimit, 
includeRowIds);
+        }
         return new OffsetGlobalIndexReader(reader, rowRangeStart, rowRangeEnd)
                 .visitBatchVectorSearch(batchVectorSearch)
                 .whenComplete((r, t) -> IOUtils.closeQuietly(reader));
     }
 
+    private CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> 
evalPostFilter(
+            GlobalIndexReader reader,
+            long from,
+            long to,
+            float[][] vectors,
+            int searchLimit,
+            @Nullable RoaringNavigableMap64 include) {
+        try {
+            OffsetGlobalIndexReader offsetReader = new 
OffsetGlobalIndexReader(reader, from, to);
+            int candidates =
+                    VectorSearchPostFilter.candidateLimit(
+                            limit, candidatesFactor, searchLimit, to - from + 
1);
+            return VectorSearchPostFilter.search(
+                    vectors,
+                    candidates,
+                    searchLimit,
+                    new Range(from, to),
+                    include,
+                    queries ->
+                            offsetReader.visitBatchVectorSearch(
+                                    new BatchVectorSearch(
+                                                    queries,
+                                                    candidates,
+                                                    vectorColumn.name(),
+                                                    options)
+                                            .withIncludeRowIds(include)),
+                    rows ->
+                            new FilteredRowIdReader(
+                                            table,
+                                            planSnapshot,
+                                            partitionFilter,
+                                            checkNotNull(filter))
+                                    .matchingRowIds(rows),
+                    () -> IOUtils.closeQuietly(reader));
+        } catch (Throwable error) {
+            IOUtils.closeQuietly(reader);
+            CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> failed =
+                    new CompletableFuture<>();
+            failed.completeExceptionally(error);
+            return failed;
+        }
+    }
+
     protected ScoredGlobalIndexResult withRawSearch(
             ScoredGlobalIndexResult result,
             List<RawVectorSearchSplit> rawSplits,
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
index d1e7ba58a0..59bd6e97f9 100644
--- 
a/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/DataEvolutionVectorScan.java
@@ -22,6 +22,8 @@ import org.apache.paimon.CoreOptions;
 import org.apache.paimon.CoreOptions.GlobalIndexSearchMode;
 import org.apache.paimon.Snapshot;
 import org.apache.paimon.globalindex.DataEvolutionGlobalIndexCoverage;
+import org.apache.paimon.globalindex.DataEvolutionGlobalIndexScanner;
+import org.apache.paimon.globalindex.GlobalIndexEvaluator;
 import org.apache.paimon.index.GlobalIndexMeta;
 import org.apache.paimon.index.IndexFileHandler;
 import org.apache.paimon.index.IndexFileMeta;
@@ -38,12 +40,14 @@ import org.apache.paimon.utils.Range;
 
 import javax.annotation.Nullable;
 
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 
@@ -174,13 +178,11 @@ public class DataEvolutionVectorScan implements 
VectorScan {
                         .unindexedRanges(vectorColumn.id());
         if (filter != null) {
             List<Range> scalarUnindexedRanges =
-                    new DataEvolutionGlobalIndexCoverage(
-                                    table,
-                                    snapshot,
-                                    partitionFilter,
-                                    scalarIndexFiles(allIndexFiles),
-                                    effectiveOptions.scalarIndexSearchMode())
-                            .unindexedRanges(table.rowType(), filter);
+                    scalarUnindexedRanges(
+                            snapshot,
+                            scalarIndexFiles(allIndexFiles),
+                            effectiveOptions.scalarIndexSearchMode(),
+                            filterFieldIds);
             if (vectorSearchMode == GlobalIndexSearchMode.FAST) {
                 scalarUnindexedRanges =
                         Range.and(
@@ -213,6 +215,54 @@ public class DataEvolutionVectorScan implements VectorScan 
{
         };
     }
 
+    private List<Range> scalarUnindexedRanges(
+            @Nullable Snapshot snapshot,
+            List<IndexFileMeta> scalarFiles,
+            GlobalIndexSearchMode searchMode,
+            Set<Integer> filterFieldIds) {
+        if (searchMode == GlobalIndexSearchMode.FAST) {
+            return Collections.emptyList();
+        }
+        DataEvolutionGlobalIndexCoverage coverage =
+                new DataEvolutionGlobalIndexCoverage(
+                        table, snapshot, partitionFilter, scalarFiles, 
searchMode);
+        List<Range> dataRanges = 
coverage.unindexedRanges(Collections.emptySet(), null);
+        boolean possiblyPartial = false;
+        for (int fieldId : filterFieldIds) {
+            List<Range> missing =
+                    coverage.unindexedRanges(Collections.singleton(fieldId), 
dataRanges);
+            if (!missing.isEmpty() && !missing.equals(dataRanges)) {
+                possiblyPartial = true;
+                break;
+            }
+        }
+        if (!possiblyPartial) {
+            return Collections.emptyList();
+        }
+
+        // Metadata alone cannot prove operator support. Probe only partial 
coverage, and
+        // use the actual contributing fields so a declined OR arm does not 
generate raw work.
+        Optional<DataEvolutionGlobalIndexScanner> optionalScanner =
+                DataEvolutionGlobalIndexScanner.createForScalarFilters(
+                        table, snapshot, partitionFilter, scalarFiles);
+        if (!optionalScanner.isPresent()) {
+            return Collections.emptyList();
+        }
+        try (DataEvolutionGlobalIndexScanner scanner = optionalScanner.get()) {
+            Optional<GlobalIndexEvaluator.Evaluation> evaluation = 
scanner.scanWithCoverage(filter);
+            if (!evaluation.isPresent()) {
+                return Collections.emptyList();
+            }
+            GlobalIndexEvaluator.Evaluation evaluated = evaluation.get();
+            return evaluated.coveredRanges() == null
+                    ? 
coverage.unindexedRanges(evaluated.contributingFieldIds(), dataRanges)
+                    : 
coverage.unindexedRangesFromCoverage(evaluated.coveredRanges(), dataRanges);
+        } catch (IOException e) {
+            throw new RuntimeException(
+                    "Failed to evaluate scalar index coverage for vector 
search.", e);
+        }
+    }
+
     private CoreOptions effectiveCoreOptions() {
         Map<String, String> merged = new HashMap<>(table.options());
         merged.putAll(options);
diff --git 
a/paimon-core/src/main/java/org/apache/paimon/table/source/VectorSearchPostFilter.java
 
b/paimon-core/src/main/java/org/apache/paimon/table/source/VectorSearchPostFilter.java
new file mode 100644
index 0000000000..fbec39c092
--- /dev/null
+++ 
b/paimon-core/src/main/java/org/apache/paimon/table/source/VectorSearchPostFilter.java
@@ -0,0 +1,151 @@
+/*
+ * 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.table.source;
+
+import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
+import org.apache.paimon.utils.Range;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.Function;
+
+/** One ANN request per query followed by exact filtering on its shard's data. 
*/
+final class VectorSearchPostFilter {
+    private static final int MAX_BATCH_CANDIDATES = 1 << 20;
+
+    private VectorSearchPostFilter() {}
+
+    static int candidateLimit(int topK, int factor, int required, long 
shardSize) {
+        if (topK <= 0 || factor <= 0 || required <= 0 || shardSize <= 0) {
+            throw new IllegalArgumentException("Invalid post-filter candidate 
limits");
+        }
+        return (int)
+                Math.min(
+                        Integer.MAX_VALUE,
+                        Math.min(shardSize, Math.max((long) topK * factor, 
required)));
+    }
+
+    static CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> search(
+            float[][] vectors,
+            int candidates,
+            int required,
+            Range range,
+            @Nullable RoaringNavigableMap64 include,
+            Function<float[][], 
CompletableFuture<List<Optional<ScoredGlobalIndexResult>>>>
+                    retrieve,
+            Function<RoaringNavigableMap64, RoaringNavigableMap64> check,
+            Runnable close) {
+        List<Optional<ScoredGlobalIndexResult>> results = new 
ArrayList<>(vectors.length);
+        AtomicBoolean cancelled = new AtomicBoolean();
+        int chunkSize = Math.max(1, MAX_BATCH_CANDIDATES / candidates);
+        CompletableFuture<Void> chain = 
CompletableFuture.completedFuture(null);
+        for (int start = 0; start < vectors.length; start += chunkSize) {
+            float[][] batch =
+                    Arrays.copyOfRange(vectors, start, 
Math.min(vectors.length, start + chunkSize));
+            // Do not submit from the native completion thread: it may still 
hold
+            // the only permit of a SemaphoredDelegatingExecutor.
+            chain =
+                    chain.thenComposeAsync(
+                            ignored -> {
+                                if (cancelled.get()) {
+                                    throw new CancellationException();
+                                }
+                                return retrieve.apply(batch)
+                                        .thenAcceptAsync(
+                                                values -> {
+                                                    if (cancelled.get()) {
+                                                        throw new 
CancellationException();
+                                                    }
+                                                    if (values.size() != 
batch.length) {
+                                                        throw new 
IllegalStateException(
+                                                                "Vector index 
returned the wrong query count");
+                                                    }
+                                                    results.addAll(
+                                                            filter(
+                                                                    values, 
required, range,
+                                                                    include, 
check));
+                                                });
+                            });
+        }
+        // Expose only a downstream stage. Cancelling it cannot skip cleanup or
+        // close the reader while an in-flight native request still uses it.
+        CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> output =
+                chain.whenComplete((ignored, failure) -> 
close.run()).thenApply(ignored -> results);
+        output.whenComplete(
+                (ignored, failure) -> {
+                    if (output.isCancelled()) {
+                        cancelled.set(true);
+                    }
+                });
+        return output;
+    }
+
+    static List<Optional<ScoredGlobalIndexResult>> filter(
+            List<Optional<ScoredGlobalIndexResult>> values,
+            int required,
+            Range range,
+            @Nullable RoaringNavigableMap64 include,
+            Function<RoaringNavigableMap64, RoaringNavigableMap64> check) {
+        RoaringNavigableMap64 candidates = new RoaringNavigableMap64();
+        for (Optional<ScoredGlobalIndexResult> value : values) {
+            if (value.isPresent()) {
+                for (long id : value.get().results()) {
+                    if (id < range.from
+                            || id > range.to
+                            || (include != null && !include.contains(id))) {
+                        throw new IllegalStateException("Vector candidate lies 
outside its source");
+                    }
+                    candidates.add(id);
+                }
+            }
+        }
+        RoaringNavigableMap64 matched =
+                candidates.isEmpty()
+                        ? candidates
+                        : RoaringNavigableMap64.and(check.apply(candidates), 
candidates);
+        List<Optional<ScoredGlobalIndexResult>> filtered = new 
ArrayList<>(values.size());
+        for (Optional<ScoredGlobalIndexResult> value : values) {
+            if (!value.isPresent()) {
+                filtered.add(Optional.empty());
+                continue;
+            }
+            ScoredGlobalIndexResult candidate = value.get();
+            RoaringNavigableMap64 ids = 
RoaringNavigableMap64.and(candidate.results(), matched);
+            ScoredGlobalIndexResult selected =
+                    ScoredGlobalIndexResult.create(ids, 
candidate.scoreGetter()).topK(required);
+            Map<Long, Float> scores = new HashMap<>();
+            for (long id : selected.results()) {
+                scores.put(id, selected.scoreGetter().score(id));
+            }
+            filtered.add(
+                    
Optional.of(ScoredGlobalIndexResult.create(selected.results(), scores::get)));
+        }
+        return filtered;
+    }
+}
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchPostFilterTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchPostFilterTest.java
new file mode 100644
index 0000000000..785e62458c
--- /dev/null
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchPostFilterTest.java
@@ -0,0 +1,228 @@
+/*
+ * 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.table.source;
+
+import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
+import org.apache.paimon.utils.Range;
+import org.apache.paimon.utils.RoaringNavigableMap64;
+import org.apache.paimon.utils.SemaphoredDelegatingExecutor;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+class VectorSearchPostFilterTest {
+    private static RoaringNavigableMap64 ids(long... ids) {
+        RoaringNavigableMap64 bitmap = new RoaringNavigableMap64();
+        for (long id : ids) {
+            bitmap.add(id);
+        }
+        return bitmap;
+    }
+
+    private static Optional<ScoredGlobalIndexResult> hit(long id) {
+        return Optional.of(ScoredGlobalIndexResult.create(ids(id), ignored -> 
1.0f));
+    }
+
+    @Test
+    void candidateCountUsesOriginalTopKAndCapsWithoutOverflow() {
+        assertThat(VectorSearchPostFilter.candidateLimit(2, 10, 6, 
1000)).isEqualTo(20);
+        assertThat(VectorSearchPostFilter.candidateLimit(2, 1, 6, 
1000)).isEqualTo(6);
+        assertThat(VectorSearchPostFilter.candidateLimit(2, 10, 6, 
12)).isEqualTo(12);
+        assertThat(
+                        VectorSearchPostFilter.candidateLimit(
+                                Integer.MAX_VALUE, Integer.MAX_VALUE, 1, 
Long.MAX_VALUE))
+                .isEqualTo(Integer.MAX_VALUE);
+        assertThatThrownBy(() -> VectorSearchPostFilter.candidateLimit(1, 0, 
1, 10))
+                .isInstanceOf(IllegalArgumentException.class);
+    }
+
+    @Test
+    void filtersTheBatchUnionOnceAndDetachesRetainedScores() throws Exception {
+        Map<Long, Float> scores = new HashMap<>();
+        scores.put(101L, 3.0f);
+        scores.put(102L, 2.0f);
+        scores.put(103L, 1.0f);
+        Optional<ScoredGlobalIndexResult> candidate =
+                Optional.of(ScoredGlobalIndexResult.create(ids(101, 102, 103), 
scores::get));
+        AtomicInteger checks = new AtomicInteger();
+        AtomicInteger searches = new AtomicInteger();
+        AtomicInteger closes = new AtomicInteger();
+        List<Optional<ScoredGlobalIndexResult>> result =
+                VectorSearchPostFilter.search(
+                                new float[][] {{0}, {1}},
+                                10,
+                                2,
+                                new Range(100, 110),
+                                ids(101, 102, 103),
+                                vectors -> {
+                                    searches.incrementAndGet();
+                                    return CompletableFuture.completedFuture(
+                                            Arrays.asList(candidate, 
candidate));
+                                },
+                                rows -> {
+                                    assertThat(rows).containsExactly(101L, 
102L, 103L);
+                                    checks.incrementAndGet();
+                                    return ids(102, 999);
+                                },
+                                closes::incrementAndGet)
+                        .get(10, SECONDS);
+        scores.clear();
+        assertThat(searches.get()).isEqualTo(1);
+        assertThat(checks.get()).isEqualTo(1);
+        assertThat(closes.get()).isEqualTo(1);
+        for (Optional<ScoredGlobalIndexResult> value : result) {
+            assertThat(value.get().results()).containsExactly(102L);
+            assertThat(value.get().scoreGetter().score(102)).isEqualTo(2.0f);
+        }
+    }
+
+    @Test
+    void chunksLargeBatchesButNeverRetriesQueriesOrDeadlocksOnOnePermit() 
throws Exception {
+        ExecutorService thread = Executors.newSingleThreadExecutor();
+        ExecutorService executor = new SemaphoredDelegatingExecutor(thread, 1, 
false);
+        AtomicInteger closes = new AtomicInteger();
+        AtomicInteger searches = new AtomicInteger();
+        float[][] vectors = {{0}, {1}, {2}, {3}, {4}, {5}};
+        int[] seen = new int[6];
+        try {
+            List<Optional<ScoredGlobalIndexResult>> result =
+                    VectorSearchPostFilter.search(
+                                    vectors,
+                                    200000,
+                                    2,
+                                    new Range(0, 1000000),
+                                    null,
+                                    batch ->
+                                            CompletableFuture.supplyAsync(
+                                                    () -> {
+                                                        
searches.incrementAndGet();
+                                                        assertThat((long) 
batch.length * 200000)
+                                                                
.isLessThanOrEqualTo(1 << 20);
+                                                        
List<Optional<ScoredGlobalIndexResult>>
+                                                                values = new 
ArrayList<>();
+                                                        for (float[] vector : 
batch) {
+                                                            int id = (int) 
vector[0];
+                                                            assertThat(vector)
+                                                                    
.isSameAs(vectors[id]);
+                                                            seen[id]++;
+                                                            
values.add(hit(id));
+                                                        }
+                                                        return values;
+                                                    },
+                                                    executor),
+                                    rows -> new RoaringNavigableMap64(),
+                                    closes::incrementAndGet)
+                            .get(10, SECONDS);
+            assertThat(searches.get()).isEqualTo(2);
+            assertThat(seen).containsExactly(1, 1, 1, 1, 1, 1);
+            assertThat(closes.get()).isEqualTo(1);
+            assertThat(result).hasSize(6);
+            for (Optional<ScoredGlobalIndexResult> value : result) {
+                assertThat(value.get().results()).isEmpty();
+            }
+        } finally {
+            thread.shutdownNow();
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"sync", "async", "scalar", "count", "range"})
+    void errorsCompleteTheFutureAndCloseTheReader(String failure) {
+        AtomicInteger closes = new AtomicInteger();
+        CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> result =
+                VectorSearchPostFilter.search(
+                        new float[][] {{0}},
+                        10,
+                        2,
+                        new Range(0, 100),
+                        null,
+                        vectors -> {
+                            if (failure.equals("sync")) {
+                                throw new IllegalStateException("sync");
+                            }
+                            if (failure.equals("async")) {
+                                
CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> failed =
+                                        new CompletableFuture<>();
+                                failed.completeExceptionally(new 
IllegalStateException("async"));
+                                return failed;
+                            }
+                            return CompletableFuture.completedFuture(
+                                    failure.equals("count")
+                                            ? Collections.emptyList()
+                                            : Collections.singletonList(
+                                                    
hit(failure.equals("range") ? 999 : 1)));
+                        },
+                        rows -> {
+                            throw new IllegalStateException("scalar");
+                        },
+                        closes::incrementAndGet);
+        assertThatThrownBy(() -> result.get(10, SECONDS))
+                .hasCauseInstanceOf(IllegalStateException.class);
+        assertThat(closes.get()).isEqualTo(1);
+    }
+
+    @Test
+    void 
cancellationWaitsForNativeCompletionBeforeClosingAndSkipsFurtherWork() throws 
Exception {
+        CountDownLatch started = new CountDownLatch(1);
+        CountDownLatch closed = new CountDownLatch(1);
+        CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> 
nativeResult =
+                new CompletableFuture<>();
+        AtomicInteger searches = new AtomicInteger();
+        CompletableFuture<List<Optional<ScoredGlobalIndexResult>>> result =
+                VectorSearchPostFilter.search(
+                        new float[][] {{0}, {1}},
+                        1 << 20,
+                        2,
+                        new Range(0, 10000000),
+                        null,
+                        vectors -> {
+                            searches.incrementAndGet();
+                            started.countDown();
+                            return nativeResult;
+                        },
+                        rows -> {
+                            throw new AssertionError("Cancelled query must not 
read scalar data");
+                        },
+                        closed::countDown);
+        assertThat(started.await(10, SECONDS)).isTrue();
+        assertThat(result.cancel(false)).isTrue();
+        assertThat(closed.getCount()).isEqualTo(1);
+        nativeResult.complete(Collections.singletonList(hit(0)));
+        assertThat(closed.await(10, SECONDS)).isTrue();
+        assertThat(searches.get()).isEqualTo(1);
+    }
+}
diff --git 
a/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchRowFilterExactnessTest.java
 
b/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchRowFilterExactnessTest.java
index c0bd13300f..48d5252876 100644
--- 
a/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchRowFilterExactnessTest.java
+++ 
b/paimon-core/src/test/java/org/apache/paimon/table/source/VectorSearchRowFilterExactnessTest.java
@@ -19,6 +19,7 @@
 package org.apache.paimon.table.source;
 
 import org.apache.paimon.CoreOptions;
+import org.apache.paimon.Snapshot;
 import org.apache.paimon.catalog.Identifier;
 import org.apache.paimon.data.BinaryRow;
 import org.apache.paimon.data.BinaryString;
@@ -27,6 +28,8 @@ import org.apache.paimon.data.GenericRow;
 import org.apache.paimon.globalindex.GlobalIndexBuilderUtils;
 import org.apache.paimon.globalindex.GlobalIndexResult;
 import org.apache.paimon.globalindex.GlobalIndexSingleColumnWriter;
+import org.apache.paimon.globalindex.GlobalIndexer;
+import org.apache.paimon.globalindex.ScoredGlobalIndexResult;
 import org.apache.paimon.globalindex.btree.BTreeGlobalIndexerFactory;
 import org.apache.paimon.globalindex.testvector.TestVectorGlobalIndexerFactory;
 import org.apache.paimon.index.IndexFileMeta;
@@ -46,6 +49,7 @@ import org.apache.paimon.table.sink.CommitMessageImpl;
 import org.apache.paimon.types.ArrayType;
 import org.apache.paimon.types.DataField;
 import org.apache.paimon.types.DataTypes;
+import org.apache.paimon.utils.InstantiationUtil;
 import org.apache.paimon.utils.Range;
 
 import org.junit.jupiter.api.Test;
@@ -53,11 +57,13 @@ import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.CsvSource;
 import org.junit.jupiter.params.provider.ValueSource;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 /**
  * Vector search with a row filter must rank an exact match set: 
candidate-only scalar index answers
@@ -66,11 +72,369 @@ import static org.assertj.core.api.Assertions.assertThat;
  */
 public class VectorSearchRowFilterExactnessTest extends TableTestBase {
 
+    @Test
+    public void testPostFilterKeepsIndexedRangesOffRawPath() throws Exception {
+        createTableDefault();
+        FileStoreTable table = getTableDefault();
+        String[] names = new String[128];
+        float[][] vectors = new float[128][2];
+        for (int i = 0; i < names.length; i++) {
+            names[i] = i >= 8 ? "match" : "other";
+            vectors[i][0] = i;
+        }
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        Predicate filter =
+                new PredicateBuilder(table.rowType()).equal(1, 
BinaryString.fromString("match"));
+        VectorScan.Plan plan =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {0, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(2)
+                        .withFilter(filter)
+                        .newVectorScan()
+                        .scan();
+        DataEvolutionVectorRead read =
+                new DataEvolutionVectorRead(
+                        table,
+                        null,
+                        filter,
+                        2,
+                        table.rowType().getField("vec"),
+                        new float[] {0, 0},
+                        Collections.emptyMap()) {
+                    @Override
+                    protected ScoredGlobalIndexResult readRawSearch(
+                            List<Range> ranges,
+                            org.apache.paimon.utils.RoaringNavigableMap64 
include,
+                            GlobalIndexer indexer,
+                            float[] query) {
+                        throw new AssertionError(
+                                "Indexed candidates must be filtered without 
raw scoring");
+                    }
+                };
+        assertThat(read.read(plan).results()).containsExactly(8L, 9L);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"fast", "full", "detail"})
+    public void 
testPostFilterFactorAllowsShortResultsWithoutRawRecovery(String scalarMode)
+            throws Exception {
+        FileStoreTable table =
+                createTable(
+                        "post_filter_" + scalarMode,
+                        schemaBuilder(true)
+                                
.option(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), scalarMode)
+                                .option(
+                                        
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR
+                                                .key(),
+                                        "64"));
+        String[] names = new String[128];
+        float[][] vectors = new float[128][2];
+        for (int i = 0; i < names.length; i++) {
+            names[i] = i > 90 ? "match" : "other";
+            vectors[i][0] = i;
+        }
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        buildAndCommitIdBTreeIndex(table, names.length);
+        PredicateBuilder predicates = new PredicateBuilder(table.rowType());
+        // One indexed arm and one unindexed arm make the whole OR unevaluable.
+        Predicate filter =
+                PredicateBuilder.or(
+                        predicates.lessThan(0, 0),
+                        predicates.equal(1, BinaryString.fromString("match")));
+        for (String factor : Arrays.asList("2", "64")) {
+            BatchVectorSearchBuilder builder =
+                    table.newBatchVectorSearchBuilder()
+                            .withVectors(new float[][] {{0, 0}, {127, 0}})
+                            .withVectorColumn("vec")
+                            .withLimit(2)
+                            .withFilter(filter)
+                            .withOption(
+                                    
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR.key(),
+                                    factor);
+            VectorScan.Plan captured = builder.newVectorScan().scan();
+            assertThat(captured.splits()).noneMatch(split -> split instanceof 
RawVectorSearchSplit);
+            List<VectorSearchSplit> transported = new ArrayList<>();
+            for (VectorSearchSplit split : captured.splits()) {
+                transported.add(
+                        InstantiationUtil.deserializeObject(
+                                InstantiationUtil.serializeObject(split),
+                                getClass().getClassLoader()));
+            }
+            VectorScan.Plan restored =
+                    new VectorScan.Plan() {
+                        @Override
+                        public List<VectorSearchSplit> splits() {
+                            return transported;
+                        }
+
+                        @Override
+                        public Snapshot snapshot() {
+                            return captured.snapshot();
+                        }
+                    };
+            List<GlobalIndexResult> results = 
builder.newBatchVectorRead().readBatch(restored);
+            assertThat(results.get(0).results())
+                    .containsExactly(factor.equals("2") ? new Long[0] : new 
Long[] {91L, 92L});
+            
assertThat(results.get(1).results()).containsExactlyInAnyOrder(127L, 126L);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"fast", "full", "detail"})
+    public void testUnsupportedOrWithPartialScalarCoveragePlansNoRaw(String 
scalarMode)
+            throws Exception {
+        FileStoreTable table =
+                createTable(
+                        "unsupported_partial_or_" + scalarMode,
+                        schemaBuilder(true)
+                                
.option(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), scalarMode));
+        String[] names = {"other", "other", "other", "other", "other", 
"other", "match", "other"};
+        float[][] vectors = linearVectors(names.length);
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        buildAndCommitIdBTreeIndex(table, new Range(0, 3));
+        PredicateBuilder predicates = new PredicateBuilder(table.rowType());
+        Predicate filter =
+                PredicateBuilder.or(
+                        predicates.lessThan(0, 0),
+                        predicates.equal(1, BinaryString.fromString("match")));
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {0, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter)
+                        .withOption(
+                                
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR.key(), "1");
+        VectorScan.Plan plan = builder.newVectorScan().scan();
+        assertThat(rawRanges(plan)).isEmpty();
+        assertThat(builder.newVectorRead().read(plan).results()).isEmpty();
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"fast", "full", "detail"})
+    public void 
testPartialScalarAndUsesContributingCoverageAndQueryMode(String scalarMode)
+            throws Exception {
+        FileStoreTable table =
+                createTable(
+                        "partial_scalar_and_" + scalarMode,
+                        schemaBuilder(true)
+                                
.option(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), "fast"));
+        String[] names = {"other", "match", "other", "other", "other", 
"other", "match", "other"};
+        float[][] vectors = linearVectors(names.length);
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        buildAndCommitIdBTreeIndex(table, new Range(0, 3));
+        PredicateBuilder predicates = new PredicateBuilder(table.rowType());
+        Predicate filter =
+                PredicateBuilder.and(
+                        predicates.greaterOrEqual(0, 0),
+                        predicates.equal(1, BinaryString.fromString("match")));
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {6, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter)
+                        
.withOption(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), scalarMode);
+        VectorScan.Plan plan = transportPlan(builder.newVectorScan().scan());
+        if (scalarMode.equals("fast")) {
+            assertThat(rawRanges(plan)).isEmpty();
+            
assertThat(builder.newVectorRead().read(plan).results()).containsExactly(1L);
+        } else {
+            assertThat(rawRanges(plan)).containsExactly(new Range(4, 7));
+            
assertThat(builder.newVectorRead().read(plan).results()).containsExactly(6L);
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"full", "detail"})
+    public void testEmptyScalarMatchesStillPlanUncoveredRows(String 
scalarMode) throws Exception {
+        FileStoreTable table =
+                createTable(
+                        "empty_partial_scalar_" + scalarMode,
+                        schemaBuilder(true)
+                                
.option(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), "fast"));
+        String[] names = {"other", "other", "other", "other", "other", 
"other", "match", "other"};
+        float[][] vectors = linearVectors(names.length);
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        buildAndCommitIdBTreeIndex(table, new Range(0, 3));
+        Predicate filter = new 
PredicateBuilder(table.rowType()).greaterOrEqual(0, 6);
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {6, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter)
+                        
.withOption(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), scalarMode);
+        VectorScan.Plan plan = builder.newVectorScan().scan();
+        assertThat(rawRanges(plan)).containsExactly(new Range(4, 7));
+        
assertThat(builder.newVectorRead().read(plan).results()).containsExactly(6L);
+    }
+
+    @Test
+    public void testDeclinedPartialScalarOperatorPlansNoRaw() throws Exception 
{
+        FileStoreTable table =
+                createTable(
+                        "declined_partial_scalar",
+                        schemaBuilder(true)
+                                
.option(CoreOptions.SCALAR_INDEX_SEARCH_MODE.key(), "full")
+                                .option("btree-index.fallback-scan-max-size", 
"0"));
+        String[] names = {
+            "other-0", "other-1", "other-2", "other-3", "other-4", "other-5", 
"match", "other-7"
+        };
+        float[][] vectors = linearVectors(names.length);
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        buildAndCommitNameBTreeIndex(table, names, new Range(0, 3));
+        Predicate filter =
+                new PredicateBuilder(table.rowType()).contains(1, 
BinaryString.fromString("match"));
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {0, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter)
+                        .withOption(
+                                
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR.key(), "1");
+        VectorScan.Plan plan = builder.newVectorScan().scan();
+        assertThat(rawRanges(plan)).isEmpty();
+        assertThat(builder.newVectorRead().read(plan).results()).isEmpty();
+    }
+
+    @Test
+    public void testExplicitRawSourceRetainsScoringDuringPostFilter() throws 
Exception {
+        createTableDefault();
+        FileStoreTable table = getTableDefault();
+        String[] names = {"other", "other", "match"};
+        float[][] vectors = linearVectors(names.length);
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        Predicate filter =
+                new PredicateBuilder(table.rowType()).equal(1, 
BinaryString.fromString("match"));
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {0, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter)
+                        .withOption(
+                                
CoreOptions.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR.key(), "1");
+        VectorScan.Plan captured = builder.newVectorScan().scan();
+        List<VectorSearchSplit> splits = new ArrayList<>(captured.splits());
+        splits.add(
+                new RawVectorSearchSplit(
+                        Collections.singletonList(new Range(2, 2)),
+                        Collections.emptyList(),
+                        TestVectorGlobalIndexerFactory.IDENTIFIER));
+        VectorScan.Plan plan =
+                new VectorScan.Plan() {
+                    @Override
+                    public List<VectorSearchSplit> splits() {
+                        return splits;
+                    }
+
+                    @Override
+                    public Snapshot snapshot() {
+                        return captured.snapshot();
+                    }
+                };
+        
assertThat(builder.newVectorRead().read(transportPlan(plan)).results()).containsExactly(2L);
+    }
+
+    private VectorScan.Plan transportPlan(VectorScan.Plan captured) throws 
Exception {
+        List<VectorSearchSplit> splits = new ArrayList<>();
+        for (VectorSearchSplit split : captured.splits()) {
+            splits.add(
+                    InstantiationUtil.deserializeObject(
+                            InstantiationUtil.serializeObject(split), 
getClass().getClassLoader()));
+        }
+        return new VectorScan.Plan() {
+            @Override
+            public List<VectorSearchSplit> splits() {
+                return splits;
+            }
+
+            @Override
+            public Snapshot snapshot() {
+                return captured.snapshot();
+            }
+        };
+    }
+
+    private static float[][] linearVectors(int count) {
+        float[][] vectors = new float[count][2];
+        for (int i = 0; i < count; i++) {
+            vectors[i][0] = i;
+        }
+        return vectors;
+    }
+
+    private static List<Range> rawRanges(VectorScan.Plan plan) {
+        List<Range> ranges = new ArrayList<>();
+        for (VectorSearchSplit split : plan.splits()) {
+            if (split instanceof RawVectorSearchSplit) {
+                ranges.addAll(((RawVectorSearchSplit) split).rowRanges());
+            }
+        }
+        return Range.sortAndMergeOverlap(ranges, true);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"0", "-1", "bad", "2147483648"})
+    public void testPostFilterRejectsInvalidCandidateFactor(String value) 
throws Exception {
+        createTableDefault();
+        FileStoreTable table = getTableDefault();
+        assertThatThrownBy(
+                        () ->
+                                table.newVectorSearchBuilder()
+                                        .withVector(new float[] {0, 0})
+                                        .withVectorColumn("vec")
+                                        .withLimit(2)
+                                        .withOption(
+                                                CoreOptions
+                                                        
.VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR
+                                                        .key(),
+                                                value)
+                                        .newVectorRead())
+                .isInstanceOf(IllegalArgumentException.class);
+    }
+
     @Override
     protected Schema schemaDefault() {
         return schemaBuilder(true).build();
     }
 
+    @Test
+    public void 
testPostFilterPinsCandidateReadsAndDeletionVectorsToPlanSnapshot()
+            throws Exception {
+        FileStoreTable table =
+                createTable(
+                        "post_filter_snapshot",
+                        schemaBuilder(true)
+                                
.option(CoreOptions.DELETION_VECTORS_ENABLED.key(), "true"));
+        String[] names = {"other", "match", "match"};
+        float[][] vectors = {{0, 0}, {1, 0}, {2, 0}};
+        write(table, names, vectors);
+        buildAndCommitVectorIndex(table, vectors);
+        Predicate filter =
+                new PredicateBuilder(table.rowType()).equal(1, 
BinaryString.fromString("match"));
+        VectorSearchBuilder builder =
+                table.newVectorSearchBuilder()
+                        .withVector(new float[] {0, 0})
+                        .withVectorColumn("vec")
+                        .withLimit(1)
+                        .withFilter(filter);
+        VectorScan.Plan oldPlan = builder.newVectorScan().scan();
+        DeletionVectorTestUtils.commitDeletionVectors(table, 1L);
+        
assertThat(builder.newVectorRead().read(oldPlan).results()).containsExactly(1L);
+        assertThat(builder.executeLocal().results()).containsExactly(2L);
+    }
+
     /**
      * {@code refine} sets {@code global-index.filter.refine-from-data}, which 
defaults to false.
      */
@@ -530,6 +894,11 @@ public class VectorSearchRowFilterExactnessTest extends 
TableTestBase {
 
     private void buildAndCommitNameBTreeIndex(FileStoreTable table, String[] 
names)
             throws Exception {
+        buildAndCommitNameBTreeIndex(table, names, new Range(0, names.length - 
1));
+    }
+
+    private void buildAndCommitNameBTreeIndex(FileStoreTable table, String[] 
names, Range rowRange)
+            throws Exception {
         Options options = table.coreOptions().toConfiguration();
         DataField nameField = table.rowType().getField("name");
         GlobalIndexSingleColumnWriter writer =
@@ -540,13 +909,13 @@ public class VectorSearchRowFilterExactnessTest extends 
TableTestBase {
                                 Collections.singletonList(nameField),
                                 options);
         // The btree writer needs sorted keys.
-        Integer[] order = new Integer[names.length];
-        for (int i = 0; i < names.length; i++) {
-            order[i] = i;
+        Integer[] order = new Integer[(int) rowRange.count()];
+        for (int i = 0; i < order.length; i++) {
+            order[i] = (int) rowRange.from + i;
         }
         Arrays.sort(order, (a, b) -> names[a].compareTo(names[b]));
         for (int rowId : order) {
-            writer.write(BinaryString.fromString(names[rowId]), rowId);
+            writer.write(BinaryString.fromString(names[rowId]), rowId - 
rowRange.from);
         }
         commitIndex(
                 table,
@@ -554,13 +923,17 @@ public class VectorSearchRowFilterExactnessTest extends 
TableTestBase {
                         table.fileIO(),
                         table.store().pathFactory().globalIndexFileFactory(),
                         table.coreOptions(),
-                        new Range(0, names.length - 1),
+                        rowRange,
                         nameField.id(),
                         BTreeGlobalIndexerFactory.IDENTIFIER,
                         writer.finish()));
     }
 
     private void buildAndCommitIdBTreeIndex(FileStoreTable table, int 
rowCount) throws Exception {
+        buildAndCommitIdBTreeIndex(table, new Range(0, rowCount - 1));
+    }
+
+    private void buildAndCommitIdBTreeIndex(FileStoreTable table, Range 
rowRange) throws Exception {
         Options options = table.coreOptions().toConfiguration();
         DataField idField = table.rowType().getField("id");
         GlobalIndexSingleColumnWriter writer =
@@ -570,8 +943,8 @@ public class VectorSearchRowFilterExactnessTest extends 
TableTestBase {
                                 BTreeGlobalIndexerFactory.IDENTIFIER,
                                 Collections.singletonList(idField),
                                 options);
-        for (int i = 0; i < rowCount; i++) {
-            writer.write(i, i);
+        for (long rowId = rowRange.from; rowId <= rowRange.to; rowId++) {
+            writer.write((int) rowId, rowId - rowRange.from);
         }
         commitIndex(
                 table,
@@ -579,7 +952,7 @@ public class VectorSearchRowFilterExactnessTest extends 
TableTestBase {
                         table.fileIO(),
                         table.store().pathFactory().globalIndexFileFactory(),
                         table.coreOptions(),
-                        new Range(0, rowCount - 1),
+                        rowRange,
                         idField.id(),
                         BTreeGlobalIndexerFactory.IDENTIFIER,
                         writer.finish()));

Reply via email to