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 df8c2974 [core] Choose centroid and IVF probe widths jointly (#1494)
df8c2974 is described below

commit df8c2974db1dd6388adb0e1104de6f57c3b30bfe
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 22 15:31:47 2026 +0800

    [core] Choose centroid and IVF probe widths jointly (#1494)
---
 crates/paimon/src/table/de_vector_read.rs          |  95 ++++--
 crates/paimon/src/table/de_vector_read/centroid.rs | 332 +++++++++++++++++++--
 .../table/de_vector_read/centroid_joint_tests.rs   | 284 ++++++++++++++++++
 crates/paimon/src/table/pk_vector_read/tests.rs    |  42 +--
 .../paimon/src/table/vector_search_test_utils.rs   |  36 ++-
 crates/paimon/src/vindex/reader.rs                 | 131 +++++---
 docs/src/sql.md                                    |   9 +
 7 files changed, 797 insertions(+), 132 deletions(-)

diff --git a/crates/paimon/src/table/de_vector_read.rs 
b/crates/paimon/src/table/de_vector_read.rs
index e5281d93..a0f42de5 100644
--- a/crates/paimon/src/table/de_vector_read.rs
+++ b/crates/paimon/src/table/de_vector_read.rs
@@ -324,6 +324,28 @@ async fn execute_vector_file_work(
     batch_index_parallelism: usize,
     allow_buffered_read: bool,
 ) -> crate::Result<(Vec<ScoredRowIds>, IndexSearchTiming)> {
+    let (hits, timing) = execute_vector_file_probes(
+        evaluation,
+        work,
+        metric_check,
+        range_read_limiter,
+        batch_index_parallelism,
+        vec![],
+        allow_buffered_read,
+    )
+    .await?;
+    Ok((hits.into_iter().map(|hits| hits.standard).collect(), timing))
+}
+
+async fn execute_vector_file_probes(
+    evaluation: VectorSearchEvaluation<'_>,
+    work: VectorIndexWork,
+    metric_check: VectorMetricCheck,
+    range_read_limiter: RangeReadLimiter,
+    batch_index_parallelism: usize,
+    probes: Vec<centroid::Probe>,
+    allow_buffered_read: bool,
+) -> crate::Result<(Vec<centroid::ProbeMatches<ScoredRowIds>>, 
IndexSearchTiming)> {
     let timing_enabled = vector_search_timing_enabled();
     let concurrency = 
CoreOptions::new(evaluation.table_options).global_index_thread_num()?;
     let global_meta = work
@@ -435,7 +457,7 @@ async fn execute_vector_file_work(
             .is_some_and(|row_ids| row_ids.is_empty())
     }) {
         return Ok((
-            vec![ScoredRowIds::empty(); vector_searches.len()],
+            vec![centroid::ProbeMatches::standard(ScoredRowIds::empty()); 
vector_searches.len()],
             IndexSearchTiming::default(),
         ));
     }
@@ -481,6 +503,7 @@ async fn execute_vector_file_work(
                     list_row_count,
                     metrics: metric_check,
                     post_filter,
+                    probes,
                 },
                 permit,
             )
@@ -510,6 +533,7 @@ async fn execute_vector_file_work(
                     list_row_count,
                     metrics: metric_check,
                     post_filter,
+                    probes,
                 },
                 permit,
             )
@@ -544,20 +568,26 @@ async fn execute_vector_file_work(
         });
     }
 
+    let convert = |result: centroid::NativeMatches| match result {
+        Some(scored_map) => {
+            if max_centroid_label
+                .is_some_and(|max_label| scored_map.keys().any(|&id| id > 
max_label))
+            {
+                return Err(super::centroid_index::invalid(format!(
+                    "Vector candidate in '{file_name}' lies outside its 
centroid shard"
+                )));
+            }
+            
Ok(ScoredRowIds::from_scored_map(scored_map).offset(row_range_start))
+        }
+        None => Ok(ScoredRowIds::empty()),
+    };
     let results = results
         .into_iter()
-        .map(|result| match result {
-            Some(scored_map) => {
-                if max_centroid_label
-                    .is_some_and(|max_label| scored_map.keys().any(|&id| id > 
max_label))
-                {
-                    return Err(super::centroid_index::invalid(format!(
-                        "Vector candidate in '{file_name}' lies outside its 
centroid shard"
-                    )));
-                }
-                
Ok(ScoredRowIds::from_scored_map(scored_map).offset(row_range_start))
-            }
-            None => Ok(ScoredRowIds::empty()),
+        .map(|hits| {
+            Ok(centroid::ProbeMatches {
+                standard: convert(hits.standard)?,
+                joint: hits.joint.map(&convert).transpose()?,
+            })
         })
         .collect::<crate::Result<Vec<_>>>()?;
     Ok::<_, crate::Error>((
@@ -583,7 +613,7 @@ async fn execute_vindex_searches<S: SeekRead + 'static, G: 
Send + 'static>(
     file_name: String,
     context: VectorIndexSearchContext,
     guard: G,
-) -> crate::Result<Vec<Option<HashMap<u64, f32>>>> {
+) -> crate::Result<Vec<centroid::ProbeMatches<centroid::NativeMatches>>> {
     if context.post_filter.is_some() {
         return execute_post_filter_vindex_searches(
             io_meta,
@@ -593,7 +623,12 @@ async fn execute_vindex_searches<S: SeekRead + 'static, G: 
Send + 'static>(
             context,
             guard,
         )
-        .await;
+        .await
+        .map(|hits| {
+            hits.into_iter()
+                .map(centroid::ProbeMatches::standard)
+                .collect()
+        });
     }
     let panic_context = if vector_searches.len() > 1 {
         "vindex global-index batch search task failed"
@@ -604,20 +639,21 @@ async fn execute_vindex_searches<S: SeekRead + 'static, 
G: Send + 'static>(
         let mut reader = VindexVectorGlobalIndexReader::new(io_meta, options)
             .with_batch_index_parallelism(context.parallelism)
             .with_list_row_count(context.list_row_count);
-        reader
-            .visit_batch_vector_search_validated(
-                &vector_searches,
-                |_| Ok(source),
-                |metadata| {
-                    context
-                        .metrics
-                        .check(RawVectorMetric::from_vindex(metadata.metric))
-                },
-            )
-            .map_err(|e| crate::Error::DataInvalid {
-                message: format!("Failed to read vindex index file '{}': {}", 
file_name, e),
-                source: Some(Box::new(e)),
-            })
+        centroid::search_file(
+            &mut reader,
+            &vector_searches,
+            &context.probes,
+            source,
+            |metadata| {
+                context
+                    .metrics
+                    .check(RawVectorMetric::from_vindex(metadata.metric))
+            },
+        )
+        .map_err(|e| crate::Error::DataInvalid {
+            message: format!("Failed to read vindex index file '{}': {}", 
file_name, e),
+            source: Some(Box::new(e)),
+        })
     })
     .await
 }
@@ -756,6 +792,7 @@ impl VectorMetricCheck {
 struct VectorIndexSearchContext {
     parallelism: usize,
     list_row_count: Option<u64>,
+    probes: Vec<centroid::Probe>,
     metrics: VectorMetricCheck,
     post_filter: Option<VectorIndexPostFilter>,
 }
diff --git a/crates/paimon/src/table/de_vector_read/centroid.rs 
b/crates/paimon/src/table/de_vector_read/centroid.rs
index 7a1bfa58..7a379751 100644
--- a/crates/paimon/src/table/de_vector_read/centroid.rs
+++ b/crates/paimon/src/table/de_vector_read/centroid.rs
@@ -16,17 +16,20 @@
 // under the License.
 
 use super::{
-    execute_vector_file_work, matching_row_ids_for_filter, post_filter,
+    execute_vector_file_probes, execute_vector_file_work, 
matching_row_ids_for_filter, post_filter,
     sorted_row_ids_to_row_ranges, IndexSearchTiming, RangeReadLimiter, 
RawVectorMetric,
     VectorIndexWork, VectorMetricCheck, VectorSearchEvaluation,
 };
 use crate::spec::{IndexManifestEntry, VectorIndexOptions};
 use crate::table::centroid_index::{self, Descriptor, Generation, Role, Router};
 use crate::vector_search::{ScoredRowIds, VectorSearch};
+use crate::vindex::reader::VindexVectorGlobalIndexReader;
 use crate::{Error, Result};
 use paimon_vindex_core::distance::MetricType;
+use paimon_vindex_core::index::VectorIndexMetadata;
+use paimon_vindex_core::io::SeekRead;
 use roaring::RoaringTreemap;
-use std::collections::{BTreeMap, HashMap};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
 
 type CentroidFiles<'a> = HashMap<&'a str, Vec<IndexManifestEntry>>;
 
@@ -51,12 +54,118 @@ pub(super) fn plan<'a>(
     Ok((plans, files))
 }
 
+const ROUTER_LISTS: usize = 64;
+const AUTOMATIC_WIDTH: usize = 8;
+const JOINT_OUTER_PROBES: usize = 4;
+const JOINT_INNER_PROBES: usize = 16;
+const SHARD_LISTS: usize = 64;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(super) enum Probe {
+    Standard,
+    Joint,
+    CheckLayout,
+}
+
+#[derive(Clone, Default)]
+pub(super) struct ProbeMatches<T> {
+    pub(super) standard: T,
+    // A legacy shard reports Some only when its native layout supports joint 
probing.
+    pub(super) joint: Option<T>,
+}
+
+impl<T> ProbeMatches<T> {
+    pub(super) fn standard(standard: T) -> Self {
+        Self {
+            standard,
+            joint: None,
+        }
+    }
+}
+
+pub(super) type NativeMatches = Option<HashMap<u64, f32>>;
+
+pub(super) fn search_file<S: SeekRead + 'static>(
+    reader: &mut VindexVectorGlobalIndexReader,
+    searches: &[VectorSearch],
+    probes: &[Probe],
+    source: S,
+    validate: impl FnOnce(&VectorIndexMetadata) -> Result<()>,
+) -> Result<Vec<ProbeMatches<NativeMatches>>> {
+    if probes.is_empty() {
+        return reader
+            .visit_batch_vector_search_validated(searches, |_| Ok(source), 
validate)
+            .map(|hits| 
hits.into_iter().map(ProbeMatches::standard).collect());
+    }
+
+    debug_assert_eq!(searches.len(), probes.len());
+    reader.load_validated(|_| Ok(source), validate)?;
+    let metadata = reader.metadata()?;
+    let compatible = metadata.nlist == SHARD_LISTS && metadata.metric == 
MetricType::L2;
+    let mut standard_queries = Vec::new();
+    let mut standard_indices = Vec::new();
+    let mut joint_queries = Vec::new();
+    let mut joint_indices = Vec::new();
+    for (index, (query, probe)) in searches.iter().zip(probes).enumerate() {
+        if *probe != Probe::Joint {
+            standard_queries.push(query);
+            standard_indices.push(index);
+        }
+        if *probe == Probe::Joint || (*probe == Probe::CheckLayout && 
compatible) {
+            joint_queries.push(query);
+            joint_indices.push(index);
+        }
+    }
+
+    let mut results = vec![ProbeMatches::default(); searches.len()];
+    if !standard_queries.is_empty() {
+        let hits = reader.search_loaded_batch(&standard_queries, None)?;
+        for (index, hits) in standard_indices.into_iter().zip(hits) {
+            results[index].standard = hits;
+        }
+    }
+    if joint_queries.is_empty() {
+        return Ok(results);
+    }
+
+    // Java retries an incomplete local joint probe at the ordinary width.
+    // A legacy probe has already computed those results for the other policy.
+    let joint_hits = reader.search_loaded_batch(&joint_queries, 
Some(JOINT_INNER_PROBES))?;
+    let mut retry = Vec::new();
+    for (index, hits) in joint_indices.into_iter().zip(joint_hits) {
+        if hits.as_ref().map_or(0, HashMap::len) < searches[index].limit {
+            if probes[index] == Probe::CheckLayout {
+                results[index].joint = Some(results[index].standard.clone());
+            } else {
+                retry.push(index);
+            }
+        } else {
+            results[index].joint = Some(hits);
+        }
+    }
+    if !retry.is_empty() {
+        let queries = retry
+            .iter()
+            .map(|&index| &searches[index])
+            .collect::<Vec<_>>();
+        for (index, hits) in retry
+            .into_iter()
+            .zip(reader.search_loaded_batch(&queries, None)?)
+        {
+            results[index].joint = Some(hits);
+        }
+    }
+    Ok(results)
+}
+
 struct Route {
     nearest: Vec<usize>,
     visited: usize,
     width: usize,
     limit: usize,
     hits: ScoredRowIds,
+    joint: bool,
+    legacy_joint_hits: ScoredRowIds,
 }
 
 pub(super) async fn execute_work(
@@ -156,6 +265,21 @@ pub(super) async fn execute_work(
         )));
     }
 
+    let joint_enabled = explicit_width.is_none()
+        && nlist == ROUTER_LISTS
+        && router.metric == MetricType::L2
+        && work.filter.is_none()
+        && matches!(
+            work.entry.index_file.index_type.as_str(),
+            "ivf-flat" | "ivf-pq"
+        )
+        && [
+            "ivf.nprobe",
+            "diskann.l_search",
+            "ivf.max_initial_filter_expansion_factor",
+        ]
+        .iter()
+        .all(|option| !configuration.options.contains_key(*option));
     let search = RoutedSearch {
         evaluation,
         group,
@@ -166,6 +290,7 @@ pub(super) async fn execute_work(
         range_read_limiter,
         batch_parallelism,
         allow_buffered_read,
+        joint_enabled,
     };
     let Some(predicate) = work.filter else {
         let mut timing = IndexSearchTiming::default();
@@ -231,6 +356,7 @@ struct RoutedSearch<'a> {
     range_read_limiter: RangeReadLimiter,
     batch_parallelism: usize,
     allow_buffered_read: bool,
+    joint_enabled: bool,
 }
 
 impl RoutedSearch<'_> {
@@ -276,46 +402,59 @@ impl RoutedSearch<'_> {
                 width,
                 limit,
                 hits: ScoredRowIds::empty(),
+                joint: false,
+                legacy_joint_hits: ScoredRowIds::empty(),
             });
         }
 
+        let legacy_probed = if self.joint_enabled {
+            self.resolve_joint_routes(queries, &mut routes, timing)
+                .await?
+        } else {
+            BTreeSet::new()
+        };
+
         loop {
             let mut queries_by_centroid = BTreeMap::<_, Vec<_>>::new();
             for (index, route) in routes.iter_mut().enumerate() {
                 for &centroid in &route.nearest[route.visited..route.width] {
-                    if group.shards[&centroid].index_file.row_count > 0 {
-                        
queries_by_centroid.entry(centroid).or_default().push(index);
+                    if group.shards[&centroid].index_file.row_count > 0
+                        && !(route.visited == 0 && 
legacy_probed.contains(&centroid))
+                    {
+                        let probe = if route.joint {
+                            Probe::Joint
+                        } else {
+                            Probe::Standard
+                        };
+                        queries_by_centroid
+                            .entry(centroid)
+                            .or_default()
+                            .push((index, probe));
                     }
                 }
                 route.visited = route.width;
             }
-            for (centroid, indices) in queries_by_centroid {
-                let (results, stats) = execute_vector_file_work(
+            for (centroid, pending) in queries_by_centroid {
+                let (indices, probes): (Vec<_>, Vec<_>) = 
pending.into_iter().unzip();
+                let (results, stats) = execute_vector_file_probes(
                     self.evaluation,
-                    VectorIndexWork {
-                        entry: group.shards[&centroid].clone(),
-                        centroid_files: vec![],
-                        queries: indices
-                            .iter()
-                            .map(|&index| queries[index].clone())
-                            .collect(),
-                        resolved: Some(self.configuration.clone()),
-                        filter: None,
-                        top_ks: vec![],
-                    },
+                    self.shard_work(queries, centroid, &indices),
                     self.metric_check.clone(),
                     self.range_read_limiter.clone(),
                     self.batch_parallelism,
+                    if probes.contains(&Probe::Joint) {
+                        probes
+                    } else {
+                        vec![]
+                    },
                     self.allow_buffered_read,
                 )
                 .await?;
-                timing.permit_wait = 
timing.permit_wait.saturating_add(stats.permit_wait);
-                timing.file_reader_open = timing
-                    .file_reader_open
-                    .saturating_add(stats.file_reader_open);
+                add_timing(timing, stats);
                 for (index, result) in indices.into_iter().zip(results) {
                     let route = &mut routes[index];
-                    route.hits = route.hits.or(&result).top_k(route.limit);
+                    let hits = result.joint.unwrap_or(result.standard);
+                    route.hits = route.hits.or(&hits).top_k(route.limit);
                 }
             }
 
@@ -327,6 +466,7 @@ impl RoutedSearch<'_> {
                         && route.hits.row_ids.len() < route.limit
                     {
                         route.width = route.width.saturating_mul(2).min(nlist);
+                        route.joint = false;
                         expand = true;
                     }
                 }
@@ -337,4 +477,152 @@ impl RoutedSearch<'_> {
         }
         Ok(routes.into_iter().map(|route| route.hits).collect())
     }
+
+    fn shard_work(
+        &self,
+        queries: &[VectorSearch],
+        id: usize,
+        indices: &[usize],
+    ) -> VectorIndexWork {
+        VectorIndexWork {
+            entry: self.group.shards[&id].clone(),
+            centroid_files: vec![],
+            queries: indices
+                .iter()
+                .map(|&index| queries[index].clone())
+                .collect(),
+            resolved: Some(self.configuration.clone()),
+            filter: None,
+            top_ks: vec![],
+        }
+    }
+
+    async fn resolve_joint_routes(
+        &self,
+        queries: &[VectorSearch],
+        routes: &mut [Route],
+        timing: &mut IndexSearchTiming,
+    ) -> Result<BTreeSet<usize>> {
+        let group = self.group;
+        let mut layouts = HashMap::new();
+        let mut legacy = BTreeSet::new();
+        for (route, query) in routes.iter_mut().zip(queries) {
+            if route.width != AUTOMATIC_WIDTH
+                || !(10..=100).contains(&query.limit)
+                || query.effective_include_row_ids().is_some()
+            {
+                continue;
+            }
+            let mut unknown = Vec::new();
+            route.joint = true;
+            for &id in &route.nearest[..JOINT_OUTER_PROBES] {
+                let file = &group.shards[&id].index_file;
+                if file.row_count < (JOINT_INNER_PROBES * query.limit) as i64 {
+                    route.joint = false;
+                    break;
+                }
+                let layout = match layouts.entry(id) {
+                    std::collections::hash_map::Entry::Occupied(entry) => 
*entry.get(),
+                    std::collections::hash_map::Entry::Vacant(entry) => {
+                        let desc = Descriptor::parse(file)?.expect("validated 
centroid shard");
+                        let options = centroid_index::payload_options(&desc)?;
+                        let layout = options
+                            .get("localNlist")
+                            .map(|count| {
+                                count
+                                    .parse::<usize>()
+                                    .map(|n| {
+                                        n == SHARD_LISTS
+                                            && options
+                                                .get("metric")
+                                                .is_some_and(|value| value == 
"l2")
+                                    })
+                                    .map_err(|_| {
+                                        centroid_index::invalid("Invalid 
centroid shard localNlist")
+                                    })
+                            })
+                            .transpose()?;
+                        *entry.insert(layout)
+                    }
+                };
+                match layout {
+                    Some(false) => {
+                        route.joint = false;
+                        break;
+                    }
+                    None => unknown.push(id),
+                    Some(true) => {}
+                }
+            }
+            if route.joint {
+                if unknown.is_empty() {
+                    route.width = JOINT_OUTER_PROBES;
+                } else {
+                    legacy.extend(unknown);
+                }
+            }
+        }
+
+        // Evaluate both policies while each legacy shard's native reader is 
open.
+        // Only the winning policy's bounded top-K survives layout resolution.
+        for &id in &legacy {
+            let (indices, probes): (Vec<_>, Vec<_>) = routes
+                .iter()
+                .enumerate()
+                .filter_map(|(index, route)| {
+                    let rank = route.nearest[..route.width]
+                        .iter()
+                        .position(|&candidate| candidate == id)?;
+                    let probe = if route.joint && rank < JOINT_OUTER_PROBES {
+                        Probe::CheckLayout
+                    } else {
+                        Probe::Standard
+                    };
+                    Some((index, probe))
+                })
+                .unzip();
+            let (hits, stats) = execute_vector_file_probes(
+                self.evaluation,
+                self.shard_work(queries, id, &indices),
+                self.metric_check.clone(),
+                self.range_read_limiter.clone(),
+                self.batch_parallelism,
+                probes.clone(),
+                self.allow_buffered_read,
+            )
+            .await?;
+            add_timing(timing, stats);
+            for ((index, probe), hits) in 
indices.into_iter().zip(probes).zip(hits) {
+                let route = &mut routes[index];
+                route.hits = route.hits.or(&hits.standard).top_k(route.limit);
+                if probe == Probe::CheckLayout {
+                    if let Some(joint) = hits.joint {
+                        route.legacy_joint_hits =
+                            
route.legacy_joint_hits.or(&joint).top_k(route.limit);
+                    } else {
+                        route.joint = false;
+                    }
+                }
+            }
+        }
+        for route in routes {
+            if route.joint {
+                route.width = JOINT_OUTER_PROBES;
+                std::mem::swap(&mut route.hits, &mut route.legacy_joint_hits);
+            }
+            route.legacy_joint_hits = ScoredRowIds::empty();
+        }
+        Ok(legacy)
+    }
+}
+
+fn add_timing(timing: &mut IndexSearchTiming, stats: IndexSearchTiming) {
+    timing.permit_wait = timing.permit_wait.saturating_add(stats.permit_wait);
+    timing.file_reader_open = timing
+        .file_reader_open
+        .saturating_add(stats.file_reader_open);
 }
+
+#[cfg(test)]
+#[path = "centroid_joint_tests.rs"]
+mod joint_tests;
diff --git a/crates/paimon/src/table/de_vector_read/centroid_joint_tests.rs 
b/crates/paimon/src/table/de_vector_read/centroid_joint_tests.rs
new file mode 100644
index 00000000..69303c19
--- /dev/null
+++ b/crates/paimon/src/table/de_vector_read/centroid_joint_tests.rs
@@ -0,0 +1,284 @@
+// 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::io::{FileIO, FileIOBuilder};
+use crate::spec::{BinaryRow, FileKind, GlobalIndexMeta, IndexFileMeta, 
VectorIndexOptions};
+use crate::table::vector_search_test_utils::{vector_search_log_start, 
vector_search_logs_since};
+use crate::vector_search::GlobalIndexIOMeta;
+use paimon_vindex_core::io::PosWriter;
+use paimon_vindex_core::ivfflat::IVFFlatIndex;
+use paimon_vindex_core::ivfflat_io::write_ivfflat_index;
+use std::io::Cursor;
+use std::sync::{Arc, Mutex};
+
+const ROOT: &str = "memory:/centroid-joint";
+const ROWS: usize = 192;
+
+fn flat_shard(nlist: usize, base: f32, first_id: usize, rows_per_list: usize) 
-> Vec<u8> {
+    let centers = (0..nlist)
+        .map(|i| base + 10.0 * i as f32)
+        .collect::<Vec<_>>();
+    let mut index = IVFFlatIndex::new(1, nlist, MetricType::L2);
+    index.set_quantizer_centroids(centers.clone());
+    let data = centers
+        .into_iter()
+        .flat_map(|center| std::iter::repeat_n(center, rows_per_list))
+        .collect::<Vec<_>>();
+    let labels = (first_id..first_id + data.len())
+        .map(|label| label as i64)
+        .collect::<Vec<_>>();
+    index.add(&data, &labels, data.len());
+    let mut bytes = Vec::new();
+    write_ivfflat_index(&index, &mut PosWriter::new(&mut bytes)).unwrap();
+    bytes
+}
+
+#[test]
+fn joint_probe_uses_sixteen_lists_and_retries_an_incomplete_shard() {
+    let bytes = flat_shard(64, 0.0, 0, 1);
+    let meta = GlobalIndexIOMeta::new("joint".into(), bytes.len() as u64, 
vec![]);
+    let mut reader = VindexVectorGlobalIndexReader::new(meta, HashMap::new());
+    let queries = [
+        VectorSearch::new(vec![0.0], 16, "embedding".into())
+            .unwrap()
+            .with_options(HashMap::from([("ivf.nprobe".into(), "1".into())])),
+        VectorSearch::new(vec![0.0], 17, "embedding".into())
+            .unwrap()
+            .with_options(HashMap::from([("ivf.nprobe".into(), "1".into())])),
+        VectorSearch::new(vec![0.0], 20, "embedding".into())
+            .unwrap()
+            .with_options(HashMap::from([("ivf.nprobe".into(), "64".into())])),
+    ];
+    let probes = [Probe::CheckLayout, Probe::CheckLayout, Probe::Joint];
+    let result = search_file(&mut reader, &queries, &probes, 
Cursor::new(bytes), |_| {
+        Ok(())
+    })
+    .unwrap();
+    assert_eq!(result[0].standard.as_ref().unwrap().len(), 1);
+    let joint = result[0].joint.as_ref().unwrap().as_ref().unwrap();
+    assert_eq!(joint.len(), 16);
+    assert!((0..16).all(|id| joint.contains_key(&id)));
+    assert_eq!(result[1].joint.as_ref(), Some(&result[1].standard));
+    assert_eq!(result[1].standard.as_ref().unwrap().len(), 1);
+    let retried = result[2].joint.as_ref().unwrap().as_ref().unwrap();
+    assert_eq!(retried.len(), 20);
+    assert!((0..20).all(|id| retried.contains_key(&id)));
+}
+
+fn entry(role: Role, size: usize, rows: usize, payload: Option<&[u8]>) -> 
IndexManifestEntry {
+    let file_name = match role {
+        Role::Router(_) => "router".into(),
+        Role::Shard(id) => format!("shard-{id}"),
+        _ => unreachable!(),
+    };
+    IndexManifestEntry {
+        version: 1,
+        kind: FileKind::Add,
+        partition: BinaryRow::new(0).to_serialized_bytes(),
+        bucket: 0,
+        index_file: IndexFileMeta {
+            index_type: "ivf-flat".into(),
+            file_name,
+            file_size: size as i64,
+            row_count: rows as i64,
+            external_path: None,
+            deletion_vectors_ranges: None,
+            global_index_meta: Some(GlobalIndexMeta {
+                row_range_start: 0,
+                row_range_end: (8 * ROWS - 1) as i64,
+                index_field_id: 0,
+                extra_field_ids: None,
+                index_meta: Some(
+                    Descriptor {
+                        model_id: "test-router",
+                        version: 1,
+                        role,
+                        payload,
+                    }
+                    .encode()
+                    .unwrap(),
+                ),
+                source_meta: None,
+            }),
+        },
+    }
+}
+
+async fn store(io: &FileIO, entry: &IndexManifestEntry, bytes: Vec<u8>) {
+    io.new_output(&format!("{ROOT}/index/{}", entry.index_file.file_name))
+        .unwrap()
+        .write(bytes.into())
+        .await
+        .unwrap();
+}
+
+async fn run(
+    io: &FileIO,
+    entries: &[IndexManifestEntry],
+    queries: &[f32],
+    options: HashMap<String, String>,
+) -> Vec<ScoredRowIds> {
+    let queries = queries
+        .iter()
+        .copied()
+        .map(|value| VectorSearch::new(vec![value], 10, 
"embedding".into()).unwrap())
+        .collect();
+    let options = VectorIndexOptions {
+        index_type: Some("ivf-flat".into()),
+        metric: "l2".into(),
+        options,
+    };
+    let table_options = HashMap::new();
+    execute_work(
+        VectorSearchEvaluation {
+            table: None,
+            file_io: io,
+            table_path: ROOT,
+            table_options: &table_options,
+            schema_fields: &[],
+            next_row_id: None,
+            filter: None,
+        },
+        VectorIndexWork {
+            entry: entries[0].clone(),
+            centroid_files: entries.to_vec(),
+            queries,
+            resolved: Some(options),
+            filter: None,
+            top_ks: vec![],
+        },
+        VectorMetricCheck {
+            persisted: Arc::new(Mutex::new(None)),
+            requested: None,
+        },
+        RangeReadLimiter::new(2),
+        1,
+    )
+    .await
+    .unwrap()
+    .0
+}
+
+#[tokio::test]
+async fn joint_routes_use_four_shards_with_or_without_manifest_geometry() {
+    let io = FileIOBuilder::new("memory").build().unwrap();
+    let router = Router::new(
+        MetricType::L2,
+        1,
+        (0..64).map(|i| i as f32 * 10.0).collect(),
+    )
+    .unwrap();
+    let bytes = router.encode("test-router").unwrap();
+    let router_entry = entry(Role::Router(64), bytes.len(), 0, None);
+    store(&io, &router_entry, bytes).await;
+    let mut entries = vec![router_entry];
+    let mut legacy = entries.clone();
+    for id in 0..64 {
+        let base = if id < 4 { 100.0 + id as f32 } else { 0.0 };
+        let (bytes, count) = if id < 8 {
+            (flat_shard(64, base, id * ROWS, 3), ROWS)
+        } else {
+            (centroid_index::EMPTY_SHARD.to_vec(), 0)
+        };
+        let shard = entry(
+            Role::Shard(id),
+            bytes.len(),
+            count,
+            Some(br#"{"localNlist":"64","metric":"l2"}"#),
+        );
+        store(&io, &shard, bytes).await;
+        legacy.push(if id == 0 {
+            entry(
+                Role::Shard(id),
+                shard.index_file.file_size as usize,
+                count,
+                None,
+            )
+        } else {
+            shard.clone()
+        });
+        entries.push(shard);
+    }
+    let queries = [0.0, 70.0];
+    let joint = run(&io, &entries, &queries, HashMap::new()).await;
+    let legacy_joint = run(&io, &legacy, &queries, HashMap::new()).await;
+    assert_eq!(joint[0].row_ids.len(), 10);
+    assert!(joint[0].row_ids.iter().all(|&id| id < (4 * ROWS) as u64));
+    for (expected, actual) in joint.iter().zip(legacy_joint) {
+        assert_eq!(expected.row_ids, actual.row_ids);
+        assert_eq!(expected.scores, actual.scores);
+    }
+
+    let standard = run(
+        &io,
+        &entries,
+        &queries,
+        HashMap::from([("centroid.nprobe".into(), "8".into())]),
+    )
+    .await;
+    assert!(standard[0]
+        .row_ids
+        .iter()
+        .all(|&id| id >= (4 * ROWS) as u64));
+
+    // Shard 4 needs a layout check for the second query. It ranks fifth for
+    // the first query, whose four nearest shards already have known layouts.
+    let mut mixed = entries.clone();
+    mixed[5] = entry(
+        Role::Shard(4),
+        entries[5].index_file.file_size as usize,
+        ROWS,
+        None,
+    );
+    let mixed_queries = [0.0, 40.0];
+    let expected = run(&io, &entries, &mixed_queries, HashMap::new()).await;
+    let log_start = vector_search_log_start();
+    let timing = crate::vindex::enable_vector_search_timing_for_test();
+    let actual = run(&io, &mixed, &mixed_queries, HashMap::new()).await;
+    drop(timing);
+    for (expected, actual) in expected.iter().zip(actual) {
+        assert_eq!(expected.row_ids, actual.row_ids);
+        assert_eq!(expected.scores, actual.scores);
+    }
+    let logs = vector_search_logs_since(log_start);
+    let shard_logs: Vec<_> = logs
+        .iter()
+        .filter(|entry| entry.starts_with("event=paimon_vindex_reader 
file=shard-4 "))
+        .collect();
+    assert_eq!(shard_logs.len(), 2, "{shard_logs:?}");
+    assert!(
+        shard_logs[0].contains("nq=1 nprobe=auto "),
+        "{shard_logs:?}"
+    );
+    assert!(shard_logs[1].contains("nq=1 nprobe=16 "), "{shard_logs:?}");
+    assert!(
+        !shard_logs[0].contains("vindex_open_ms=0.000 "),
+        "{shard_logs:?}"
+    );
+    assert!(
+        shard_logs[1].contains("vindex_open_ms=0.000 "),
+        "{shard_logs:?}"
+    );
+
+    let bytes = flat_shard(1, 100.0, 0, ROWS);
+    legacy[1] = entry(Role::Shard(0), bytes.len(), ROWS, None);
+    store(&io, &legacy[1], bytes).await;
+    let fallback = run(&io, &legacy, &queries, HashMap::new()).await;
+    assert_eq!(standard[0].row_ids, fallback[0].row_ids);
+    assert_eq!(standard[0].scores, fallback[0].scores);
+}
diff --git a/crates/paimon/src/table/pk_vector_read/tests.rs 
b/crates/paimon/src/table/pk_vector_read/tests.rs
index ffa02348..209cb703 100644
--- a/crates/paimon/src/table/pk_vector_read/tests.rs
+++ b/crates/paimon/src/table/pk_vector_read/tests.rs
@@ -27,7 +27,9 @@ use crate::table::data_file_reader::DataFileReader;
 use crate::table::pk_vector_orchestrator::{PkVectorCandidate, 
PkVectorSearchSplit};
 use crate::table::source::DataSplitBuilder;
 use crate::table::vector_scan::Scan;
-use crate::table::vector_search_test_utils::{build_vindex_segment_bytes, 
pk_vector_table};
+use crate::table::vector_search_test_utils::{
+    build_vindex_segment_bytes, pk_vector_table, vector_search_log_start, 
vector_search_logs_since,
+};
 use crate::table::{Table, TableCommit, TableWrite};
 use crate::vindex::pkvector::metric::VectorSearchMetric;
 use crate::vindex::IVF_FLAT_IDENTIFIER;
@@ -37,39 +39,7 @@ use arrow_schema::{DataType as ArrowDataType, Field as 
ArrowField, Schema as Arr
 use paimon_vindex_core::index::VectorIndexReader as VIndexReader;
 use std::collections::HashMap;
 use std::io::Cursor;
-use std::sync::{Arc, Mutex, Once};
-
-const VECTOR_SEARCH_LOG_TARGET: &str = "paimon::vector_search";
-
-static VECTOR_SEARCH_TEST_LOGGER: VectorSearchTestLogger = 
VectorSearchTestLogger;
-
-static VECTOR_SEARCH_TEST_LOGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
-
-struct VectorSearchTestLogger;
-
-impl log::Log for VectorSearchTestLogger {
-    fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
-        metadata.target() == VECTOR_SEARCH_LOG_TARGET && metadata.level() <= 
log::Level::Debug
-    }
-
-    fn log(&self, record: &log::Record<'_>) {
-        if self.enabled(record.metadata()) {
-            VECTOR_SEARCH_TEST_LOGS
-                .lock()
-                .unwrap()
-                .push(record.args().to_string());
-        }
-    }
-
-    fn flush(&self) {}
-}
-
-fn reset_vector_search_test_logs() {
-    static INIT: Once = Once::new();
-    INIT.call_once(|| log::set_logger(&VECTOR_SEARCH_TEST_LOGGER).unwrap());
-    log::set_max_level(log::LevelFilter::Debug);
-    VECTOR_SEARCH_TEST_LOGS.lock().unwrap().clear();
-}
+use std::sync::Arc;
 
 fn pk_data_file(name: &str, row_count: i64, first_row_id: Option<i64>) -> 
DataFileMeta {
     DataFileMeta {
@@ -1092,7 +1062,7 @@ async fn 
reader_uses_planned_splits_after_index_manifest_is_removed() {
 
 #[tokio::test]
 async fn execute_returns_scored_positions_and_publishes_diagnostics() {
-    reset_vector_search_test_logs();
+    let log_start = vector_search_log_start();
     let _timing = crate::vindex::enable_vector_search_timing_for_test();
     // query [0,1]: squared-L2 distances pos1=0 < pos2=1 < pos0=2, so the
     // strict-gap top-2 is [pos1, pos2] (best-first, not physical order).
@@ -1135,7 +1105,7 @@ async fn 
execute_returns_scored_positions_and_publishes_diagnostics() {
         "positions must refer to their retained source split"
     );
 
-    let logs = VECTOR_SEARCH_TEST_LOGS.lock().unwrap();
+    let logs = vector_search_logs_since(log_start);
     assert!(
         logs.iter().any(|entry| {
             entry.contains("event=paimon_vindex_reader")
diff --git a/crates/paimon/src/table/vector_search_test_utils.rs 
b/crates/paimon/src/table/vector_search_test_utils.rs
index b8794a26..d4c10d92 100644
--- a/crates/paimon/src/table/vector_search_test_utils.rs
+++ b/crates/paimon/src/table/vector_search_test_utils.rs
@@ -27,7 +27,41 @@ use arrow_array::builder::{Float32Builder, ListBuilder};
 use arrow_array::{ArrayRef, Int32Array, RecordBatch};
 use arrow_schema::{DataType as ArrowDataType, Field as ArrowField, Schema as 
ArrowSchema};
 use std::collections::HashMap;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex, Once};
+
+const VECTOR_SEARCH_LOG_TARGET: &str = "paimon::vector_search";
+static VECTOR_SEARCH_TEST_LOGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
+
+struct VectorSearchTestLogger;
+
+impl log::Log for VectorSearchTestLogger {
+    fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
+        metadata.target() == VECTOR_SEARCH_LOG_TARGET && metadata.level() <= 
log::Level::Debug
+    }
+
+    fn log(&self, record: &log::Record<'_>) {
+        if self.enabled(record.metadata()) {
+            VECTOR_SEARCH_TEST_LOGS
+                .lock()
+                .unwrap()
+                .push(record.args().to_string());
+        }
+    }
+
+    fn flush(&self) {}
+}
+
+pub(super) fn vector_search_log_start() -> usize {
+    static INIT: Once = Once::new();
+    static LOGGER: VectorSearchTestLogger = VectorSearchTestLogger;
+    INIT.call_once(|| log::set_logger(&LOGGER).unwrap());
+    log::set_max_level(log::LevelFilter::Debug);
+    VECTOR_SEARCH_TEST_LOGS.lock().unwrap().len()
+}
+
+pub(super) fn vector_search_logs_since(start: usize) -> Vec<String> {
+    VECTOR_SEARCH_TEST_LOGS.lock().unwrap()[start..].to_vec()
+}
 
 pub(super) fn vector_test_table() -> Table {
     vector_test_table_at("memory:/vector_test")
diff --git a/crates/paimon/src/vindex/reader.rs 
b/crates/paimon/src/vindex/reader.rs
index f2629fdd..73cb6ec8 100644
--- a/crates/paimon/src/vindex/reader.rs
+++ b/crates/paimon/src/vindex/reader.rs
@@ -23,8 +23,8 @@ use paimon_vindex_core::index::{
     VectorIndexReaderOptions, VectorSearchParams,
 };
 use paimon_vindex_core::io::{ReadRequest, SeekRead, SeekReadCapabilities};
-use std::collections::BinaryHeap;
-use std::collections::HashMap;
+use std::borrow::Borrow;
+use std::collections::{BTreeSet, BinaryHeap, HashMap};
 use std::io;
 use std::sync::{Arc, Condvar, Mutex};
 use std::time::{Duration, Instant};
@@ -98,6 +98,7 @@ fn native_batch_memory_reservation(index_parallelism: usize) 
-> usize {
 
 #[derive(Clone, Copy, Default)]
 struct VindexLoadTiming {
+    total: Duration,
     vindex_open: Duration,
     metadata: Duration,
     optimize: Duration,
@@ -105,6 +106,7 @@ struct VindexLoadTiming {
 
 #[derive(Default)]
 struct VindexBatchStats {
+    nprobes: BTreeSet<Option<usize>>,
     native_chunk_queries: Vec<usize>,
     scalar_chunk_count: usize,
     max_chunk_size: usize,
@@ -225,32 +227,39 @@ impl VindexVectorGlobalIndexReader {
         S: SeekRead + 'static,
         F: FnOnce(&VectorIndexMetadata) -> crate::Result<()>,
     {
-        let total_start = self.timing_enabled.then(Instant::now);
         self.ensure_loaded(stream_fn, validate)?;
+        self.search_loaded_batch(vector_searches, None)
+    }
+
+    pub(crate) fn search_loaded_batch(
+        &mut self,
+        vector_searches: &[impl Borrow<VectorSearch>],
+        nprobe_override: Option<usize>,
+    ) -> crate::Result<Vec<Option<HashMap<u64, f32>>>> {
         let search_start = self.timing_enabled.then(Instant::now);
-        let results = self.search_batch(vector_searches)?;
-        if let (Some(total_start), Some(search_start), Some(stats)) =
-            (total_start, search_start, self.batch_stats.as_ref())
-        {
-            let total = total_start.elapsed();
+        let results = self.search_batch(vector_searches, nprobe_override)?;
+        // A preloaded reader reports its loading cost with its first search 
only.
+        let load_timing = std::mem::take(&mut self.load_timing);
+        if let (Some(search_start), Some(stats)) = (search_start, 
self.batch_stats.as_ref()) {
             let native_search = search_start.elapsed();
-            let load = self
-                .load_timing
+            let total = load_timing.total.saturating_add(native_search);
+            let load = load_timing
                 .vindex_open
-                .saturating_add(self.load_timing.metadata)
-                .saturating_add(self.load_timing.optimize);
-            let unattributed = 
total.saturating_sub(load.saturating_add(native_search));
+                .saturating_add(load_timing.metadata)
+                .saturating_add(load_timing.optimize);
+            let unattributed = load_timing.total.saturating_sub(load);
             let chunk_queries = stats
                 .native_chunk_queries
                 .iter()
                 .map(usize::to_string)
                 .collect::<Vec<_>>()
                 .join(",");
-            let nprobe = self
-                .options
-                .get(NPROBE_PARAMETER)
-                .cloned()
-                .unwrap_or_else(|| "auto".to_string());
+            let nprobe = stats
+                .nprobes
+                .iter()
+                .map(|width| width.map_or_else(|| "auto".to_string(), |width| 
width.to_string()))
+                .collect::<Vec<_>>()
+                .join(",");
             log::debug!(
                 target: "paimon::vector_search",
                 "event=paimon_vindex_reader file={} nq={} nprobe={} 
batch_index_parallelism={} memory_budget_bytes={} max_chunk_size={} 
native_chunk_count={} native_chunk_queries={} scalar_chunk_count={} 
total_ms={:.3} vindex_open_ms={:.3} metadata_ms={:.3} optimize_ms={:.3} 
native_search_wall_ms={:.3} unattributed_ms={:.3}",
@@ -264,9 +273,9 @@ impl VindexVectorGlobalIndexReader {
                 chunk_queries,
                 stats.scalar_chunk_count,
                 total.as_secs_f64() * 1000.0,
-                self.load_timing.vindex_open.as_secs_f64() * 1000.0,
-                self.load_timing.metadata.as_secs_f64() * 1000.0,
-                self.load_timing.optimize.as_secs_f64() * 1000.0,
+                load_timing.vindex_open.as_secs_f64() * 1000.0,
+                load_timing.metadata.as_secs_f64() * 1000.0,
+                load_timing.optimize.as_secs_f64() * 1000.0,
                 native_search.as_secs_f64() * 1000.0,
                 unattributed.as_secs_f64() * 1000.0,
             );
@@ -282,6 +291,14 @@ impl VindexVectorGlobalIndexReader {
         self.ensure_loaded(stream_fn, |_| Ok(()))
     }
 
+    pub(crate) fn load_validated<S: SeekRead + 'static>(
+        &mut self,
+        stream_fn: impl FnOnce(&str) -> crate::Result<S>,
+        validate: impl FnOnce(&VectorIndexMetadata) -> crate::Result<()>,
+    ) -> crate::Result<()> {
+        self.ensure_loaded(stream_fn, validate)
+    }
+
     pub fn metadata(&self) -> crate::Result<&VectorIndexMetadata> {
         self.metadata
             .as_ref()
@@ -293,7 +310,8 @@ impl VindexVectorGlobalIndexReader {
 
     fn search_batch(
         &mut self,
-        vector_searches: &[VectorSearch],
+        vector_searches: &[impl Borrow<VectorSearch>],
+        nprobe_override: Option<usize>,
     ) -> crate::Result<Vec<Option<HashMap<u64, f32>>>> {
         let reader = self
             .reader
@@ -315,13 +333,14 @@ impl VindexVectorGlobalIndexReader {
                     "MultiVector indexes require cosine similarity",
                 ));
             }
-            let prepared = prepare_batch_searches(metadata, &self.options, 
vector_searches, true)?;
+            let prepared =
+                prepare_batch_searches(metadata, &self.options, 
vector_searches, true, None)?;
             return vector_searches
                 .iter()
                 .zip(prepared)
                 .map(|(query, prepared)| match prepared {
                     Some(prepared) => {
-                        search_distinct_rows(reader, metadata, query, 
row_count, prepared)
+                        search_distinct_rows(reader, metadata, query.borrow(), 
row_count, prepared)
                     }
                     None => Ok(None),
                 })
@@ -332,6 +351,7 @@ impl VindexVectorGlobalIndexReader {
             metadata,
             &self.options,
             vector_searches,
+            nprobe_override,
             self.batch_index_parallelism,
             self.timing_enabled,
         )?;
@@ -390,7 +410,6 @@ impl VindexVectorGlobalIndexReader {
         O: FnOnce(&mut VIndexReader<VindexInput>) -> crate::Result<()>,
     {
         if self.reader.is_some() {
-            self.load_timing = VindexLoadTiming::default();
             return validate(self.metadata()?);
         }
 
@@ -418,6 +437,7 @@ impl VindexVectorGlobalIndexReader {
         self.reader = Some(reader);
         self.metadata = Some(metadata);
         self.load_timing = VindexLoadTiming {
+            total: open_start.map_or(Duration::ZERO, |start| start.elapsed()),
             vindex_open,
             metadata: metadata_elapsed,
             optimize: optimize_elapsed,
@@ -470,7 +490,7 @@ fn prepare_search(
     options: &HashMap<String, String>,
     vector_search: &VectorSearch,
 ) -> crate::Result<Option<PreparedSearch>> {
-    prepare_search_with_shared_filter(metadata, options, vector_search, None, 
false)
+    prepare_search_with_shared_filter(metadata, options, vector_search, None, 
false, None)
 }
 
 fn prepare_search_with_shared_filter(
@@ -479,6 +499,7 @@ fn prepare_search_with_shared_filter(
     vector_search: &VectorSearch,
     shared_filter_bytes: Option<&Arc<[u8]>>,
     multi_vector: bool,
+    nprobe_override: Option<usize>,
 ) -> crate::Result<Option<PreparedSearch>> {
     // Query options override the defaults of a reusable index reader.
     let mut merged_options;
@@ -515,6 +536,9 @@ fn prepare_search_with_shared_filter(
         (true, _) => (nprobe, None),
         (false, _) => (nprobe, l_search),
     };
+    let nprobe = nprobe_override
+        .map(Ok)
+        .or_else(|| nprobe.map(|value| parse_search_width(NPROBE_PARAMETER, 
value)));
     let mut params = match (nprobe, l_search) {
         (Some(_), Some(_)) => {
             return Err(crate::Error::DataInvalid {
@@ -524,9 +548,7 @@ fn prepare_search_with_shared_filter(
                 source: None,
             });
         }
-        (Some(value), None) => {
-            VectorSearchParams::new(top_k, 
parse_search_width(NPROBE_PARAMETER, value)?)
-        }
+        (Some(value), None) => VectorSearchParams::new(top_k, value?),
         (None, Some(value)) => {
             let l_search = parse_search_width(L_SEARCH_PARAMETER, value)?;
             if l_search == 0 {
@@ -572,14 +594,19 @@ fn serialize_row_id_filter(include_ids: 
&roaring::RoaringTreemap) -> crate::Resu
 }
 
 fn shared_batch_include_row_ids(
-    vector_searches: &[VectorSearch],
+    vector_searches: &[impl Borrow<VectorSearch>],
 ) -> Option<&Arc<roaring::RoaringTreemap>> {
-    let first = vector_searches.first()?.shared_include_row_ids.as_ref()?;
+    let first = vector_searches
+        .first()?
+        .borrow()
+        .shared_include_row_ids
+        .as_ref()?;
     vector_searches
         .iter()
         .skip(1)
         .all(|search| {
             search
+                .borrow()
                 .shared_include_row_ids
                 .as_ref()
                 .is_some_and(|include_row_ids| Arc::ptr_eq(first, 
include_row_ids))
@@ -590,8 +617,9 @@ fn shared_batch_include_row_ids(
 fn prepare_batch_searches(
     metadata: &VectorIndexMetadata,
     options: &HashMap<String, String>,
-    vector_searches: &[VectorSearch],
+    vector_searches: &[impl Borrow<VectorSearch>],
     multi_vector: bool,
+    nprobe_override: Option<usize>,
 ) -> crate::Result<Vec<Option<PreparedSearch>>> {
     let shared_filter_bytes = shared_batch_include_row_ids(vector_searches)
         .filter(|include_row_ids| !include_row_ids.is_empty())
@@ -603,9 +631,10 @@ fn prepare_batch_searches(
             prepare_search_with_shared_filter(
                 metadata,
                 options,
-                search,
+                search.borrow(),
                 shared_filter_bytes.as_ref(),
                 multi_vector,
+                nprobe_override,
             )
         })
         .collect()
@@ -760,7 +789,8 @@ fn search_batch_vindex(
     reader: &mut VIndexReader<impl SeekRead>,
     metadata: &VectorIndexMetadata,
     options: &HashMap<String, String>,
-    vector_searches: &[VectorSearch],
+    vector_searches: &[impl Borrow<VectorSearch>],
+    nprobe_override: Option<usize>,
     index_parallelism: usize,
     timing_enabled: bool,
 ) -> crate::Result<VindexBatchSearchResult> {
@@ -773,9 +803,10 @@ fn search_batch_vindex(
         ..VindexBatchStats::default()
     });
 
-    for (index, prepared) in prepare_batch_searches(metadata, options, 
vector_searches, false)?
-        .into_iter()
-        .enumerate()
+    for (index, prepared) in
+        prepare_batch_searches(metadata, options, vector_searches, false, 
nprobe_override)?
+            .into_iter()
+            .enumerate()
     {
         let Some(prepared) = prepared else {
             continue;
@@ -794,6 +825,12 @@ fn search_batch_vindex(
         let chunk_size = native_batch_chunk_size(metadata, &prepared, 
index_parallelism);
         if let Some(stats) = &mut batch_stats {
             stats.max_chunk_size = stats.max_chunk_size.max(chunk_size);
+            stats.nprobes.insert(
+                prepared
+                    .params
+                    .configured_ivf_nprobe()
+                    .map(|width| width.min(metadata.nlist)),
+            );
         }
         for indices in indices.chunks(chunk_size) {
             if indices.len() == 1 {
@@ -801,8 +838,11 @@ fn search_batch_vindex(
                     stats.scalar_chunk_count += 1;
                 }
                 let index = indices[0];
-                let (labels, distances) =
-                    execute_scalar_search(reader, 
&vector_searches[index].vector, &prepared)?;
+                let (labels, distances) = execute_scalar_search(
+                    reader,
+                    &vector_searches[index].borrow().vector,
+                    &prepared,
+                )?;
                 let map =
                     collect_results(&labels, &distances, 
prepared.params.top_k, metadata.metric);
                 if !map.is_empty() {
@@ -820,7 +860,7 @@ fn search_batch_vindex(
             let _memory_permit = acquire_native_batch_memory(reservation);
             let mut queries = Vec::with_capacity(indices.len() * 
metadata.dimension);
             for &index in indices {
-                queries.extend_from_slice(&vector_searches[index].vector);
+                
queries.extend_from_slice(&vector_searches[index].borrow().vector);
             }
             let params = prepared.params;
             let (labels, distances) = match &prepared.filter_bytes {
@@ -1281,7 +1321,8 @@ mod tests {
         let defaults = HashMap::from([(NPROBE_PARAMETER.into(), "1".into())]);
         let explicit = 
query().with_options(HashMap::from([(NPROBE_PARAMETER.into(), "7".into())]));
         let prepared =
-            prepare_batch_searches(&metadata, &defaults, &[explicit, query()], 
false).unwrap();
+            prepare_batch_searches(&metadata, &defaults, &[explicit, query()], 
false, None)
+                .unwrap();
         assert_eq!(prepared[0].as_ref().unwrap().params.width, 7);
         assert_eq!(prepared[1].as_ref().unwrap().params.width, 1);
         let conflicting =
@@ -1417,7 +1458,7 @@ mod tests {
         }
 
         let prepared =
-            prepare_batch_searches(&metadata, &HashMap::new(), &searches, 
false).unwrap();
+            prepare_batch_searches(&metadata, &HashMap::new(), &searches, 
false, None).unwrap();
         let first = prepared[0]
             .as_ref()
             .and_then(|search| search.filter_bytes.as_ref())
@@ -1565,7 +1606,8 @@ mod tests {
             ("diskann.l_search".to_string(), "64".to_string()),
         ]);
         assert!(prepare_search(&metadata, &mixed_options, &query()).is_err());
-        let diskann = prepare_batch_searches(&metadata, &mixed_options, 
&[query()], true).unwrap();
+        let diskann =
+            prepare_batch_searches(&metadata, &mixed_options, &[query()], 
true, None).unwrap();
         assert_eq!(
             diskann[0]
                 .as_ref()
@@ -1578,7 +1620,8 @@ mod tests {
         let mut ivf_metadata = metadata;
         ivf_metadata.index_type = IndexType::IvfFlat;
         assert!(prepare_search(&ivf_metadata, &mixed_options, 
&query()).is_err());
-        let ivf = prepare_batch_searches(&ivf_metadata, &mixed_options, 
&[query()], true).unwrap();
+        let ivf =
+            prepare_batch_searches(&ivf_metadata, &mixed_options, &[query()], 
true, None).unwrap();
         assert_eq!(
             ivf[0].as_ref().unwrap().params.configured_ivf_nprobe(),
             Some(4)
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 9917017f..d9889a26 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -2982,6 +2982,15 @@ explicitly with the build procedure. A Rust build plan 
also exposes
 `replacement_messages()` to publish with the completed shards in the same
 snapshot-guarded commit.
 
+For unfiltered L2 searches over centroid-sharded `ivf-flat` or `ivf-pq`,
+automatic probing can choose both widths together. With 64 outer centers,
+an automatic outer width of eight, and Top-K from 10 through 100, the joint
+policy starts with four shards and 16 local lists per shard. Each of those
+four shards must have 64 lists and at least 16 times Top-K vectors. Older
+descriptors use the native shard header to resolve the layout during the
+same index open. Explicit outer or inner widths and filter expansion
+settings use independent probe sizing.
+
 Set `centroid.nprobe` to choose the outer probe width. `ivf.nprobe` controls a
 selected shard's local IVF search, and `diskann.l_search` controls its DiskANN
 search. Automatic cosine and L2 routing can widen the search when necessary.

Reply via email to