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

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


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

commit ddcad6bdf3f3887beeacab5d5147c2d9bedb50a9
Author: Jingsong Lee <[email protected]>
AuthorDate: Wed Nov 18 09:13:34 2026 +0800

    [core] Post-filter DE vector candidates without scalar index support (#1439)
---
 .../datafusion/src/lateral_vector_search.rs        |  47 +-
 .../src/lateral_vector_search_filter_tests.rs      | 290 +++++++++++
 .../integrations/datafusion/src/vector_search.rs   |  56 ++-
 .../integrations/datafusion/tests/read_tables.rs   |  23 +
 crates/paimon/src/spec/predicate.rs                |   6 +-
 .../src/table/batch_vector_search_builder.rs       |   3 +-
 crates/paimon/src/table/de_vector_read.rs          | 314 ++++++++++--
 .../paimon/src/table/de_vector_read/post_filter.rs |  98 ++++
 crates/paimon/src/table/de_vector_read/tests.rs    | 196 +++++++-
 crates/paimon/src/table/de_vector_scan.rs          |  69 +++
 crates/paimon/src/table/de_vector_scan/tests.rs    | 530 ++++++++++++++++++---
 crates/paimon/src/table/global_index_scanner.rs    |  35 +-
 .../src/table/global_index_scanner/row_ranges.rs   |   2 +-
 crates/paimon/src/table/search_scan_split.rs       |   3 +-
 crates/paimon/src/table/search_task.rs             |   2 +-
 crates/paimon/src/table/vector_search_builder.rs   |   9 +-
 docs/src/sql.md                                    |  31 +-
 17 files changed, 1526 insertions(+), 188 deletions(-)

diff --git a/crates/integrations/datafusion/src/lateral_vector_search.rs 
b/crates/integrations/datafusion/src/lateral_vector_search.rs
index 1ebb7183..51072b3c 100644
--- a/crates/integrations/datafusion/src/lateral_vector_search.rs
+++ b/crates/integrations/datafusion/src/lateral_vector_search.rs
@@ -466,10 +466,16 @@ struct LateralVectorSearchExec {
     plan_properties: Arc<PlanProperties>,
 }
 
+#[derive(Debug)]
+struct PinnedFilter {
+    table: Table,
+    prepared: Option<PreparedVectorSearchFilter>,
+}
+
 #[derive(Debug)]
 struct ExecutionPreparedFilterEntry {
     context: Weak<TaskContext>,
-    prepared_filter: Arc<OnceCell<PreparedVectorSearchFilter>>,
+    prepared_filter: Arc<OnceCell<PinnedFilter>>,
     partition_count: usize,
     completed_partitions: HashSet<usize>,
     active_partition_leases: HashMap<usize, usize>,
@@ -478,8 +484,9 @@ struct ExecutionPreparedFilterEntry {
 #[derive(Debug, Default)]
 struct ExecutionPreparedFilterCache {
     // DataFusion passes the same TaskContext Arc to every partition of one
-    // execution. Keep the prepared filter alive for that TaskContext so
-    // sequential partitions resolve the same target snapshot. DataFusion
+    // execution. Reuse fully covered exact scalar-index answers across 
batches;
+    // other filters keep only the pinned table and check each ANN candidate 
set.
+    // Sequential partitions resolve the same target snapshot. DataFusion
     // exposes no TaskContext drop hook, so one cache-level reaper observes the
     // weak contexts and removes subset executions after their context dies.
     entries: Mutex<Vec<ExecutionPreparedFilterEntry>>,
@@ -488,7 +495,7 @@ struct ExecutionPreparedFilterCache {
 
 #[derive(Clone)]
 struct ExecutionPreparedFilterLease {
-    prepared_filter: Arc<OnceCell<PreparedVectorSearchFilter>>,
+    prepared_filter: Arc<OnceCell<PinnedFilter>>,
     _completion: Arc<ExecutionPartitionCompletion>,
 }
 
@@ -496,7 +503,7 @@ impl ExecutionPreparedFilterLease {
     fn new(
         cache: &Arc<ExecutionPreparedFilterCache>,
         context: Arc<TaskContext>,
-        prepared_filter: Arc<OnceCell<PreparedVectorSearchFilter>>,
+        prepared_filter: Arc<OnceCell<PinnedFilter>>,
         partition: usize,
     ) -> Self {
         Self {
@@ -514,7 +521,7 @@ impl ExecutionPreparedFilterLease {
 struct ExecutionPartitionCompletion {
     cache: Weak<ExecutionPreparedFilterCache>,
     context: Arc<TaskContext>,
-    prepared_filter: Arc<OnceCell<PreparedVectorSearchFilter>>,
+    prepared_filter: Arc<OnceCell<PinnedFilter>>,
     partition: usize,
 }
 
@@ -622,7 +629,7 @@ impl ExecutionPreparedFilterCache {
     fn finish_partition(
         &self,
         context: &Arc<TaskContext>,
-        prepared_filter: &Arc<OnceCell<PreparedVectorSearchFilter>>,
+        prepared_filter: &Arc<OnceCell<PinnedFilter>>,
         partition: usize,
     ) {
         let mut entries = self
@@ -745,7 +752,7 @@ impl LateralVectorSearchExec {
     async fn process_batch(
         &self,
         batch: RecordBatch,
-        prepared_filter: Option<&OnceCell<PreparedVectorSearchFilter>>,
+        prepared_filter: Option<&OnceCell<PinnedFilter>>,
     ) -> DFResult<RecordBatch> {
         if batch.num_rows() == 0 {
             return empty_batch(self.output_schema.clone());
@@ -768,9 +775,15 @@ impl LateralVectorSearchExec {
                     )
                 })?;
                 let prepared = prepared_filter
-                    .get_or_try_init(|| {
-                        self.target_table
-                            .prepare_vector_search_filter(filter.clone())
+                    .get_or_try_init(|| async {
+                        let snapshot = 
self.target_table.resolve_read_snapshot().await?;
+                        let table = self
+                            .target_table
+                            .copy_with_pinned_snapshot(snapshot.as_ref());
+                        let prepared = table
+                            
.try_prepare_indexed_vector_search_filter(filter.clone())
+                            .await?;
+                        Ok::<_, paimon::Error>(PinnedFilter { table, prepared 
})
                     })
                     .await
                     .map_err(to_datafusion_error)?;
@@ -779,15 +792,17 @@ impl LateralVectorSearchExec {
             None => None,
         };
         let target_table = prepared_filter
-            .map(PreparedVectorSearchFilter::table)
+            .map(|pinned| &pinned.table)
             .unwrap_or(&self.target_table);
         let mut builder = target_table.new_batch_vector_search_builder();
         builder
             .with_vector_column(&self.target_column)
             .with_query_vectors(query_vectors)
             .with_limit(self.limit);
-        if let Some(prepared_filter) = prepared_filter {
-            builder.with_prepared_filter(prepared_filter.clone());
+        if let Some(prepared) = prepared_filter.and_then(|pinned| 
pinned.prepared.as_ref()) {
+            builder.with_prepared_filter(prepared.clone());
+        } else if let Some(filter) = &self.filter {
+            builder.with_filter(filter.clone());
         }
         let results = builder
             .execute()
@@ -1146,6 +1161,10 @@ pub(crate) fn session_config() -> SessionConfig {
     SessionConfig::new().with_information_schema(true)
 }
 
+#[cfg(test)]
+#[path = "lateral_vector_search_filter_tests.rs"]
+mod filter_tests;
+
 #[cfg(test)]
 mod tests {
     use super::*;
diff --git 
a/crates/integrations/datafusion/src/lateral_vector_search_filter_tests.rs 
b/crates/integrations/datafusion/src/lateral_vector_search_filter_tests.rs
new file mode 100644
index 00000000..da8edca3
--- /dev/null
+++ b/crates/integrations/datafusion/src/lateral_vector_search_filter_tests.rs
@@ -0,0 +1,290 @@
+// 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.
+
+use super::*;
+use crate::SQLContext;
+use datafusion::arrow::array::builder::{Float32Builder, ListBuilder};
+use datafusion::arrow::array::Int32Array;
+use datafusion::arrow::datatypes::{DataType, Field, Schema};
+use datafusion::physical_expr::expressions::Column;
+use datafusion::physical_plan::empty::EmptyExec;
+use paimon::catalog::Identifier;
+use paimon::io::FileBlockCache;
+use paimon::spec::{Datum, IndexManifest, PredicateBuilder};
+use paimon::{Catalog, CatalogOptions, FileSystemCatalog, Options};
+
+#[derive(Debug, Default)]
+struct ReadTrace(Mutex<Vec<String>>);
+
+#[async_trait]
+impl FileBlockCache for ReadTrace {
+    async fn get(&self, _: &str, _: std::ops::Range<u64>) -> 
Option<bytes::Bytes> {
+        None
+    }
+
+    async fn put(&self, path: &str, _: u64, _: bytes::Bytes) {
+        // Never cache: a put records a block actually fetched from storage.
+        self.0.lock().unwrap().push(path.to_owned());
+    }
+
+    async fn invalidate_path(&self, _: &str) {}
+    async fn invalidate_prefix(&self, _: &str) {}
+}
+
+impl ReadTrace {
+    fn reads_of(&self, names: &[String]) -> usize {
+        self.0
+            .lock()
+            .unwrap()
+            .iter()
+            .filter(|path| names.iter().any(|name| path.ends_with(name)))
+            .count()
+    }
+}
+
+fn vectors(start: i32, count: i32) -> ListArray {
+    let element = Arc::new(Field::new("element", DataType::Float32, true));
+    let mut values = 
ListBuilder::new(Float32Builder::new()).with_field(element);
+    for id in start..start + count {
+        values.values().append_slice(&[id as f32, 0.0]);
+        values.append(true);
+    }
+    values.finish()
+}
+
+async fn filter_fixture(
+    indexed: bool,
+) -> (
+    tempfile::TempDir,
+    Table,
+    Arc<ReadTrace>,
+    Vec<String>,
+    Vec<String>,
+) {
+    let temp = tempfile::tempdir().unwrap();
+    let mut options = Options::new();
+    options.set(
+        CatalogOptions::WAREHOUSE,
+        format!("file://{}", temp.path().display()),
+    );
+    let catalog = Arc::new(FileSystemCatalog::new(options).unwrap());
+    let mut context = SQLContext::new();
+    context
+        .register_catalog("paimon", catalog.clone())
+        .await
+        .unwrap();
+    context
+        .sql(
+            "CREATE TABLE paimon.default.lateral_filter (id INT, embedding 
ARRAY<FLOAT>) \
+        WITH ('data-evolution.enabled' = 'true', 'row-tracking.enabled' = 
'true', \
+        'global-index.row-count-per-shard' = '128', 'scalar-index.search-mode' 
= 'full', \
+        'ivf-flat.dimension' = '2', 'ivf-flat.nlist' = '1', 'ivf-flat.metric' 
= 'l2')",
+        )
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    let table = catalog
+        .get_table(&Identifier::new("default", "lateral_filter"))
+        .await
+        .unwrap();
+    let mut tail_files = Vec::new();
+    for start in [0, 64] {
+        let embeddings = vectors(start, 64);
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("id", DataType::Int32, false),
+            Field::new("embedding", embeddings.data_type().clone(), true),
+        ]));
+        let batch = RecordBatch::try_new(
+            schema,
+            vec![
+                Arc::new(Int32Array::from_iter_values(start..start + 64)),
+                Arc::new(embeddings),
+            ],
+        )
+        .unwrap();
+        let write = table
+            .new_write_builder()
+            .with_commit_user("lateral-test")
+            .unwrap();
+        let mut writer = write.new_write().unwrap();
+        writer.write_arrow_batch(&batch).await.unwrap();
+        let messages = writer.prepare_commit().await.unwrap();
+        if start == 64 {
+            tail_files.extend(
+                messages
+                    .iter()
+                    .flat_map(|message| &message.new_files)
+                    .map(|file| file.data_file_path(&format!("{}/bucket-0", 
table.location()))),
+            );
+        }
+        write.new_commit().commit(messages).await.unwrap();
+    }
+    table
+        .new_global_index_build_builder()
+        .with_index_type("ivf-flat")
+        .with_index_column("embedding")
+        .execute()
+        .await
+        .unwrap();
+    if indexed {
+        table
+            .new_global_index_build_builder()
+            .with_index_type("btree")
+            .with_index_column("id")
+            .execute()
+            .await
+            .unwrap();
+    }
+    let snapshot = table.resolve_read_snapshot().await.unwrap().unwrap();
+    let scalar_files = IndexManifest::read(
+        table.file_io(),
+        &format!(
+            "{}/manifest/{}",
+            table.location(),
+            snapshot.index_manifest().unwrap(),
+        ),
+    )
+    .await
+    .unwrap()
+    .into_iter()
+    .filter(|entry| entry.index_file.index_type == "btree")
+    .map(|entry| entry.index_file.file_name)
+    .collect();
+    let trace = Arc::new(ReadTrace::default());
+    let file_io = table
+        .file_io()
+        .clone()
+        .with_file_block_cache(trace.clone(), 4096, "*")
+        .unwrap();
+    let table = Table::new(
+        file_io,
+        table.identifier().clone(),
+        table.location().into(),
+        table.schema().clone(),
+        None,
+    );
+    (temp, table, trace, scalar_files, tail_files)
+}
+
+fn filtered_exec(table: Table, filter: Predicate) -> (LateralVectorSearchExec, 
RecordBatch) {
+    let query = vectors(0, 1);
+    let query_schema = Arc::new(Schema::new(vec![Field::new(
+        "query_vector",
+        query.data_type().clone(),
+        true,
+    )]));
+    let query_batch = RecordBatch::try_new(query_schema.clone(), 
vec![Arc::new(query)]).unwrap();
+    let target_schema = Arc::new(Schema::new(vec![Field::new("id", 
DataType::Int32, true)]));
+    let output_schema = Arc::new(Schema::new(vec![
+        query_schema.field(0).clone(),
+        target_schema.field(0).clone(),
+    ]));
+    let exec = LateralVectorSearchExec::new(
+        Arc::new(EmptyExec::new(query_schema)),
+        table,
+        target_schema,
+        "embedding".into(),
+        Arc::new(Column::new("query_vector", 0)),
+        1,
+        output_schema,
+    )
+    .with_filter(filter);
+    (exec, query_batch)
+}
+
+fn result_id(batch: &RecordBatch) -> i32 {
+    assert_eq!(batch.num_rows(), 1);
+    batch
+        .column(1)
+        .as_any()
+        .downcast_ref::<Int32Array>()
+        .unwrap()
+        .value(0)
+}
+
+#[tokio::test]
+async fn exact_scalar_index_is_read_once_across_lateral_batches() {
+    let (_temp, table, trace, scalar_files, _) = filter_fixture(true).await;
+    assert!(!scalar_files.is_empty());
+    let filter = PredicateBuilder::new(table.schema().fields())
+        .equal("id", Datum::Int(1))
+        .unwrap();
+    let (exec, batch) = filtered_exec(table, filter);
+    let pinned = OnceCell::new();
+    assert_eq!(
+        result_id(
+            &exec
+                .process_batch(batch.clone(), Some(&pinned))
+                .await
+                .unwrap()
+        ),
+        1
+    );
+    assert!(pinned.get().unwrap().prepared.is_some());
+    let reads = trace.reads_of(&scalar_files);
+    assert!(
+        reads > 0,
+        "the first batch must read the actual BTree payload"
+    );
+    assert_eq!(
+        result_id(&exec.process_batch(batch, Some(&pinned)).await.unwrap()),
+        1
+    );
+    assert_eq!(
+        trace.reads_of(&scalar_files),
+        reads,
+        "the next batch must reuse the exact scalar answer"
+    );
+}
+
+#[tokio::test]
+async fn unindexed_lateral_filter_keeps_candidate_reads_scoped() {
+    let (_temp, table, trace, scalar_files, tail_files) = 
filter_fixture(false).await;
+    assert!(scalar_files.is_empty());
+    assert!(!tail_files.is_empty());
+    for path in &tail_files {
+        table.file_io().delete_file(path).await.unwrap();
+    }
+    let filter = PredicateBuilder::new(table.schema().fields())
+        .less_than("id", Datum::Int(100))
+        .unwrap();
+    let (exec, batch) = filtered_exec(table, filter);
+    let pinned = OnceCell::new();
+    for _ in 0..2 {
+        assert_eq!(
+            result_id(
+                &exec
+                    .process_batch(batch.clone(), Some(&pinned))
+                    .await
+                    .unwrap()
+            ),
+            0
+        );
+    }
+    assert!(pinned.get().unwrap().prepared.is_none());
+    let tail_names = tail_files
+        .iter()
+        .map(|path| path.rsplit('/').next().unwrap().to_owned())
+        .collect::<Vec<_>>();
+    assert_eq!(
+        trace.reads_of(&tail_names),
+        0,
+        "unindexed filters must not trigger a full data pre-scan"
+    );
+}
diff --git a/crates/integrations/datafusion/src/vector_search.rs 
b/crates/integrations/datafusion/src/vector_search.rs
index c483d084..626885cb 100644
--- a/crates/integrations/datafusion/src/vector_search.rs
+++ b/crates/integrations/datafusion/src/vector_search.rs
@@ -378,31 +378,22 @@ impl VectorSearchExec {
     }
 
     async fn compute_batch(&self) -> DFResult<RecordBatch> {
-        let prepared_filter = match &self.filter {
-            Some(filter) => Some(
-                self.table
-                    .prepare_vector_search_filter(filter.clone())
-                    .await
-                    .map_err(to_datafusion_error)?,
-            ),
-            None => None,
-        };
-        let search_table = prepared_filter
-            .as_ref()
-            .map(|prepared| prepared.table())
-            .unwrap_or(&self.table);
+        let snapshot = await_with_runtime(self.table.resolve_read_snapshot())
+            .await
+            .map_err(to_datafusion_error)?;
+        let search_table = 
self.table.copy_with_pinned_snapshot(snapshot.as_ref());
 
         // Best-first row-ids from the index, searched at the full top-k so 
the ANN
         // recall is unchanged (data-evolution / global-index path; PK-vector 
tables are
         // unsupported here, as before).
         let mut search_result = await_with_runtime(async {
-            let mut builder = self.table.new_batch_vector_search_builder();
+            let mut builder = search_table.new_batch_vector_search_builder();
             builder
                 .with_vector_column(&self.column_name)
                 .with_query_vectors(vec![self.query_vector.clone()])
                 .with_limit(self.search_limit);
-            if let Some(prepared) = &prepared_filter {
-                builder.with_prepared_filter(prepared.clone());
+            if let Some(filter) = &self.filter {
+                builder.with_filter(filter.clone());
             }
             let mut results = 
builder.execute().await.map_err(to_datafusion_error)?;
             results
@@ -428,7 +419,7 @@ impl VectorSearchExec {
 
         // Read the projected columns (+ internal `_ROW_ID`); the row-range 
scan yields
         // file order, realigned to relevance rank below.
-        let read_fields = projected_read_fields(search_table, 
self.projection.as_ref())?;
+        let read_fields = projected_read_fields(&search_table, 
self.projection.as_ref())?;
         let row_ranges = 
search_result.to_row_ranges().map_err(to_datafusion_error)?;
         let batches = await_with_runtime(async {
             let mut read_builder = search_table.new_read_builder();
@@ -656,6 +647,37 @@ mod tests {
     use super::*;
     use crate::SQLContext;
 
+    #[test]
+    fn unfiltered_snapshot_io_uses_runtime_bridge_when_polled_without_tokio() {
+        let temp_dir = tempfile::tempdir().unwrap();
+        let table = crate::runtime::runtime().block_on(async {
+            let mut options = Options::new();
+            options.set(CatalogOptions::WAREHOUSE, format!("file://{}", 
temp_dir.path().display()));
+            let catalog = Arc::new(FileSystemCatalog::new(options).unwrap());
+            let mut context = SQLContext::new();
+            context.register_catalog("paimon", catalog.clone()).await.unwrap();
+            context.sql("CREATE TABLE paimon.default.no_runtime_vectors (id 
INT, embedding ARRAY<FLOAT>) \
+                WITH ('data-evolution.enabled' = 'true', 
'row-tracking.enabled' = 'true')")
+                .await.unwrap();
+            context.sql("INSERT INTO paimon.default.no_runtime_vectors (id) 
VALUES (1)")
+                .await.unwrap().collect().await.unwrap();
+            catalog.get_table(&paimon::catalog::Identifier::new("default", 
"no_runtime_vectors"))
+                .await.unwrap()
+        });
+        assert!(tokio::runtime::Handle::try_current().is_err());
+        let exec = VectorSearchExec::new(
+            table,
+            "embedding".into(),
+            vec![1.0],
+            1,
+            None,
+            None,
+            Arc::new(datafusion::arrow::datatypes::Schema::empty()),
+        );
+        let batch = futures::executor::block_on(exec.compute_batch()).unwrap();
+        assert_eq!(batch.num_rows(), 0);
+    }
+
     #[tokio::test]
     async fn test_vector_search_applies_supported_session_dynamic_options() {
         let temp_dir = tempfile::tempdir().unwrap();
diff --git a/crates/integrations/datafusion/tests/read_tables.rs 
b/crates/integrations/datafusion/tests/read_tables.rs
index ed5fb70f..6ad42d97 100644
--- a/crates/integrations/datafusion/tests/read_tables.rs
+++ b/crates/integrations/datafusion/tests/read_tables.rs
@@ -2302,6 +2302,29 @@ mod vector_search_tests {
         assert_eq!(ids, vec![0, 1, 2]);
     }
 
+    #[tokio::test]
+    async fn test_vector_search_filters_without_scalar_index() {
+        let (ctx, _catalog, _tmp) = 
create_java_vindex_vector_search_context().await;
+        let batches = ctx.sql(
+            "SELECT id FROM 
vector_search('paimon.default.test_java_vindex_vector', 'embedding', '[1.0, 
0.0, 0.0, 0.0]', 1) WHERE id = 2",
+        ).await.unwrap().collect().await.unwrap();
+        assert_eq!(extract_ids_in_order(&batches), vec![2]);
+
+        let queries = build_vector_batch(
+            vec![10, 20],
+            vec![vec![1.0, 0.0, 0.0, 0.0], vec![0.0, 1.0, 0.0, 0.0]],
+        );
+        let table = MemTable::try_new(queries.schema(), 
vec![vec![queries]]).unwrap();
+        ctx.register_temp_table("paimon.default.unindexed_filter_queries", 
Arc::new(table))
+            .unwrap();
+        let batches = ctx.sql(
+            "SELECT q.id AS query_id, r.id AS result_id FROM 
paimon.default.unindexed_filter_queries q \
+             CROSS JOIN LATERAL 
vector_search('paimon.default.test_java_vindex_vector', 'embedding', 
q.embedding, 1) AS r \
+             WHERE r.id = 2 ORDER BY query_id",
+        ).await.unwrap().collect().await.unwrap();
+        assert_eq!(extract_query_result_ids(&batches), vec![(10, 2), (20, 2)]);
+    }
+
     #[tokio::test]
     async fn test_vector_search_lateral_join_uses_query_vectors() {
         let (ctx, _catalog, _tmp) = 
create_java_vindex_vector_search_context().await;
diff --git a/crates/paimon/src/spec/predicate.rs 
b/crates/paimon/src/spec/predicate.rs
index 388883b9..7b242143 100644
--- a/crates/paimon/src/spec/predicate.rs
+++ b/crates/paimon/src/spec/predicate.rs
@@ -54,7 +54,7 @@ use std::fmt;
 /// e.g. `Decimal(10, scale=1)` == `Decimal(100, scale=2)`
 /// because both represent `1.0`.
 ///
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
 pub enum Datum {
     Bool(bool),
     TinyInt(i8),
@@ -269,7 +269,7 @@ fn java_bytes_cmp(a: &[u8], b: &[u8]) -> Ordering {
 // ---------------------------------------------------------------------------
 
 /// Predicate operators for leaf predicates.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, 
serde::Deserialize)]
 pub enum PredicateOperator {
     IsNull,
     IsNotNull,
@@ -368,7 +368,7 @@ impl fmt::Display for PredicateOperator {
 /// - `And` / `Or`: N-ary logical connectives (auto-flattened)
 /// - `Not`: logical negation
 /// - `AlwaysTrue` / `AlwaysFalse`: constant predicates
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
 pub enum Predicate {
     /// Leaf: column op literal(s).
     Leaf {
diff --git a/crates/paimon/src/table/batch_vector_search_builder.rs 
b/crates/paimon/src/table/batch_vector_search_builder.rs
index 4853a27f..ec06e277 100644
--- a/crates/paimon/src/table/batch_vector_search_builder.rs
+++ b/crates/paimon/src/table/batch_vector_search_builder.rs
@@ -104,7 +104,8 @@ impl<'a> BatchVectorSearchBuilder<'a> {
     /// Attach a caller-managed row-ID allow-list.
     ///
     /// This low-level API does not bind the allow-list to a table snapshot.
-    /// Prefer [`Self::with_prepared_filter`] for scalar pre-filters.
+    /// Use [`Self::with_filter`] to let the planner choose a filtering 
strategy,
+    /// or [`Self::with_prepared_filter`] to reuse an explicitly resolved set.
     pub fn with_include_row_ids(&mut self, include_row_ids: RoaringTreemap) -> 
&mut Self {
         self.include_row_ids = Some(Arc::new(include_row_ids));
         self.filter = None;
diff --git a/crates/paimon/src/table/de_vector_read.rs 
b/crates/paimon/src/table/de_vector_read.rs
index cfe01023..14ace32a 100644
--- a/crates/paimon/src/table/de_vector_read.rs
+++ b/crates/paimon/src/table/de_vector_read.rs
@@ -25,7 +25,8 @@ use crate::spec::{
 use crate::table::de_vector_scan::DeVectorScanPlan;
 use crate::table::global_index_scanner::{
     deleted_row_ranges_for_data_evolution_dvs, search_limit_with_deleted_rows,
-    unindexed_ranges_for_global_index_entries, GlobalIndexScanner, 
RowRangeIndex,
+    unindexed_ranges_for_global_index_entries, 
unindexed_ranges_for_indexed_coverage,
+    GlobalIndexScanner, RowRangeIndex,
 };
 use crate::table::global_index_search_filter::matching_row_ids_for_filter;
 use crate::table::global_index_types::normalize_queryable_global_index_type;
@@ -67,6 +68,8 @@ use std::io::Cursor;
 use std::sync::Arc;
 use std::time::{Duration, Instant};
 
+mod post_filter;
+
 /// Owns the queries and executes the snapshot-scoped plan from `DeVectorScan`.
 pub(super) struct DeVectorRead {
     vector_searches: Vec<VectorSearch>,
@@ -322,7 +325,7 @@ async fn execute_vector_index_work(
     let file_size = work.entry.index_file.file_size as u64;
     let index_meta_bytes = global_meta.index_meta.clone().unwrap_or_default();
     let row_range_start = global_meta.row_range_start;
-    let vector_searches = work.queries;
+    let mut vector_searches = work.queries;
     let options = if let Some(resolved) = work.resolved {
         if resolved.index_type.as_deref() != 
Some(work.entry.index_file.index_type.as_str()) {
             return Err(crate::table::search_task::invalid(
@@ -338,6 +341,46 @@ async fn execute_vector_index_work(
             &work.entry.index_file.index_type,
         )?
     };
+    let targets: Vec<_> = vector_searches.iter().map(|query| 
query.limit).collect();
+    if work.filter.is_some() {
+        if work.top_ks.len() != vector_searches.len() || 
work.top_ks.contains(&0) {
+            return Err(crate::table::search_task::invalid(
+                "Post-filtering requires each original Top-K",
+            ));
+        }
+        let factor = post_filter::candidates_factor(&options)?;
+        let from = u64::try_from(row_range_start)
+            .map_err(|_| crate::table::search_task::invalid("Invalid vector 
shard start"))?;
+        let shard_size = u64::try_from(global_meta.row_range_end)
+            .ok()
+            .and_then(|to| to.checked_sub(from))
+            .and_then(|count| count.checked_add(1))
+            .ok_or_else(|| crate::table::search_task::invalid("Invalid vector 
shard range"))?;
+        for (query, &top_k) in vector_searches.iter_mut().zip(&work.top_ks) {
+            query.limit = post_filter::candidate_limit(top_k, factor, 
query.limit, shard_size);
+        }
+    }
+    let post_filter = work
+        .filter
+        .as_ref()
+        .map(|predicate| {
+            Ok::<_, crate::Error>(VectorIndexPostFilter {
+                table: evaluation
+                    .table
+                    .ok_or_else(|| {
+                        crate::table::search_task::invalid(
+                            "Vector post-filter requires table context",
+                        )
+                    })?
+                    .clone(),
+                predicate: predicate.clone(),
+                from: row_range_start as u64,
+                to: global_meta.row_range_end as u64,
+                targets,
+                concurrency,
+            })
+        })
+        .transpose()?;
     let input = evaluation.file_io.new_input(&path);
     if vector_searches.iter().all(|search| {
         search
@@ -389,6 +432,7 @@ async fn execute_vector_index_work(
                 VectorIndexSearchContext {
                     parallelism: batch_index_parallelism,
                     metrics: metric_check,
+                    post_filter,
                 },
                 permit,
             )
@@ -398,7 +442,7 @@ async fn execute_vector_index_work(
             }
             results
         }
-        Err(_) if query_count > 1 => {
+        Err(_) if query_count > 1 || work.filter.is_some() => {
             let read_start = timing_enabled.then(Instant::now);
             let data = input.read().await.map_err(|e| 
crate::Error::DataInvalid {
                 message: format!("Failed to read vindex index file '{}': {}", 
file_name, e),
@@ -416,6 +460,7 @@ async fn execute_vector_index_work(
                 VectorIndexSearchContext {
                     parallelism: batch_index_parallelism,
                     metrics: metric_check,
+                    post_filter,
                 },
                 permit,
             )
@@ -450,16 +495,15 @@ async fn execute_vector_index_work(
         });
     }
 
+    let results = results
+        .into_iter()
+        .map(|result| match result {
+            Some(scored_map) => 
ScoredRowIds::from_scored_map(scored_map).offset(row_range_start),
+            None => ScoredRowIds::empty(),
+        })
+        .collect::<Vec<_>>();
     Ok::<_, crate::Error>((
-        results
-            .into_iter()
-            .map(|result| match result {
-                Some(scored_map) => {
-                    
ScoredRowIds::from_scored_map(scored_map).offset(row_range_start)
-                }
-                None => ScoredRowIds::empty(),
-            })
-            .collect::<Vec<_>>(),
+        results,
         IndexSearchTiming {
             permit_wait,
             file_reader_open,
@@ -482,6 +526,17 @@ async fn execute_vindex_searches<S: SeekRead + 'static, G: 
Send + 'static>(
     context: VectorIndexSearchContext,
     guard: G,
 ) -> crate::Result<Vec<Option<HashMap<u64, f32>>>> {
+    if context.post_filter.is_some() {
+        return execute_post_filter_vindex_searches(
+            io_meta,
+            options,
+            vector_searches,
+            source,
+            context,
+            guard,
+        )
+        .await;
+    }
     let panic_context = if vector_searches.len() > 1 {
         "vindex global-index batch search task failed"
     } else {
@@ -508,6 +563,91 @@ async fn execute_vindex_searches<S: SeekRead + 'static, G: 
Send + 'static>(
     .await
 }
 
+async fn execute_post_filter_vindex_searches<S: SeekRead + 'static, G: Send + 
'static>(
+    io_meta: GlobalIndexIOMeta,
+    options: HashMap<String, String>,
+    vector_searches: Vec<VectorSearch>,
+    source: S,
+    context: VectorIndexSearchContext,
+    guard: G,
+) -> crate::Result<Vec<Option<HashMap<u64, f32>>>> {
+    let filter = context.post_filter.unwrap();
+    let batch_size =
+        post_filter::batch_size(vector_searches.iter().map(|q| 
q.limit).max().unwrap_or(1));
+    let mut queries = vector_searches.into_iter().zip(filter.targets);
+    let mut reader = VindexVectorGlobalIndexReader::new(io_meta, options)
+        .with_batch_index_parallelism(context.parallelism);
+    let mut source = Some(source);
+    let mut first_guard = Some(guard);
+    let mut results = Vec::new();
+    loop {
+        let (batch, targets): (Vec<_>, Vec<_>) = 
queries.by_ref().take(batch_size).unzip();
+        if batch.is_empty() {
+            return Ok(results);
+        }
+        let source = source.take();
+        let metrics = context.metrics.clone();
+        let task = move || {
+            let rows = reader.visit_batch_vector_search_validated(
+                &batch,
+                |_| {
+                    source.ok_or_else(|| {
+                        crate::table::search_task::invalid("Vector reader was 
not retained")
+                    })
+                },
+                |metadata| 
metrics.check(RawVectorMetric::from_vindex(metadata.metric)),
+            )?;
+            Ok((rows, reader))
+        };
+        // Keep the loaded reader between chunks, but release its search permit
+        // before awaiting scalar I/O. Each input query belongs to one chunk.
+        let (rows, retained_reader) = if let Some(guard) = first_guard.take() {
+            execute_global_index_with_guard("vindex post-filter search 
failed", guard, task).await?
+        } else {
+            let permit = 
acquire_process_global_search_permit(filter.concurrency).await?;
+            execute_global_index_with_guard("vindex post-filter search 
failed", permit, task)
+                .await?
+        };
+        reader = retained_reader;
+        if rows.len() != targets.len() {
+            return Err(crate::table::search_task::invalid(
+                "Vector index returned wrong query count",
+            ));
+        }
+        let mut candidates = RoaringTreemap::new();
+        for scores in rows.iter().flatten() {
+            for &id in scores.keys() {
+                let global = id
+                    .checked_add(filter.from)
+                    .filter(|id| *id <= filter.to)
+                    .ok_or_else(|| {
+                        crate::table::search_task::invalid(
+                            "Vector candidate lies outside its shard",
+                        )
+                    })?;
+                candidates.insert(global);
+            }
+        }
+        let matched = if candidates.is_empty() {
+            candidates
+        } else {
+            matching_row_ids_for_filter(
+                &filter.table,
+                &filter.predicate,
+                Some(sorted_row_ids_to_row_ranges(candidates.iter())?),
+            )
+            .await?
+        };
+        for (scores, target) in rows.into_iter().zip(targets) {
+            results.push(scores.map(|mut scores| {
+                scores.retain(|id, _| matched.contains(filter.from + id));
+                let retained = 
ScoredRowIds::from_scored_map(scores).top_k(target);
+                retained.row_ids.into_iter().zip(retained.scores).collect()
+            }));
+        }
+    }
+}
+
 #[derive(Clone, Copy)]
 pub(super) struct VectorSearchEvaluation<'a> {
     pub(super) table: Option<&'a Table>,
@@ -556,6 +696,16 @@ impl VectorMetricCheck {
 struct VectorIndexSearchContext {
     parallelism: usize,
     metrics: VectorMetricCheck,
+    post_filter: Option<VectorIndexPostFilter>,
+}
+
+struct VectorIndexPostFilter {
+    table: Table,
+    predicate: Predicate,
+    from: u64,
+    to: u64,
+    targets: Vec<usize>,
+    concurrency: usize,
 }
 
 #[derive(Default)]
@@ -579,14 +729,11 @@ async fn evaluate_vector_search(
     crate::table::vector_search_common::take_only_result(results, "vector 
search")?.to_row_ranges()
 }
 
-/// None means the scalar index cannot evaluate the filter: Java routes all
-/// vector-index-covered ranges to raw scoring in that case, even in FAST mode.
-async fn scalar_matched_row_ids(
+/// Search pre-filters and coverage planning use the same single-field indexes.
+pub(super) fn scalar_filter_scanner(
     evaluation: VectorSearchEvaluation<'_>,
     entries: &[IndexManifestEntry],
-    vector_ranges: &[RowRange],
-    filter: &Predicate,
-) -> crate::Result<Option<RoaringTreemap>> {
+) -> crate::Result<Option<GlobalIndexScanner>> {
     // Java search pre-filters use per-column coverage and exclude multi-field
     // definitions, even though ordinary table scans can use composite indexes.
     let scalar_entries: Vec<_> = entries
@@ -624,10 +771,21 @@ async fn scalar_matched_row_ids(
             crate::fm_index::FMReadOptions::default()
         },
     )?;
-    let Some(scanner) = scanner else {
+    scanner
+        .map(|scanner| scanner.with_field_options(evaluation.table_options, 
&scalar_entries))
+        .transpose()
+}
+
+/// None selects one ANN query followed by exact candidate filtering.
+async fn scalar_matched_row_ids(
+    evaluation: VectorSearchEvaluation<'_>,
+    entries: &[IndexManifestEntry],
+    vector_ranges: &[RowRange],
+    filter: &Predicate,
+) -> crate::Result<Option<RoaringTreemap>> {
+    let Some(scanner) = scalar_filter_scanner(evaluation, entries)? else {
         return Ok(None);
     };
-    let scanner = scanner.with_field_options(evaluation.table_options, 
&scalar_entries)?;
     let Some((ranges, exact, candidate_ranges)) =
         scanner.matching_ranges_with_exactness(filter).await?
     else {
@@ -647,7 +805,7 @@ async fn scalar_matched_row_ids(
     if candidates.is_empty() {
         return Ok(Some(matched));
     }
-    if !core.global_index_filter_refine_from_data() {
+    if 
!CoreOptions::new(evaluation.table_options).global_index_filter_refine_from_data()
 {
         log::warn!("Scalar global index only provides candidates for 
{filter:?}; global-index.filter.refine-from-data is false, so indexed 
candidates are excluded");
         return Ok(Some(matched));
     }
@@ -659,7 +817,7 @@ async fn scalar_matched_row_ids(
     Ok(Some(matched))
 }
 
-fn scalar_row_ids(ranges: &[RowRange]) -> crate::Result<RoaringTreemap> {
+pub(super) fn scalar_row_ids(ranges: &[RowRange]) -> 
crate::Result<RoaringTreemap> {
     let mut row_ids = RoaringTreemap::new();
     for range in ranges {
         let start = u64::try_from(range.from()).map_err(|_| 
crate::Error::DataInvalid {
@@ -839,7 +997,8 @@ async fn evaluate_batch_vector_search_with_executor(
             }
         }
     }
-    let mut route_indexed_to_raw = false;
+    post_filter::candidates_factor(&effective_options)?;
+    let mut post_filter_predicate = None;
     // Partition predicates have already pruned manifest entries. They do not
     // make an otherwise exact scalar lookup candidate-only.
     let scalar_filter = evaluation.filter.and_then(|filter| match 
evaluation.table {
@@ -873,7 +1032,7 @@ async fn evaluate_batch_vector_search_with_executor(
                     }
                 }
             }
-            None => route_indexed_to_raw = true,
+            None => post_filter_predicate = evaluation.filter.cloned(),
         }
     }
 
@@ -912,9 +1071,9 @@ async fn evaluate_batch_vector_search_with_executor(
     let index_search_limit = indexed_search_limit(max_limit, refine_factor)?;
 
     let vector_entry_count = vector_entries.len();
-    let vector_search_plans = if route_indexed_to_raw {
-        Vec::new()
-    } else if let Some(include_row_ids) = 
shared_batch_include_row_ids(&indexed_searches) {
+    let vector_search_plans = if let Some(include_row_ids) =
+        shared_batch_include_row_ids(&indexed_searches)
+    {
         let ranges = vector_entries
             .iter()
             .map(|entry| {
@@ -1014,6 +1173,12 @@ async fn evaluate_batch_vector_search_with_executor(
                     entry: entry.clone(),
                     queries: searches,
                     resolved: Some(configuration.resolved.clone()),
+                    filter: post_filter_predicate.clone(),
+                    top_ks: if post_filter_predicate.is_some() {
+                        vector_searches.iter().map(|query| 
query.limit).collect()
+                    } else {
+                        Vec::new()
+                    },
                 })
             });
         let results = if let Some(executor) = executor {
@@ -1031,10 +1196,18 @@ async fn evaluate_batch_vector_search_with_executor(
                             entry: work.entry,
                             queries: 
TaskVectorQueries::capture(&work.queries)?,
                             resolved: work.resolved,
+                            filter: work.filter,
+                            top_ks: work.top_ks,
                         };
                         SearchTask::new(
                             table,
-                            "vector-index",
+                            // Older workers must reject this work instead of
+                            // ignoring an unfamiliar predicate payload.
+                            if work.filter.is_some() {
+                                "vector-index-filtered"
+                            } else {
+                                "vector-index"
+                            },
                             serde_json::to_value(work).map_err(|error| {
                                 
crate::table::search_task::invalid(error.to_string())
                             })?,
@@ -1107,7 +1280,6 @@ async fn evaluate_batch_vector_search_with_executor(
     }
 
     if sources.is_some()
-        || route_indexed_to_raw
         || search_mode != GlobalIndexSearchMode::Fast
         || scalar_search_mode.is_some_and(|mode| mode != 
GlobalIndexSearchMode::Fast)
     {
@@ -1145,14 +1317,17 @@ async fn evaluate_batch_vector_search_with_executor(
                 &detail_ranges,
                 is_vector_global_index_file,
             );
-            if let (Some(filter), Some(scalar_mode)) = (&scalar_filter, 
scalar_search_mode) {
+            if let (Some(filter), Some(scalar_mode), None) =
+                (&scalar_filter, scalar_search_mode, &post_filter_predicate)
+            {
                 let mut scalar_ranges = scalar_unindexed_ranges(
                     evaluation,
                     index_entries,
                     filter,
                     scalar_mode,
                     &detail_ranges,
-                );
+                )
+                .await?;
                 // Scalar FULL/DETAIL also recover gaps inside vector 
coverage. In
                 // vector FAST they must not expand beyond the indexed corpus.
                 if search_mode == GlobalIndexSearchMode::Fast {
@@ -1162,9 +1337,6 @@ async fn evaluate_batch_vector_search_with_executor(
             }
             ranges
         };
-        if route_indexed_to_raw {
-            raw_ranges.extend(vector_ranges);
-        }
         raw_ranges = merge_row_ranges(raw_ranges);
         if !raw_ranges.is_empty() {
             let table = evaluation.table.ok_or_else(|| 
crate::Error::DataInvalid {
@@ -1263,27 +1435,70 @@ async fn evaluate_batch_vector_search_with_executor(
     Ok(results)
 }
 
-/// Predicate coverage requires every referenced field to be covered by a
-/// single-field scalar index. Reuse the table scanner's coverage accounting.
-pub(super) fn scalar_unindexed_ranges(
+/// Recover partial row coverage only when an index can evaluate the predicate.
+/// An unsupported predicate uses post-filtering and needs no scalar-gap scan.
+pub(super) async fn scalar_unindexed_ranges(
     evaluation: VectorSearchEvaluation<'_>,
     entries: &[IndexManifestEntry],
     filter: &Predicate,
     search_mode: GlobalIndexSearchMode,
     data_ranges: &[RowRange],
-) -> Vec<RowRange> {
-    if evaluation.next_row_id.is_none_or(|next| next <= 0) {
-        return Vec::new();
+) -> crate::Result<Vec<RowRange>> {
+    if search_mode == GlobalIndexSearchMode::Fast {
+        return Ok(Vec::new());
     }
     let mut leaf_refs = Vec::new();
     crate::arrow::residual::collect_predicate_leaf_refs(filter, &mut 
leaf_refs);
-    let field_ids = leaf_refs
+    let field_ids: HashSet<_> = leaf_refs
         .into_iter()
         .filter_map(|(column, _)| 
find_field_id_by_name(evaluation.schema_fields, column))
         .collect();
+    let data_ranges = scalar_coverage_gaps(
+        evaluation,
+        entries,
+        &HashSet::new(),
+        search_mode,
+        data_ranges,
+    );
+    // Most queries have either full coverage or no scalar indexes. Avoid
+    // opening index readers in planning unless a field has partial coverage.
+    let has_partial_coverage = field_ids.into_iter().any(|field_id| {
+        let gaps = scalar_coverage_gaps(
+            evaluation,
+            entries,
+            &HashSet::from([field_id]),
+            search_mode,
+            &data_ranges,
+        );
+        !gaps.is_empty() && gaps != data_ranges
+    });
+    if !has_partial_coverage {
+        return Ok(Vec::new());
+    }
+    let Some(scanner) = scalar_filter_scanner(evaluation, entries)? else {
+        return Ok(Vec::new());
+    };
+    let Some(coverage) = scanner.matching_indexed_coverage(filter).await? else 
{
+        return Ok(Vec::new());
+    };
+    Ok(unindexed_ranges_for_indexed_coverage(
+        &coverage,
+        search_mode,
+        evaluation.next_row_id,
+        &data_ranges,
+    ))
+}
+
+pub(super) fn scalar_coverage_gaps(
+    evaluation: VectorSearchEvaluation<'_>,
+    entries: &[IndexManifestEntry],
+    field_ids: &HashSet<i32>,
+    search_mode: GlobalIndexSearchMode,
+    data_ranges: &[RowRange],
+) -> Vec<RowRange> {
     unindexed_ranges_for_global_index_entries(
         entries,
-        &field_ids,
+        field_ids,
         search_mode,
         evaluation.next_row_id,
         data_ranges,
@@ -2765,11 +2980,17 @@ struct VectorIndexTask {
     queries: TaskVectorQueries,
     #[serde(default)]
     resolved: Option<crate::spec::VectorIndexOptions>,
+    #[serde(default)]
+    filter: Option<Predicate>,
+    #[serde(default, skip_serializing_if = "Vec::is_empty")]
+    top_ks: Vec<usize>,
 }
 struct VectorIndexWork {
     entry: IndexManifestEntry,
     queries: Vec<VectorSearch>,
     resolved: Option<crate::spec::VectorIndexOptions>,
+    filter: Option<Predicate>,
+    top_ks: Vec<usize>,
 }
 #[derive(Serialize, Deserialize)]
 struct VectorRowsTask {
@@ -2826,9 +3047,14 @@ pub(super) async fn execute_search_task(
     payload: &serde_json::Value,
 ) -> crate::Result<serde_json::Value> {
     let scores = match kind {
-        "vector-index" => {
+        "vector-index" | "vector-index-filtered" => {
             let work: VectorIndexTask = serde_json::from_value(payload.clone())
                 .map_err(|error| 
crate::table::search_task::invalid(error.to_string()))?;
+            if kind == "vector-index-filtered" && work.filter.is_none() {
+                return Err(crate::table::search_task::invalid(
+                    "Filtered vector task is missing its predicate",
+                ));
+            }
             if work.queries.queries.is_empty() {
                 return Err(crate::table::search_task::invalid(
                     "Vector task has no queries",
@@ -2856,6 +3082,8 @@ pub(super) async fn execute_search_task(
                     entry: work.entry,
                     queries: work.queries.restore()?,
                     resolved: work.resolved,
+                    filter: work.filter,
+                    top_ks: work.top_ks,
                 },
                 metric_check.clone(),
                 RangeReadLimiter::new(range_concurrency),
diff --git a/crates/paimon/src/table/de_vector_read/post_filter.rs 
b/crates/paimon/src/table/de_vector_read/post_filter.rs
new file mode 100644
index 00000000..5b44bf94
--- /dev/null
+++ b/crates/paimon/src/table/de_vector_read/post_filter.rs
@@ -0,0 +1,98 @@
+// 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.
+
+use std::collections::HashMap;
+
+const CANDIDATES_FACTOR: &str = "vector-index.post-filter.candidates-factor";
+
+pub(super) fn candidates_factor(options: &HashMap<String, String>) -> 
crate::Result<usize> {
+    match options.get(CANDIDATES_FACTOR) {
+        None => Ok(10),
+        Some(value) => value
+            .parse::<usize>()
+            .ok()
+            .filter(|n| *n > 0 && *n <= i32::MAX as usize)
+            .ok_or_else(|| crate::Error::ConfigInvalid {
+                message: format!(
+                    "{CANDIDATES_FACTOR} must be between 1 and {}, got 
{value}",
+                    i32::MAX
+                ),
+            }),
+    }
+}
+
+pub(super) fn candidate_limit(
+    top_k: usize,
+    factor: usize,
+    required: usize,
+    shard_size: u64,
+) -> usize {
+    top_k
+        .saturating_mul(factor)
+        .max(required)
+        .min(usize::try_from(shard_size).unwrap_or(usize::MAX))
+        .min(i32::MAX as usize)
+}
+
+// Bound retained candidate maps as well as native scratch allocations.
+const MAX_BATCH_CANDIDATES: usize = 1 << 20;
+
+pub(super) fn batch_size(candidate_limit: usize) -> usize {
+    (MAX_BATCH_CANDIDATES / candidate_limit.max(1)).max(1)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn batches_bound_candidate_maps_without_reducing_query_limits() {
+        assert_eq!(batch_size(1000), 1048);
+        assert_eq!(batch_size(usize::MAX), 1);
+        assert_eq!(batch_size(1), MAX_BATCH_CANDIDATES);
+    }
+
+    #[test]
+    fn count_uses_original_top_k_and_preserves_required_allowance() {
+        assert_eq!(candidates_factor(&HashMap::new()).unwrap(), 10);
+        assert_eq!(candidate_limit(2, 10, 6, 1000), 20);
+        assert_eq!(candidate_limit(2, 1, 6, 1000), 6);
+        assert_eq!(candidate_limit(2, 10, 6, 12), 12);
+        assert_eq!(
+            candidate_limit(usize::MAX, 10, 6, u64::MAX),
+            i32::MAX as usize
+        );
+        assert_eq!(candidate_limit(2, 10, 6, 0), 0);
+        for value in ["0", "-1", "abc", "2147483648"] {
+            assert!(
+                candidates_factor(&HashMap::from([(CANDIDATES_FACTOR.into(), 
value.into())]))
+                    .is_err()
+            );
+        }
+    }
+    #[test]
+    fn task_literal_transport_preserves_decimal() {
+        use crate::spec::Datum;
+        let decimal = Datum::Decimal {
+            unscaled: i128::MAX,
+            precision: 38,
+            scale: 2,
+        };
+        let encoded = serde_json::to_value(&decimal).unwrap();
+        assert_eq!(serde_json::from_value::<Datum>(encoded).unwrap(), decimal);
+    }
+}
diff --git a/crates/paimon/src/table/de_vector_read/tests.rs 
b/crates/paimon/src/table/de_vector_read/tests.rs
index 3c210847..535d1543 100644
--- a/crates/paimon/src/table/de_vector_read/tests.rs
+++ b/crates/paimon/src/table/de_vector_read/tests.rs
@@ -1683,7 +1683,7 @@ async fn 
filtered_rerank_rejects_metric_from_a_skipped_shard() {
 }
 
 #[test]
-fn scalar_unindexed_coverage_intersects_all_predicate_fields() {
+fn scalar_coverage_gaps_use_single_field_definitions() {
     let io = FileIOBuilder::new("memory").build().unwrap();
     let options = HashMap::new();
     let fields = vec![make_field(1, "id"), make_field(2, "other")];
@@ -1700,40 +1700,32 @@ fn 
scalar_unindexed_coverage_intersects_all_predicate_fields() {
     let meta = composite.index_file.global_index_meta.as_mut().unwrap();
     meta.row_range_end = 19;
     meta.extra_field_ids = Some(vec![2]);
-    let builder = crate::spec::PredicateBuilder::new(&fields);
-    let predicates = vec![
-        builder.equal("id", crate::spec::Datum::Int(7)).unwrap(),
-        builder.equal("other", crate::spec::Datum::Int(7)).unwrap(),
-    ];
-    for filter in [
-        Predicate::and(predicates.clone()),
-        Predicate::or(predicates),
-    ] {
+    for field_ids in [HashSet::from([2]), HashSet::from([1, 2])] {
         let entries = vec![id.clone(), other.clone(), composite.clone()];
         assert_eq!(
-            scalar_unindexed_ranges(
+            scalar_coverage_gaps(
                 evaluation,
                 &entries,
-                &filter,
+                &field_ids,
                 GlobalIndexSearchMode::Full,
                 &[]
             ),
             vec![RowRange::new(5, 19)]
         );
         assert_eq!(
-            scalar_unindexed_ranges(
+            scalar_coverage_gaps(
                 evaluation,
                 &entries,
-                &filter,
+                &field_ids,
                 GlobalIndexSearchMode::Detail,
                 &[RowRange::new(0, 9), RowRange::new(15, 17)]
             ),
             vec![RowRange::new(5, 9), RowRange::new(15, 17)]
         );
-        assert!(scalar_unindexed_ranges(
+        assert!(scalar_coverage_gaps(
             evaluation,
             &entries,
-            &filter,
+            &field_ids,
             GlobalIndexSearchMode::Fast,
             &[]
         )
@@ -1741,10 +1733,10 @@ fn 
scalar_unindexed_coverage_intersects_all_predicate_fields() {
         // An index from another family cannot fill scalar coverage.
         id.index_file.index_type = "full-text".to_string();
         assert_eq!(
-            scalar_unindexed_ranges(
+            scalar_coverage_gaps(
                 evaluation,
                 &[id.clone(), other.clone()],
-                &filter,
+                &HashSet::from([1, 2]),
                 GlobalIndexSearchMode::Full,
                 &[]
             ),
@@ -1776,7 +1768,15 @@ impl crate::table::SearchTaskExecutor for 
WireSearchExecutor {
         let mut results = Vec::new();
         for (task, frame) in tasks.iter().zip(frames) {
             let value: serde_json::Value = 
serde_json::from_slice(&task.serialize()?).unwrap();
-            if value["kind"] == "vector-index" {
+            if value["kind"] == "vector-index-filtered" {
+                // This fixture requests K=1 with refine_factor=2: transport
+                // the original result limit, not the enlarged index limit.
+                assert_eq!(value["payload"]["top_ks"], serde_json::json!([1, 
1]));
+            }
+            if matches!(
+                value["kind"].as_str(),
+                Some("vector-index" | "vector-index-filtered")
+            ) {
                 let resolved: crate::spec::VectorIndexOptions =
                     
serde_json::from_value(value["payload"]["resolved"].clone()).unwrap();
                 assert_eq!(resolved.index_type.as_deref(), Some("ivf-flat"));
@@ -1799,6 +1799,93 @@ impl crate::table::SearchTaskExecutor for 
WireSearchExecutor {
     }
 }
 
+#[tokio::test]
+async fn scheduled_unevaluable_scalar_filter_keeps_vector_index() {
+    use crate::table::de_vector_scan::DeVectorScan;
+    use crate::table::vector_scan::Scan;
+
+    let table = de_vector_table().await;
+    let filter = id_gt_filter(&table, 1);
+    let mut plan = DeVectorScan::new(&table, Some(&filter), None, None)
+        .plan()
+        .await
+        .unwrap();
+    plan.index_entries
+        .retain(|entry| entry.index_file.index_type == "ivf-flat");
+    let reader = DeVectorRead::new(
+        "embedding",
+        &[&[1.0, 0.0], &[0.0, 1.0]],
+        1,
+        &HashMap::from([("refine_factor".into(), "2".into())]),
+    )
+    .unwrap();
+    let executor = WireSearchExecutor {
+        table,
+        kinds: std::sync::Mutex::new(Vec::new()),
+        fail: false,
+    };
+    let results = reader
+        .read_with_executor(plan, Some(&executor))
+        .await
+        .unwrap();
+    assert_eq!(results[0].row_ids().unwrap().row_ids, vec![2]);
+    assert_eq!(results[1].row_ids().unwrap().row_ids, vec![1]);
+    assert!(executor
+        .kinds
+        .lock()
+        .unwrap()
+        .iter()
+        .any(|kind| kind == "vector-index-filtered"));
+}
+
+#[test]
+fn filtered_batch_preserves_buffered_search_without_tokio() {
+    use crate::table::de_vector_scan::DeVectorScan;
+    use crate::table::vector_scan::Scan;
+
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    let table = runtime.block_on(de_vector_table());
+    let filter = id_gt_filter(&table, 1);
+    let mut plan = runtime
+        .block_on(DeVectorScan::new(&table, Some(&filter), None, None).plan())
+        .unwrap();
+    plan.index_entries
+        .retain(|entry| entry.index_file.index_type == IVF_FLAT_IDENTIFIER);
+    assert!(tokio::runtime::Handle::try_current().is_err());
+    for factor in [1, 10] {
+        let reader = DeVectorRead::new(
+            "embedding",
+            &[&[1.0, 0.0], &[0.0, 1.0]],
+            1,
+            &HashMap::from([
+                (
+                    "vector-index.post-filter.candidates-factor".into(),
+                    factor.to_string(),
+                ),
+                ("refine_factor".into(), "2".into()),
+            ]),
+        )
+        .unwrap();
+        let executor = WireSearchExecutor {
+            table: table.clone(),
+            kinds: std::sync::Mutex::new(Vec::new()),
+            fail: false,
+        };
+        for scheduled in [false, true] {
+            let results = 
futures::executor::block_on(reader.read_with_executor(
+                plan.clone(),
+                scheduled.then_some(&executor as &dyn SearchTaskExecutor),
+            ))
+            .unwrap_or_else(|error| panic!("factor={factor}, 
scheduled={scheduled}: {error}"));
+            assert_eq!(results[0].row_ids().unwrap().row_ids, vec![2]);
+            assert_eq!(results[1].row_ids().unwrap().row_ids, vec![1]);
+        }
+    }
+    let single = DeVectorRead::new("embedding", &[&[1.0, 0.0]], 1, 
&HashMap::new()).unwrap();
+    let results = futures::executor::block_on(single.read(plan)).unwrap();
+    assert_eq!(results[0].row_ids().unwrap().row_ids, vec![2]);
+}
+
 #[tokio::test]
 async fn scheduled_batch_vector_matches_local_filter_refine_and_pinned_plan() {
     let table = de_vector_table().await;
@@ -1862,6 +1949,77 @@ struct CandidateSearchExecutor {
     index_ordinal: std::sync::atomic::AtomicUsize,
     index_batch_sizes: std::sync::Mutex<Vec<usize>>,
 }
+
+struct MissingNearestExecutor {
+    table: Table,
+}
+
+#[async_trait::async_trait]
+impl crate::table::SearchTaskExecutor for MissingNearestExecutor {
+    async fn execute(
+        &self,
+        tasks: Vec<crate::table::SearchTask>,
+    ) -> crate::Result<Vec<crate::table::SearchTaskResult>> {
+        let mut results = Vec::new();
+        for task in tasks {
+            let wire: serde_json::Value = 
serde_json::from_slice(&task.serialize()?).unwrap();
+            if wire["kind"] == "vector-index-filtered" {
+                // A valid approximate answer can miss the nearest matching 
row.
+                let payload = serde_json::to_value(VectorTaskScores::capture(
+                    vec![ScoredRowIds::new(vec![1], vec![l2_score(2.0)])],
+                    Some(RawVectorMetric::L2),
+                ))
+                .unwrap();
+                let result =
+                    serde_json::json!({"version": 1, "id": wire["id"], 
"payload": payload});
+                results.push(crate::table::SearchTaskResult::deserialize(
+                    &serde_json::to_vec(&result).unwrap(),
+                )?);
+            } else {
+                results.push(task.execute(&self.table).await?);
+            }
+        }
+        Ok(results)
+    }
+}
+
+#[tokio::test]
+async fn explicit_overlapping_raw_source_recovers_an_ann_miss() {
+    let table =
+        
crate::table::vector_search_test_utils::de_vector_table_with_metric(Some("l2")).await;
+    let mut builder = table.new_vector_search_builder();
+    builder
+        .with_vector_column("embedding")
+        .with_query_vector(vec![1.0, 0.0])
+        .with_limit(1)
+        .with_filter(id_gt_filter(&table, 0));
+    let plan = builder.new_scan().unwrap().plan().await.unwrap();
+    let mut sources = plan.splits().to_vec();
+    for source in &mut sources {
+        if let crate::table::SearchScanSplit::Index {
+            scalar_index_files, ..
+        } = source
+        {
+            scalar_index_files.clear();
+        }
+    }
+    sources.push(crate::table::SearchScanSplit::Raw {
+        row_ranges: vec![RowRange::new(0, 0)],
+        scalar_index_files: vec![],
+        index_type: Some("ivf-flat".into()),
+    });
+    let plan = crate::table::VectorScanPlan::new(plan.snapshot().cloned(), 
sources).unwrap();
+    let wire = serde_json::to_value(&plan).unwrap();
+    let plan = serde_json::from_value(wire).unwrap();
+    let result = builder
+        .new_read()
+        .unwrap()
+        .read_with_executor(plan, &MissingNearestExecutor { table })
+        .await
+        .unwrap();
+    assert_eq!(result.row_ids().unwrap().row_ids, vec![0]);
+}
+
 #[async_trait::async_trait]
 impl crate::table::SearchTaskExecutor for CandidateSearchExecutor {
     async fn execute(
diff --git a/crates/paimon/src/table/de_vector_scan.rs 
b/crates/paimon/src/table/de_vector_scan.rs
index b9d48b04..2e039bd7 100644
--- a/crates/paimon/src/table/de_vector_scan.rs
+++ b/crates/paimon/src/table/de_vector_scan.rs
@@ -54,6 +54,75 @@ fn same_vector_search_table(left: &Table, right: &Table) -> 
bool {
 }
 
 impl Table {
+    /// Pin and reuse a scalar index answer when it is exact and covers every
+    /// snapshot row. Returns `None` for unsupported or partially covered
+    /// predicates without reading scalar data files.
+    pub async fn try_prepare_indexed_vector_search_filter(
+        &self,
+        filter: Predicate,
+    ) -> crate::Result<Option<PreparedVectorSearchFilter>> {
+        let core = CoreOptions::new(self.schema().options());
+        core.ensure_read_authorized()?;
+        if !core.data_evolution_enabled() {
+            return Ok(None);
+        }
+        let plan = DeVectorScan::new(self, Some(&filter), None, None)
+            .plan()
+            .await?;
+        if plan.skip_search {
+            return Ok(Some(PreparedVectorSearchFilter {
+                table: plan.table.copy_with_pinned_snapshot(None),
+                include_row_ids: Arc::new(RoaringTreemap::new()),
+            }));
+        }
+        let Some(next_row_id) = plan.next_row_id.filter(|id| *id > 0) else {
+            return Ok(None);
+        };
+        let table = &plan.table;
+        let evaluation = super::de_vector_read::VectorSearchEvaluation {
+            table: Some(table),
+            file_io: table.file_io(),
+            table_path: table.location(),
+            table_options: table.schema().options(),
+            schema_fields: table.schema().fields(),
+            next_row_id: Some(next_row_id),
+            filter: Some(&filter),
+        };
+        let mut leaves = Vec::new();
+        crate::arrow::residual::collect_predicate_leaf_refs(&filter, &mut 
leaves);
+        let field_ids = leaves
+            .into_iter()
+            .filter_map(|(column, _)| 
super::find_field_id_by_name(table.schema().fields(), column))
+            .collect();
+        if !super::de_vector_read::scalar_coverage_gaps(
+            evaluation,
+            &plan.index_entries,
+            &field_ids,
+            crate::spec::GlobalIndexSearchMode::Full,
+            &[],
+        )
+        .is_empty()
+        {
+            return Ok(None);
+        }
+        let Some(scanner) =
+            super::de_vector_read::scalar_filter_scanner(evaluation, 
&plan.index_entries)?
+        else {
+            return Ok(None);
+        };
+        let Some(ranges) = scanner
+            .matching_exact_ranges(&filter, &[super::RowRange::new(0, 
next_row_id - 1)])
+            .await?
+        else {
+            return Ok(None);
+        };
+        let include_row_ids = super::de_vector_read::scalar_row_ids(&ranges)?;
+        Ok(Some(PreparedVectorSearchFilter {
+            table: plan.table,
+            include_row_ids: Arc::new(include_row_ids),
+        }))
+    }
+
     /// Resolve a scalar predicate once and pin all later vector-search/read
     /// stages to the same snapshot.
     pub async fn prepare_vector_search_filter(
diff --git a/crates/paimon/src/table/de_vector_scan/tests.rs 
b/crates/paimon/src/table/de_vector_scan/tests.rs
index 5f5cbf9d..b56f060b 100644
--- a/crates/paimon/src/table/de_vector_scan/tests.rs
+++ b/crates/paimon/src/table/de_vector_scan/tests.rs
@@ -22,6 +22,7 @@ use crate::table::vector_read::Read;
 use crate::table::vector_search_test_utils::{
     de_vector_table, id_gt_filter, vector_test_table, vector_test_table_at,
 };
+use crate::table::RowRange;
 use crate::table::{TableCommit, TableWrite};
 use crate::vector_search::GlobalIndexResult;
 use arrow_array::builder::{Float32Builder, ListBuilder};
@@ -43,6 +44,11 @@ async fn 
prepared_empty_filter_keeps_its_read_table_empty_after_commit() {
         .prepare_vector_search_filter(id_gt_filter(&table, 0))
         .await
         .unwrap();
+    let indexed_prepared = table
+        .try_prepare_indexed_vector_search_filter(id_gt_filter(&table, 0))
+        .await
+        .unwrap()
+        .unwrap();
     let field = Arc::new(ArrowField::new("element", ArrowDataType::Float32, 
true));
     let mut vectors = 
ListBuilder::new(Float32Builder::new()).with_field(field.clone());
     vectors.values().append_value(1.0);
@@ -67,31 +73,33 @@ async fn 
prepared_empty_filter_keeps_its_read_table_empty_after_commit() {
         .unwrap();
 
     assert!(table.resolve_read_snapshot().await.unwrap().is_some());
-    assert!(prepared
-        .table()
-        .resolve_read_snapshot()
-        .await
-        .unwrap()
-        .is_none());
-    assert!(prepared
-        .table()
-        .new_read_builder()
-        .new_scan()
-        .plan()
-        .await
-        .unwrap()
-        .splits()
-        .is_empty());
-    assert!(prepared
-        .table()
-        .new_vector_search_builder()
-        .with_vector_column("embedding")
-        .with_query_vector(vec![1.0, 0.0])
-        .with_limit(2)
-        .execute()
-        .await
-        .unwrap()
-        .is_empty());
+    for prepared in [prepared, indexed_prepared] {
+        assert!(prepared
+            .table()
+            .resolve_read_snapshot()
+            .await
+            .unwrap()
+            .is_none());
+        assert!(prepared
+            .table()
+            .new_read_builder()
+            .new_scan()
+            .plan()
+            .await
+            .unwrap()
+            .splits()
+            .is_empty());
+        assert!(prepared
+            .table()
+            .new_vector_search_builder()
+            .with_vector_column("embedding")
+            .with_query_vector(vec![1.0, 0.0])
+            .with_limit(2)
+            .execute()
+            .await
+            .unwrap()
+            .is_empty());
+    }
     assert!(!table
         .new_vector_search_builder()
         .with_vector_column("embedding")
@@ -436,7 +444,7 @@ async fn 
de_scalar_filter_applies_to_unindexed_raw_fallback() {
 }
 
 #[tokio::test]
-async fn 
unevaluable_scalar_filter_routes_covered_ranges_to_raw_in_every_mode() {
+async fn unevaluable_scalar_filter_preserves_ann_hits_in_every_mode() {
     let table = de_vector_table().await;
     for mode in ["fast", "full", "detail"] {
         let table = table.copy_with_options(HashMap::from([(
@@ -449,7 +457,8 @@ async fn 
unevaluable_scalar_filter_routes_covered_ranges_to_raw_in_every_mode()
             .await
             .unwrap();
         // Keep the committed IVF shards but remove the scalar index from this
-        // plan. A data-derived ANN allow-list can lose hits with nprobe=1.
+        // plan. With nprobe=1 the ANN may legitimately return fewer than K;
+        // post-filtering an all-matching predicate must preserve those hits.
         plan.index_entries
             .retain(|entry| entry.index_file.index_type == "ivf-flat");
         let read = DeVectorRead::new(
@@ -459,15 +468,316 @@ async fn 
unevaluable_scalar_filter_routes_covered_ranges_to_raw_in_every_mode()
             &HashMap::from([("ivf.nprobe".to_string(), "1".to_string())]),
         )
         .unwrap();
+        let mut unfiltered = plan.clone();
+        unfiltered.filter = None;
+        let expected = read.read(unfiltered).await.unwrap();
         let results = read.read(plan).await.unwrap();
-        for result in results {
+        for (result, expected) in results.into_iter().zip(expected) {
             let mut ids = result.row_ids().unwrap().row_ids.clone();
             ids.sort_unstable();
-            assert_eq!(ids, vec![0, 1, 2], "{mode}");
+            let mut expected = expected.row_ids().unwrap().row_ids.clone();
+            expected.sort_unstable();
+            assert_eq!(ids, expected, "{mode}");
         }
     }
 }
 
+/// Two physical data files, one vector shard, and no scalar index. Keeping the
+/// files separate lets a missing unrelated file expose accidental full scans.
+async fn post_filter_table(shard_size: usize) -> (Table, Vec<String>) {
+    let table =
+        
vector_test_table_at("memory:/post_vector_filter").copy_with_options(HashMap::from([
+            ("row-tracking.enabled".into(), "true".into()),
+            ("data-evolution.enabled".into(), "true".into()),
+            (
+                "global-index.row-count-per-shard".into(),
+                shard_size.to_string(),
+            ),
+            ("ivf-flat.dimension".into(), "2".into()),
+            ("ivf-flat.nlist".into(), "1".into()),
+            ("ivf-flat.metric".into(), "l2".into()),
+        ]));
+    let mut tail_files = Vec::new();
+    for start in [0, 64] {
+        let field = Arc::new(ArrowField::new("element", 
ArrowDataType::Float32, true));
+        let mut vectors = 
ListBuilder::new(Float32Builder::new()).with_field(field.clone());
+        for id in start..start + 64 {
+            vectors.values().append_value(id as f32);
+            vectors.values().append_value(0.0);
+            vectors.append(true);
+        }
+        let batch = RecordBatch::try_new(
+            Arc::new(ArrowSchema::new(vec![
+                ArrowField::new("id", ArrowDataType::Int32, false),
+                ArrowField::new("embedding", ArrowDataType::List(field), true),
+            ])),
+            vec![
+                Arc::new(Int32Array::from_iter_values(start..start + 64)),
+                Arc::new(vectors.finish()),
+            ],
+        )
+        .unwrap();
+        let mut writer = TableWrite::new(&table, "test".into()).unwrap();
+        writer.write_arrow_batch(&batch).await.unwrap();
+        let messages = writer.prepare_commit().await.unwrap();
+        if start == 64 {
+            tail_files.extend(
+                messages
+                    .iter()
+                    .flat_map(|m| &m.new_files)
+                    .map(|file| file.data_file_path(&format!("{}/bucket-0", 
table.location()))),
+            );
+        }
+        TableCommit::new(table.clone(), "test".into())
+            .commit(messages)
+            .await
+            .unwrap();
+    }
+    table
+        .new_global_index_build_builder()
+        .with_index_type("ivf-flat")
+        .with_index_column("embedding")
+        .execute()
+        .await
+        .unwrap();
+    assert!(!tail_files.is_empty());
+    (table, tail_files)
+}
+
+#[tokio::test]
+async fn post_filter_does_not_scan_unrelated_scalar_data() {
+    let (table, tail_files) = post_filter_table(128).await;
+    for path in tail_files {
+        table.file_io().delete_file(&path).await.unwrap();
+    }
+    let filter = crate::spec::PredicateBuilder::new(table.schema().fields())
+        .less_than("id", crate::spec::Datum::Int(100))
+        .unwrap();
+    for mode in ["fast", "full", "detail"] {
+        let table = table.copy_with_options(HashMap::from([
+            ("vector-index.search-mode".into(), mode.into()),
+            ("scalar-index.search-mode".into(), "full".into()),
+        ]));
+        let result = table
+            .new_vector_search_builder()
+            .with_vector_column("embedding")
+            .with_query_vector(vec![0.0, 0.0])
+            .with_limit(2)
+            .with_filter(filter.clone())
+            .execute()
+            .await
+            .unwrap();
+        assert_eq!(result.row_ids().unwrap().row_ids, vec![0, 1], "{mode}");
+    }
+    // The old central pre-filter would have to open the missing second file.
+    assert!(table
+        .try_prepare_indexed_vector_search_filter(filter.clone())
+        .await
+        .unwrap()
+        .is_none());
+    assert!(table.prepare_vector_search_filter(filter).await.is_err());
+}
+
+#[tokio::test]
+async fn indexed_filter_preparation_uses_only_complete_exact_index_answers() {
+    let (table, tail_files) = post_filter_table(128).await;
+    table
+        .new_global_index_build_builder()
+        .with_index_type("btree")
+        .with_index_column("id")
+        .execute()
+        .await
+        .unwrap();
+    for path in tail_files {
+        table.file_io().delete_file(&path).await.unwrap();
+    }
+    // A full scalar-data read would fail on the missing tail file.
+    let filter = id_gt_filter(&table, 90);
+    let prepared = table
+        .try_prepare_indexed_vector_search_filter(filter.clone())
+        .await
+        .unwrap()
+        .unwrap();
+    assert_eq!(
+        prepared.include_row_ids().iter().collect::<Vec<_>>(),
+        (91..128).collect::<Vec<_>>()
+    );
+    let predicates = 
crate::spec::PredicateBuilder::new(table.schema().fields());
+    let partial = Predicate::and(vec![
+        filter.clone(),
+        predicates.is_not_null("embedding").unwrap(),
+    ]);
+    assert!(table
+        .try_prepare_indexed_vector_search_filter(partial)
+        .await
+        .unwrap()
+        .is_none());
+    let table = table.copy_with_options(HashMap::from([(
+        "btree-index.fallback-scan-max-size".into(),
+        "0".into(),
+    )]));
+    assert!(table
+        .try_prepare_indexed_vector_search_filter(filter)
+        .await
+        .unwrap()
+        .is_none());
+}
+
+#[tokio::test]
+async fn post_filter_returns_short_results_without_retry_or_raw_scoring() {
+    let (table, _) = post_filter_table(128).await;
+    for mode in ["fast", "full", "detail"] {
+        for factor in ["2", "64"] {
+            let table = table.copy_with_options(HashMap::from([
+                ("vector-index.search-mode".into(), mode.into()),
+                ("scalar-index.search-mode".into(), "full".into()),
+            ]));
+            let results = table
+                .new_batch_vector_search_builder()
+                .with_vector_column("embedding")
+                .with_query_vectors(vec![vec![0.0, 0.0], vec![127.0, 0.0]])
+                .with_limit(2)
+                .with_filter(id_gt_filter(&table, 90))
+                .with_options(HashMap::from([(
+                    "vector-index.post-filter.candidates-factor".into(),
+                    factor.into(),
+                )]))
+                .execute()
+                .await
+                .unwrap();
+            assert_eq!(
+                results[0].row_ids().unwrap().row_ids,
+                if factor == "2" { vec![] } else { vec![91, 92] },
+                "{mode} {factor}"
+            );
+            assert_eq!(
+                results[1].row_ids().unwrap().row_ids,
+                vec![127, 126],
+                "{mode} {factor}"
+            );
+        }
+    }
+}
+
+#[tokio::test]
+async fn post_filter_with_an_unindexed_or_arm_avoids_duplicate_raw_scan() {
+    let (table, tail_files) = post_filter_table(128).await;
+    table
+        .new_global_index_build_builder()
+        .with_index_type("btree")
+        .with_index_column("id")
+        .execute()
+        .await
+        .unwrap();
+    for path in tail_files {
+        table.file_io().delete_file(&path).await.unwrap();
+    }
+    let predicates = 
crate::spec::PredicateBuilder::new(table.schema().fields());
+    let filter = crate::spec::Predicate::or(vec![
+        predicates
+            .less_than("id", crate::spec::Datum::Int(0))
+            .unwrap(),
+        predicates.is_not_null("embedding").unwrap(),
+    ]);
+    for scalar_mode in ["full", "detail"] {
+        let table = table.copy_with_options(HashMap::from([(
+            "scalar-index.search-mode".into(),
+            scalar_mode.into(),
+        )]));
+        let mut builder = table.new_vector_search_builder();
+        builder
+            .with_vector_column("embedding")
+            .with_query_vector(vec![0.0, 0.0])
+            .with_limit(2)
+            .with_filter(filter.clone());
+        let plan = builder.new_scan().unwrap().plan().await.unwrap();
+        let wire = serde_json::to_value(&plan).unwrap();
+        assert!(
+            !plan
+                .splits()
+                .iter()
+                .any(|split| matches!(split, 
crate::table::SearchScanSplit::Raw { .. })),
+            "an unevaluable OR must not create scalar-gap Raw sources"
+        );
+        let plan = serde_json::from_value(wire).unwrap();
+        let result = builder.new_read().unwrap().read(plan).await.unwrap();
+        assert_eq!(result.row_ids().unwrap().row_ids, vec![0, 1]);
+    }
+}
+
+#[tokio::test]
+async fn post_filter_large_batch_reuses_the_reader_across_candidate_chunks() {
+    let (table, _) = post_filter_table(128).await;
+    let queries = (0..8193)
+        .map(|i| vec![if i % 2 == 0 { 0.0 } else { 127.0 }, 0.0])
+        .collect();
+    // C=128 puts 8192 queries in the first candidate chunk and one in the
+    // second. Reopening the stream instead of retaining the reader is an 
error.
+    let results = table
+        .new_batch_vector_search_builder()
+        .with_vector_column("embedding")
+        .with_query_vectors(queries)
+        .with_limit(1)
+        .with_filter(id_gt_filter(&table, 90))
+        .with_options(HashMap::from([(
+            "vector-index.post-filter.candidates-factor".into(),
+            "128".into(),
+        )]))
+        .execute()
+        .await
+        .unwrap();
+    assert_eq!(results.len(), 8193);
+    for (i, result) in results.into_iter().enumerate() {
+        assert_eq!(
+            result.row_ids().unwrap().row_ids,
+            vec![if i % 2 == 0 { 91 } else { 127 }]
+        );
+    }
+}
+
+#[tokio::test]
+async fn post_filter_preserves_shard_offsets_and_input_allow_lists() {
+    let (table, _) = post_filter_table(64).await;
+    let filter = id_gt_filter(&table, 105);
+    let include = Arc::new(RoaringTreemap::from_iter(99..=110));
+    for factor in ["2", "32"] {
+        let plan = DeVectorScan::new(&table, Some(&filter), Some(&include), 
None)
+            .plan()
+            .await
+            .unwrap();
+        assert!(plan.index_entries.iter().any(|entry| entry
+            .index_file
+            .global_index_meta
+            .as_ref()
+            .is_some_and(|meta| meta.row_range_start == 64)));
+        let reader = DeVectorRead::new(
+            "embedding",
+            &[&[0.0, 0.0], &[127.0, 0.0]],
+            2,
+            &HashMap::from([(
+                "vector-index.post-filter.candidates-factor".into(),
+                factor.into(),
+            )]),
+        )
+        .unwrap();
+        let results = reader.read(plan).await.unwrap();
+        assert_eq!(
+            results[0].row_ids().unwrap().row_ids,
+            if factor == "2" {
+                vec![]
+            } else {
+                vec![106, 107]
+            },
+            "{factor}"
+        );
+        assert_eq!(
+            results[1].row_ids().unwrap().row_ids,
+            vec![110, 109],
+            "{factor}"
+        );
+    }
+}
+
 #[tokio::test]
 async fn exact_and_partial_scalar_indexes_obey_refinement_switch() {
     let table = de_vector_table().await;
@@ -589,58 +899,124 @@ async fn 
scalar_coverage_gaps_follow_scalar_and_vector_modes() {
                 .await
                 .unwrap();
         }
-        let filter = id_gt_filter(&table, 3);
-        for scalar_mode in ["fast", "full", "detail"] {
-            for vector_mode in ["fast", "full", "detail"] {
-                for builder_options in [false, true] {
-                    let modes = HashMap::from([
-                        (
-                            "vector-index.search-mode".to_string(),
-                            vector_mode.to_string(),
-                        ),
-                        (
-                            "scalar-index.search-mode".to_string(),
-                            scalar_mode.to_string(),
-                        ),
-                    ]);
-                    let mut table_options = if builder_options {
-                        HashMap::from([
-                            ("vector-index.search-mode".to_string(), 
"fast".to_string()),
-                            ("scalar-index.search-mode".to_string(), 
"fast".to_string()),
-                        ])
-                    } else {
-                        modes.clone()
-                    };
-                    table_options.insert(
-                        "global-index.filter.refine-from-data".to_string(),
-                        "false".to_string(),
-                    );
-                    let table = table.copy_with_options(table_options);
-                    let mut builder = table.new_batch_vector_search_builder();
-                    builder
-                        .with_vector_column("embedding")
-                        .with_query_vectors(vec![vec![0.0, 0.0], vec![1.0, 
0.0]])
-                        .with_limit(10)
-                        .with_filter(filter.clone());
-                    if builder_options {
-                        builder.with_options(modes);
-                    }
-                    let expected = if (vector_covers_tail && scalar_mode != 
"fast")
-                        || (!vector_covers_tail && vector_mode != "fast")
-                    {
-                        vec![3]
-                    } else {
-                        vec![]
-                    };
-                    let results = builder.execute().await.unwrap();
-                    assert_eq!(results.len(), 2);
-                    for result in results {
-                        assert_eq!(result.row_ids().unwrap().row_ids, expected,
-                            "scalar={scalar_mode}, vector={vector_mode}, 
vector_covers_tail={vector_covers_tail}, builder_options={builder_options}");
+        let predicate = 
crate::spec::PredicateBuilder::new(table.schema().fields());
+        // No covered row matches these predicates. Empty scalar results must
+        // still recover the tail, including an AND with an unsupported arm.
+        let exact = id_gt_filter(&table, 3);
+        assert!(table
+            .try_prepare_indexed_vector_search_filter(exact.clone())
+            .await
+            .unwrap()
+            .is_none());
+        let filters = [
+            exact.clone(),
+            Predicate::and(vec![
+                exact.clone(),
+                predicate.is_not_null("embedding").unwrap(),
+            ]),
+            Predicate::or(vec![exact, 
predicate.is_null("embedding").unwrap()]),
+        ];
+        for (filter_index, filter) in filters.into_iter().enumerate() {
+            for scalar_mode in ["fast", "full", "detail"] {
+                for vector_mode in ["fast", "full", "detail"] {
+                    for builder_options in [false, true] {
+                        let modes = HashMap::from([
+                            (
+                                "vector-index.search-mode".to_string(),
+                                vector_mode.to_string(),
+                            ),
+                            (
+                                "scalar-index.search-mode".to_string(),
+                                scalar_mode.to_string(),
+                            ),
+                        ]);
+                        let mut table_options = if builder_options {
+                            HashMap::from([
+                                ("vector-index.search-mode".to_string(), 
"fast".to_string()),
+                                ("scalar-index.search-mode".to_string(), 
"fast".to_string()),
+                            ])
+                        } else {
+                            modes.clone()
+                        };
+                        table_options.insert(
+                            "global-index.filter.refine-from-data".to_string(),
+                            "false".to_string(),
+                        );
+                        let table = table.copy_with_options(table_options);
+                        let mut builder = 
table.new_batch_vector_search_builder();
+                        builder
+                            .with_vector_column("embedding")
+                            .with_query_vectors(vec![vec![0.0, 0.0], vec![1.0, 
0.0]])
+                            .with_limit(10)
+                            .with_filter(filter.clone());
+                        if builder_options {
+                            builder.with_options(modes);
+                        }
+                        let post_filter = filter_index == 2;
+                        let expected = if (vector_covers_tail
+                            && (post_filter || scalar_mode != "fast"))
+                            || (!vector_covers_tail && vector_mode != "fast")
+                        {
+                            vec![3]
+                        } else {
+                            vec![]
+                        };
+                        let plan = 
builder.new_scan().unwrap().plan().await.unwrap();
+                        let raw_ranges: Vec<_> = plan
+                            .splits()
+                            .iter()
+                            .filter_map(|split| {
+                                if let crate::table::SearchScanSplit::Raw { 
row_ranges, .. } = split
+                                {
+                                    Some(row_ranges.as_slice())
+                                } else {
+                                    None
+                                }
+                            })
+                            .flatten()
+                            .cloned()
+                            .collect();
+                        let expect_raw = (!vector_covers_tail && vector_mode 
!= "fast")
+                            || (vector_covers_tail && !post_filter && 
scalar_mode != "fast");
+                        assert_eq!(raw_ranges, if expect_raw { 
vec![RowRange::new(3, 3)] } else { vec![] },
+                        "scalar={scalar_mode}, vector={vector_mode}, 
vector_covers_tail={vector_covers_tail}, filter={filter_index}, 
builder_options={builder_options}");
+                        let results = 
builder.new_read().unwrap().read(plan).await.unwrap();
+                        assert_eq!(results.len(), 2);
+                        for result in results {
+                            assert_eq!(result.row_ids().unwrap().row_ids, 
expected,
+                            "scalar={scalar_mode}, vector={vector_mode}, 
vector_covers_tail={vector_covers_tail}, filter={filter_index}, 
builder_options={builder_options}");
+                        }
                     }
                 }
             }
         }
+        if vector_covers_tail {
+            // Metadata alone reports a partial BTree. This range lookup is
+            // declined by its scan budget, so it must use post-filtering.
+            for scalar_mode in ["full", "detail"] {
+                let table = table.copy_with_options(HashMap::from([
+                    ("scalar-index.search-mode".into(), scalar_mode.into()),
+                    ("btree-index.fallback-scan-max-size".into(), "0".into()),
+                    (
+                        "vector-index.post-filter.candidates-factor".into(),
+                        "1".into(),
+                    ),
+                ]));
+                let mut builder = table.new_vector_search_builder();
+                builder
+                    .with_vector_column("embedding")
+                    .with_query_vector(vec![1.0, -2.0])
+                    .with_limit(1)
+                    .with_filter(id_gt_filter(&table, 1));
+                let plan = builder.new_scan().unwrap().plan().await.unwrap();
+                assert!(!plan
+                    .splits()
+                    .iter()
+                    .any(|split| matches!(split, 
crate::table::SearchScanSplit::Raw { .. })));
+                let result = 
builder.new_read().unwrap().read(plan).await.unwrap();
+                assert!(result.row_ids().unwrap().row_ids.iter().all(|id| *id 
> 0));
+            }
+        }
     }
 }
 
diff --git a/crates/paimon/src/table/global_index_scanner.rs 
b/crates/paimon/src/table/global_index_scanner.rs
index 63f3e742..6281d8e0 100644
--- a/crates/paimon/src/table/global_index_scanner.rs
+++ b/crates/paimon/src/table/global_index_scanner.rs
@@ -33,9 +33,9 @@ mod row_ranges;
 pub(crate) use deletion_vectors::deleted_row_ranges_for_data_evolution_dvs;
 use entry::{validate_fm_file_sets, GlobalIndexEntry, GlobalIndexEntryMeta, 
GlobalIndexFileKind};
 pub(super) use row_ranges::intersect_sorted_ranges;
-use row_ranges::unindexed_ranges_for_indexed_coverage;
 pub(crate) use row_ranges::{
-    search_limit_with_deleted_rows, unindexed_ranges_for_global_index_entries, 
RowRangeIndex,
+    search_limit_with_deleted_rows, unindexed_ranges_for_global_index_entries,
+    unindexed_ranges_for_indexed_coverage, RowRangeIndex,
 };
 
 use super::global_index_types::{
@@ -551,6 +551,37 @@ impl GlobalIndexScanner {
         Ok(Some((result.row_ranges, exact, result.candidate_ranges)))
     }
 
+    /// Coverage of indexes which actually contributed to this evaluation.
+    pub(super) async fn matching_indexed_coverage(
+        &self,
+        predicate: &Predicate,
+    ) -> Result<Option<Vec<RowRange>>> {
+        Ok(self
+            .evaluate(predicate)
+            .await?
+            .map(|result| result.indexed_coverage))
+    }
+
+    /// An exact reusable answer must also cover every row the caller can read.
+    pub(super) async fn matching_exact_ranges(
+        &self,
+        predicate: &Predicate,
+        required_coverage: &[RowRange],
+    ) -> Result<Option<Vec<RowRange>>> {
+        let Some(result) = self.evaluate(predicate).await? else {
+            return Ok(None);
+        };
+        if !result.fully_evaluated
+            || !self.is_exact_predicate(predicate, &result.evaluated_field_ids)
+            || !result.candidate_ranges.is_empty()
+            || !super::source::exclude_row_ranges(required_coverage, 
&result.indexed_coverage)
+                .is_empty()
+        {
+            return Ok(None);
+        }
+        Ok(Some(result.row_ranges))
+    }
+
     fn is_exact_predicate(
         &self,
         predicate: &Predicate,
diff --git a/crates/paimon/src/table/global_index_scanner/row_ranges.rs 
b/crates/paimon/src/table/global_index_scanner/row_ranges.rs
index 3c4c7f12..b88d6ebf 100644
--- a/crates/paimon/src/table/global_index_scanner/row_ranges.rs
+++ b/crates/paimon/src/table/global_index_scanner/row_ranges.rs
@@ -112,7 +112,7 @@ pub(super) fn unindexed_ranges_for_coverage(
     source::exclude_row_ranges(&data_ranges, &indexed_ranges)
 }
 
-pub(super) fn unindexed_ranges_for_indexed_coverage(
+pub(crate) fn unindexed_ranges_for_indexed_coverage(
     indexed_ranges: &[RowRange],
     search_mode: GlobalIndexSearchMode,
     next_row_id: Option<i64>,
diff --git a/crates/paimon/src/table/search_scan_split.rs 
b/crates/paimon/src/table/search_scan_split.rs
index 26f1befc..29b2f2ab 100644
--- a/crates/paimon/src/table/search_scan_split.rs
+++ b/crates/paimon/src/table/search_scan_split.rs
@@ -188,7 +188,8 @@ pub(super) async fn global_search_splits(
                 filter,
                 scalar_mode,
                 &detail_ranges,
-            );
+            )
+            .await?;
             if mode == GlobalIndexSearchMode::Fast {
                 let indexed = merge_row_ranges(
                     grouped
diff --git a/crates/paimon/src/table/search_task.rs 
b/crates/paimon/src/table/search_task.rs
index 977328e6..de4ae468 100644
--- a/crates/paimon/src/table/search_task.rs
+++ b/crates/paimon/src/table/search_task.rs
@@ -240,7 +240,7 @@ impl SearchTask {
             .copy_with_resolved_schema(self.schema.clone(), &self.branch)?
             .copy_with_pinned_snapshot(self.snapshot.as_ref());
         let payload = match self.kind.as_str() {
-            "vector-index" | "vector-rows" => {
+            "vector-index" | "vector-index-filtered" | "vector-rows" => {
                 super::de_vector_read::execute_search_task(&pinned, 
&self.kind, &self.payload)
                     .await?
             }
diff --git a/crates/paimon/src/table/vector_search_builder.rs 
b/crates/paimon/src/table/vector_search_builder.rs
index cd94a076..098c76ca 100644
--- a/crates/paimon/src/table/vector_search_builder.rs
+++ b/crates/paimon/src/table/vector_search_builder.rs
@@ -98,8 +98,13 @@ impl<'a> VectorSearchBuilder<'a> {
     /// refined against snapshot-pinned data when
     /// `global-index.filter.refine-from-data=true`; otherwise those candidates
     /// are excluded. If no scalar index can evaluate the predicate, indexed
-    /// ranges are scored from raw data even in FAST mode. Raw searches always
-    /// apply the row predicate before Top-K, matching Java.
+    /// searches retrieve ANN candidates once and check their scalar values
+    /// against the pinned data before the final Top-K. Candidate count is the
+    /// original Top-K times `vector-index.post-filter.candidates-factor`
+    /// (default 10), with at least the required reranking/deletion allowance.
+    /// Results may contain fewer than Top-K matches, including zero; there is
+    /// no retry or automatic raw scoring of indexed ranges. Approximate recall
+    /// is retained. Raw sources outside index coverage follow the search mode.
     pub fn with_filter(&mut self, filter: Predicate) -> &mut Self {
         add_filter(&mut self.config.write().unwrap().filter, filter);
         self
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 13fdac2f..265dc6cc 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -2865,8 +2865,7 @@ score. If no matching index is found, an empty result is 
returned.
 
 ### Scalar Pre-Filters
 
-Add a `WHERE` clause to restrict the rows considered by vector Top-K. The
-predicate is evaluated before the vector index selects its nearest neighbors:
+Add a `WHERE` clause to restrict the rows returned by vector Top-K:
 
 ```sql
 SELECT id, event_time
@@ -2879,11 +2878,28 @@ FROM vector_search(
 WHERE event_time >= TIMESTAMP '2026-08-01 00:00:00';
 ```
 
-On data-evolution tables, Paimon resolves the predicate to matching global row
-IDs using a snapshot-pinned table read. Scalar global indexes such as BTree can
-narrow this read. The matching global row IDs are intersected with each vector
-index shard and passed to the vector backend as its row filter, so an excluded
-nearest neighbor does not consume one of the requested Top-K positions.
+On data-evolution tables, exact scalar global-index answers are passed to each
+vector shard as a row-ID filter. When no scalar index can evaluate the
+predicate, each shard retrieves ANN candidates once and checks their scalar
+values against the same pinned snapshot before returning results. Batch queries
+share a candidate row-ID union for each filtering read.
+
+`vector-index.post-filter.candidates-factor` defaults to `10`. Each query's
+candidate count is `max(original Top-K * factor, required candidate limit)`,
+capped by shard size and the backend limit (`2147483647`). The required limit
+includes reranking/deletion slack; neither that slack nor batch size multiplies
+the factor. For example, Top-K 10 requests 100 candidates with the default
+factor unless a larger required allowance applies.
+
+Every returned row satisfies the predicate, but filtering may leave fewer than
+Top-K rows, including no rows even when matches exist outside the candidates.
+There is no retry or automatic raw scoring of indexed ranges to fill results.
+Increase the factor to check more candidates, at additional query and scalar
+read cost. Post-filtering retains ANN's approximate recall. Raw work outside
+vector-index coverage still follows `fast`, `full`, and `detail` search modes;
+explicitly supplied Raw sources retain their exact scoring.
+When a scalar index can evaluate the predicate but covers only part of the row
+range, scalar `full` and `detail` modes still plan Raw work for its coverage 
gaps.
 
 Only predicates that can be translated completely to Paimon predicates are
 pushed into vector search. DataFusion keeps its residual filter for ordinary
@@ -3980,6 +3996,7 @@ optimization may be disabled. Full-text builds reject 
deletion-vector tables.
 | `btree-index.fallback-scan-max-size` | `256mb` | Maximum total size of BTree 
global-index files requiring fallback scans for range/between and 
suffix/contains/complex LIKE predicates; files proven to match completely by 
metadata need no scan and are excluded. `0` disables BTree fallback index 
scans. |
 | `bitmap-index.fallback-scan-max-size` | `256mb` | Maximum total size of 
selected bitmap global-index files for fallback scans used by range/between and 
suffix/contains/complex LIKE predicates; `0` disables bitmap fallback index 
scans. |
 | `global-index.search-mode` | `fast` | Global index coverage mode for reads: 
`fast`, `full`, or `detail`. |
+| `vector-index.post-filter.candidates-factor` | `10` | Multiplier of each 
query's original Top-K for one ANN query followed by exact scalar 
post-filtering. At least the required reranking/deletion allowance, capped by 
shard size and the backend limit. Positive integer no greater than 
`2147483647`. Short results are returned without retry. |
 | `global-index.thread-num` | `32` | Number of concurrent global-index search 
tasks; must be greater than 0 and must not exceed the runtime's task limit. 
This does not limit Vindex file range reads. |
 | `global-index.vindex.read-thread-num` | `64` | Maximum number of concurrent 
Vindex file range reads shared by one search operation; must be greater than 0 
and must not exceed the runtime semaphore limit. |
 | `global-index.column-update-action` | `THROW_ERROR` | What a commit does 
when it updates an indexed column: `THROW_ERROR` rejects the commit, 
`DROP_PARTITION_INDEX` drops the affected partition index instead. |

Reply via email to