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-vector-index.git


The following commit(s) were added to refs/heads/main by this push:
     new e794291  feat: add a portable centroid router for independently built 
vector shards (#131)
e794291 is described below

commit e794291e492984d13303854dfdf60015ea283bd3
Author: Jingsong Lee <[email protected]>
AuthorDate: Wed Nov 18 22:59:21 2026 +0800

    feat: add a portable centroid router for independently built vector shards 
(#131)
---
 .github/workflows/release-java.yml                 |   7 +-
 core/STORAGE_FORMAT.md                             |  19 ++
 core/src/index.rs                                  |  88 +++++++-
 core/src/index/router.rs                           | 219 ++++++++++++++++++++
 core/src/ivfflat.rs                                |   4 +
 core/src/ivfflat_io.rs                             |   2 +-
 docs/api.html                                      |  23 +++
 .../apache/paimon/index/vector/CentroidRouter.java |  93 +++++++++
 .../paimon/index/vector/VectorIndexNative.java     |  21 ++
 .../paimon/index/vector/VectorIndexTrainer.java    |  20 ++
 .../vector/VectorIndexCentroidShardingTest.java    | 108 ++++++++++
 .../vector/VectorIndexNativeValidationTest.java    |   1 +
 jni/src/lib.rs                                     |  64 ++++--
 jni/src/router.rs                                  | 221 +++++++++++++++++++++
 14 files changed, 869 insertions(+), 21 deletions(-)

diff --git a/.github/workflows/release-java.yml 
b/.github/workflows/release-java.yml
index 9758fc1..69db493 100644
--- a/.github/workflows/release-java.yml
+++ b/.github/workflows/release-java.yml
@@ -239,7 +239,10 @@ jobs:
           )"
           test -n "$jar_file"
           mkdir -p smoke-classes
-          javac -cp "$jar_file" -d smoke-classes \
-            
java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeLoaderSmokeTest.java
+          javac -cp "$jar_file" -sourcepath java/src/test/java -d 
smoke-classes \
+            
java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeLoaderSmokeTest.java
 \
+            
java/src/test/java/org/apache/paimon/index/vector/VectorIndexCentroidShardingTest.java
           java -cp "$jar_file${{ matrix.classpath_separator }}smoke-classes" \
             org.apache.paimon.index.vector.VectorIndexNativeLoaderSmokeTest
+          java -cp "$jar_file${{ matrix.classpath_separator }}smoke-classes" \
+            org.apache.paimon.index.vector.VectorIndexCentroidShardingTest
diff --git a/core/STORAGE_FORMAT.md b/core/STORAGE_FORMAT.md
index 2ef8098..194909d 100644
--- a/core/STORAGE_FORMAT.md
+++ b/core/STORAGE_FORMAT.md
@@ -456,3 +456,22 @@ normally use their own per-dimension residual bounds. A 
reader validates all
 offsets, counts, encoded-ID sizes, and SQ bounds before exposing the index.
 Putting blocked codes first lets the reader retain the list payload allocation
 as the scan buffer after decoding and truncating the trailing ID section.
+
+## Centroid routing model
+
+A router can select files containing any supported local index type. The 
routing
+payload is independent of the standard index file inside each populated shard.
+The file mapping and the global row IDs belong to the caller.
+
+| Offset | Size | Value |
+| ---: | ---: | --- |
+| 0 | 8 | ASCII `PVROUT01` |
+| 8 | 4 | Vector dimension, little-endian `u32` |
+| 12 | 4 | Number of routing centers, little-endian `u32` |
+| 16 | 4 | Metric code, as in the index header |
+| 20 | `4 * dimension * centers` | Center coordinates, little-endian `f32`, 
grouped by center ID |
+
+Dimension and center count are positive. The reader checks the metadata size 
bound,
+the exact payload length, the metric code and finite center coordinates. Row
+assignment and query routing use squared L2 distances to these centers, with 
query
+and training vectors normalized for cosine. Ties prefer the lower center ID.
diff --git a/core/src/index.rs b/core/src/index.rs
index b742b31..715b050 100644
--- a/core/src/index.rs
+++ b/core/src/index.rs
@@ -63,6 +63,9 @@ use roaring::RoaringTreemap;
 use std::collections::{HashMap, HashSet};
 use std::io::{self, Cursor};
 
+mod router;
+pub use router::CentroidRouter;
+
 /// Default ratio between the serialized PQ code and the raw `f32` vector.
 ///
 /// At 8 bits per subquantizer this resolves to one PQ subquantizer per four
@@ -1369,6 +1372,30 @@ impl VectorIndexTrainer {
         self.writer.dimension()
     }
 
+    /// Input ordinals retained by streaming this many vectors, in final 
reservoir slot order.
+    /// Call on a fresh trainer. Planning uses no vectors and leaves the 
trainer untouched.
+    pub fn plan_training_sample(&self, vector_count: usize) -> 
io::Result<Vec<usize>> {
+        if self.training_vectors_seen != 0 {
+            return Err(invalid_input(
+                "plan the training sample before adding vectors",
+            ));
+        }
+        let limit = self.training_sample_limit;
+        let mut ordinals: Vec<_> = (0..vector_count.min(limit)).collect();
+        let mut rng = self.training_rng.clone();
+        for ordinal in limit..vector_count {
+            if let Some(slot) = Self::replacement_slot(&mut rng, ordinal, 
limit) {
+                ordinals[slot] = ordinal;
+            }
+        }
+        Ok(ordinals)
+    }
+
+    fn replacement_slot(rng: &mut StdRng, ordinal: usize, limit: usize) -> 
Option<usize> {
+        let slot = rng.gen_range(0..=ordinal);
+        (slot < limit).then_some(slot)
+    }
+
     pub fn add_training_vectors(mut self, data: &[f32], n: usize) -> 
io::Result<Self> {
         self.add_training_vectors_mut(data, n)?;
         Ok(self)
@@ -1387,12 +1414,13 @@ impl VectorIndexTrainer {
             let stream_index = self.training_vectors_seen + batch_index;
             if stream_index < self.training_sample_limit {
                 self.training_data.extend_from_slice(vector);
-            } else {
-                let replacement = 
self.training_rng.gen_range(0..=stream_index);
-                if replacement < self.training_sample_limit {
-                    let start = replacement * dimension;
-                    self.training_data[start..start + 
dimension].copy_from_slice(vector);
-                }
+            } else if let Some(slot) = Self::replacement_slot(
+                &mut self.training_rng,
+                stream_index,
+                self.training_sample_limit,
+            ) {
+                let start = slot * dimension;
+                self.training_data[start..start + 
dimension].copy_from_slice(vector);
             }
         }
         self.training_vector_count = 
training_vectors_seen.min(self.training_sample_limit);
@@ -1451,6 +1479,8 @@ impl VectorIndexWriter {
                 use_approximate_coarse_assignment,
                 ..
             } => {
+                // Check the on-disk metadata bound before allocating per-list 
state.
+                crate::ivfflat_io::flat_metadata_bytes(dimension, nlist)?;
                 let mut index = IVFFlatIndex::new(dimension, nlist, metric);
                 
index.set_approximate_coarse_assignment(use_approximate_coarse_assignment);
                 Self::IvfFlat(index)
@@ -3264,6 +3294,43 @@ mod tests {
         }
     }
 
+    #[test]
+    fn 
planned_samples_match_streaming_and_can_be_replayed_for_each_index_type() {
+        for kind in ["ivf_flat", "ivf_sq", "ivf_pq", "ivf_rq", "diskann"] {
+            let mut options = HashMap::from([
+                ("index.type".to_string(), kind.to_string()),
+                ("dimension".into(), "4".into()),
+                ("nlist".into(), "4".into()),
+                ("metric".into(), "l2".into()),
+            ]);
+            if kind == "diskann" {
+                options.remove("nlist");
+                options.insert("diskann.seed".into(), "93".into());
+            }
+            let config = VectorIndexConfig::from_options(&options).unwrap();
+            let mut trainer = VectorIndexTrainer::new(config.clone()).unwrap();
+            let n = trainer.training_sample_limit * 2 + 37;
+            let data: Vec<_> = (0..n * 4).map(|i| (i % 2017) as f32).collect();
+            let ordinals = trainer.plan_training_sample(n).unwrap();
+            let sample: Vec<_> = ordinals
+                .iter()
+                .flat_map(|&i| &data[i * 4..i * 4 + 4])
+                .copied()
+                .collect();
+            for chunk in data.chunks(67 * 4) {
+                trainer
+                    .add_training_vectors_mut(chunk, chunk.len() / 4)
+                    .unwrap();
+            }
+            assert_eq!(sample, trainer.training_data, "{kind}");
+            let replay = VectorIndexTrainer::new(config)
+                .unwrap()
+                .add_training_vectors(&sample, ordinals.len())
+                .unwrap();
+            assert_eq!(replay.training_data, trainer.training_data, "{kind}");
+        }
+    }
+
     #[test]
     fn unified_search_stats_cover_all_families_calls_filters_and_storage() {
         let pool = rayon::ThreadPoolBuilder::new()
@@ -4862,7 +4929,16 @@ mod tests {
         };
 
         let mut whole = VectorIndexTrainer::new(config()).unwrap();
+        let positions = whole.plan_training_sample(count).unwrap();
+        assert_eq!(positions, whole.plan_training_sample(count).unwrap());
+        let selected: Vec<_> = positions
+            .iter()
+            .flat_map(|&i| &data[i * dimension..(i + 1) * dimension])
+            .copied()
+            .collect();
         whole.add_training_vectors_mut(&data, count).unwrap();
+        assert_eq!(selected, whole.training_data);
+        assert!(whole.plan_training_sample(count).is_err());
         let mut batched = VectorIndexTrainer::new(config()).unwrap();
         for vectors in data.chunks(137 * dimension) {
             batched
diff --git a/core/src/index/router.rs b/core/src/index/router.rs
new file mode 100644
index 0000000..bf59010
--- /dev/null
+++ b/core/src/index/router.rs
@@ -0,0 +1,219 @@
+// 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::distance::{fvec_l2sqr, fvec_normalize};
+use crate::kmeans::find_topk_checked;
+use std::borrow::Cow;
+
+const MAGIC: &[u8; 8] = b"PVROUT01";
+const HEADER: usize = 20;
+
+/// Exact coarse routing shared by all shard index types. Contains no shard 
training state.
+pub struct CentroidRouter {
+    dimension: usize,
+    metric: MetricType,
+    centers: Vec<f32>,
+}
+
+impl CentroidRouter {
+    fn payload_len(d: usize, nlist: usize) -> io::Result<usize> {
+        if d == 0 || nlist == 0 || d > i32::MAX as usize || nlist > i32::MAX 
as usize {
+            return Err(invalid_input("invalid centroid router dimensions"));
+        }
+        // Bound both center storage and the per-list allocations of an 
IVF-FLAT trainer.
+        crate::ivfflat_io::flat_metadata_bytes(d, nlist)?;
+        Ok(d * nlist * 4)
+    }
+
+    pub fn dimension(&self) -> usize {
+        self.dimension
+    }
+
+    pub fn nlist(&self) -> usize {
+        self.centers.len() / self.dimension
+    }
+
+    pub fn serialize(&self) -> Vec<u8> {
+        let mut bytes = Vec::with_capacity(HEADER + self.centers.len() * 4);
+        bytes.extend_from_slice(MAGIC);
+        bytes.extend_from_slice(&(self.dimension as u32).to_le_bytes());
+        bytes.extend_from_slice(&(self.nlist() as u32).to_le_bytes());
+        bytes.extend_from_slice(&(self.metric as u32).to_le_bytes());
+        for v in &self.centers {
+            bytes.extend_from_slice(&v.to_le_bytes());
+        }
+        bytes
+    }
+
+    /// Largest supported serialized router, including its fixed header.
+    pub const MAX_SERIALIZED_BYTES: usize =
+        HEADER + crate::index_io_util::MAX_READER_METADATA_BYTES / 2;
+    pub const HEADER_BYTES: usize = HEADER;
+
+    /// Check the fixed header and return the exact serialized size before 
allocating its body.
+    pub fn serialized_size(header: &[u8]) -> io::Result<usize> {
+        let (dimension, nlist, _) = Self::header(header)?;
+        Ok(HEADER + Self::payload_len(dimension, nlist)?)
+    }
+
+    fn header(bytes: &[u8]) -> io::Result<(usize, usize, MetricType)> {
+        if bytes.len() < HEADER || &bytes[..8] != MAGIC {
+            return Err(invalid_input("invalid centroid router header"));
+        }
+        let number = |offset| u32::from_le_bytes(bytes[offset..offset + 
4].try_into().unwrap());
+        let dimension = number(8) as usize;
+        let nlist = number(12) as usize;
+        let metric = MetricType::from_code(number(16))
+            .ok_or_else(|| invalid_input("invalid routing metric"))?;
+        Ok((dimension, nlist, metric))
+    }
+
+    pub fn deserialize(bytes: &[u8]) -> io::Result<Self> {
+        let (dimension, nlist, metric) = Self::header(bytes)?;
+        if Self::payload_len(dimension, nlist)? != bytes.len() - HEADER {
+            return Err(invalid_input("invalid centroid router length"));
+        }
+        let centers = bytes[HEADER..]
+            .chunks_exact(4)
+            .map(|b| f32::from_le_bytes(b.try_into().unwrap()))
+            .collect();
+        Self::from_centers(dimension, metric, centers)
+    }
+
+    fn from_centers(dimension: usize, metric: MetricType, centers: Vec<f32>) 
-> io::Result<Self> {
+        if centers.iter().any(|v| !v.is_finite()) {
+            return Err(invalid_input("non-finite routing centroid"));
+        }
+        Ok(Self {
+            dimension,
+            metric,
+            centers,
+        })
+    }
+
+    /// Resolve outer routing with the same automatic width policy as ordinary 
IVF search.
+    pub fn resolve_nprobe(
+        &self,
+        params: VectorSearchParams,
+        total_vectors: usize,
+        matching_vectors: Option<usize>,
+    ) -> io::Result<usize> {
+        params.validate()?;
+        params.resolve_ivf_nprobe(self.nlist(), total_vectors, 
matching_vectors)
+    }
+
+    fn routing_vector<'a>(&self, query: &'a [f32]) -> io::Result<Cow<'a, 
[f32]>> {
+        let d = self.dimension();
+        validate_query(query, d)?;
+        let mut processed = Cow::Borrowed(query);
+        if self.metric == MetricType::Cosine {
+            fvec_normalize(processed.to_mut());
+        }
+        if let Cow::Owned(ref values) = processed {
+            validate_query(values, d)?;
+        }
+        Ok(processed)
+    }
+
+    /// Exact coarse routing, for a query in the same metric space as training.
+    pub fn find_nearest_centroids(&self, query: &[f32], nprobe: usize) -> 
io::Result<Vec<usize>> {
+        validate_positive(nprobe, "nprobe")?;
+        let processed = self.routing_vector(query)?;
+        find_topk_checked(
+            &processed,
+            &self.centers,
+            self.nlist(),
+            self.dimension(),
+            nprobe,
+        )
+        .map(|centroids| {
+            centroids
+                .into_iter()
+                .map(|(_, centroid)| centroid)
+                .collect()
+        })
+        .map_err(|_| invalid_input("non-finite coarse distance"))
+    }
+
+    pub fn assign_centroid(&self, vector: &[f32]) -> io::Result<usize> {
+        let point = self.routing_vector(vector)?;
+        let mut nearest = 0;
+        let mut best = f32::INFINITY;
+        for (id, center) in 
self.centers.chunks_exact(self.dimension()).enumerate() {
+            let distance = fvec_l2sqr(&point, center);
+            if !distance.is_finite() {
+                return Err(invalid_input("non-finite coarse distance"));
+            }
+            if distance < best {
+                best = distance;
+                nearest = id;
+            }
+        }
+        Ok(nearest)
+    }
+
+    /// Take the coarse centers from a trained IVF-FLAT model.
+    pub fn from_training(training: VectorIndexTraining) -> io::Result<Self> {
+        let VectorIndexWriter::IvfFlat(flat) = training.inner else {
+            return Err(invalid_input(
+                "a centroid router requires IVF-FLAT training",
+            ));
+        };
+        Self::payload_len(flat.d, flat.nlist)?;
+        Self::from_centers(flat.d, flat.metric, 
flat.into_quantizer_centroids())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn router_payload_is_independent_of_shard_type_and_rejects_corruption() {
+        // Frozen routing format: two 2D cosine centers, including a tie on 
[1, 1].
+        let mut bytes = b"PVROUT01".to_vec();
+        for n in [2u32, 2, 2] {
+            bytes.extend(n.to_le_bytes());
+        }
+        for f in [1.0f32, 0.0, 0.0, 1.0] {
+            bytes.extend(f.to_le_bytes());
+        }
+        let router = CentroidRouter::deserialize(&bytes).unwrap();
+        assert_eq!(router.serialize(), bytes);
+        assert_eq!(router.assign_centroid(&[0., 30.]).unwrap(), 1);
+        assert_eq!(router.assign_centroid(&[1., 1.]).unwrap(), 0);
+        assert_eq!(router.find_nearest_centroids(&[1., 1.], 9).unwrap(), [0, 
1]);
+        assert!(router.assign_centroid(&[f32::NAN, 0.]).is_err());
+        assert!(router.find_nearest_centroids(&[0.], 1).is_err());
+        assert!(router.find_nearest_centroids(&[1., 0.], 0).is_err());
+        for (offset, word) in [
+            (0, 0u32),
+            (8, 0),
+            (12, u32::MAX),
+            (16, 7),
+            (20, f32::INFINITY.to_bits()),
+        ] {
+            let mut bad = bytes.clone();
+            bad[offset..offset + 4].copy_from_slice(&word.to_le_bytes());
+            assert!(CentroidRouter::deserialize(&bad).is_err());
+        }
+        assert!(CentroidRouter::deserialize(&bytes[..bytes.len() - 
1]).is_err());
+        bytes.push(0);
+        assert!(CentroidRouter::deserialize(&bytes).is_err());
+    }
+}
diff --git a/core/src/ivfflat.rs b/core/src/ivfflat.rs
index 889e233..ea52d3f 100644
--- a/core/src/ivfflat.rs
+++ b/core/src/ivfflat.rs
@@ -48,6 +48,10 @@ impl IVFFlatIndex {
         &self.quantizer_centroids
     }
 
+    pub(crate) fn into_quantizer_centroids(self) -> Vec<f32> {
+        self.quantizer_centroids
+    }
+
     /// Enables automatic Vamana coarse assignment for large centroid matrices.
     /// Disable it to keep vector assignment exact.
     pub(crate) fn set_approximate_coarse_assignment(&mut self, enabled: bool) {
diff --git a/core/src/ivfflat_io.rs b/core/src/ivfflat_io.rs
index 4d3c476..46baec9 100644
--- a/core/src/ivfflat_io.rs
+++ b/core/src/ivfflat_io.rs
@@ -334,7 +334,7 @@ struct FlatListRead {
     offset: u64,
 }
 
-fn flat_metadata_bytes(d: usize, nlist: usize) -> io::Result<usize> {
+pub(crate) fn flat_metadata_bytes(d: usize, nlist: usize) -> io::Result<usize> 
{
     let bytes = (|| {
         let wire = nlist
             .checked_mul(d)?
diff --git a/docs/api.html b/docs/api.html
index a7c56df..845d333 100644
--- a/docs/api.html
+++ b/docs/api.html
@@ -306,6 +306,29 @@ VectorSearchParams params =
           <p>Staging avoids one very large Java <code>float[]</code> and its 
array-length limit. Native reservoir sampling bounds retained training rows, 
but streaming creation still needs concrete <code>dimension</code> and either 
concrete <code>nlist</code> or <code>expected-vector-count</code>.</p>
         </section>
 
+        <section class="article-section" id="centroid-sharding">
+          <h2>Centroid routing for local indexes</h2>
+          <p>Use one coarse routing model for IVF-FLAT, IVF-SQ, IVF-PQ, IVF-RQ 
or DiskANN. The caller trains and broadcasts the centers, shuffles by center ID 
and builds an ordinary index from the vectors and absolute row IDs in each 
populated shard.</p>
+<pre><code>Map&lt;String, String&gt; options = new HashMap&lt;&gt;();
+options.put("dimension", "128");
+options.put("metric", "l2");
+options.put("nlist", "64");
+options.put("index.type", "ivf_flat");
+byte[] payload;
+try (VectorIndexTrainer trainer = VectorIndexTrainer.create(options);
+     VectorIndexTraining coarse = trainer.addTrainingVectors(samples, 
sampleCount).finishTraining();
+     CentroidRouter router = CentroidRouter.fromTraining(coarse)) {
+    payload = router.serialize();
+}
+try (CentroidRouter router = CentroidRouter.deserialize(payload)) {
+    int shuffleKey = router.assignCentroid(vector);
+    int[] filesToProbe = router.findNearestCentroids(query, 8);
+}</code></pre>
+          <p>Call <code>planTrainingSample(vectorCount)</code> on a fresh 
IVF-FLAT trainer with the outer routing options for every shard type. It 
returns zero-based input ordinals in reservoir slot order. A distributed job 
can read those rows from its splits and feed them back in that order to 
reproduce streaming IVF-FLAT training. DiskANN’s seed and memory budget apply 
when training PQ and building the graph inside each shard. The serialized 
router contains the metric, dimension and co [...]
+          <p>In each shard, use <code>VectorIndexTrainer.create</code>, 
<code>VectorIndexWriter.addVectors</code> and <code>writeIndex</code>. Use the 
standard <code>VectorIndexReader</code> on the selected files and merge results 
by score. The caller chooses the outer probe count explicitly or with 
<code>router.resolveNprobe</code>. Local IVF probes and DiskANN graph search 
width are independent. Keep the router and its center-to-file mapping in the 
same index generation.</p>
+          <p>The corresponding Rust entry points are 
<code>VectorIndexTrainer::new</code>, 
<code>CentroidRouter::from_training</code>, and 
<code>CentroidRouter::{serialize, deserialize, assign_centroid, 
find_nearest_centroids}</code>. The wire format is documented in <a 
href="../core/STORAGE_FORMAT.md">STORAGE_FORMAT.md</a>.</p>
+        </section>
+
         <section class="article-section" id="python">
           <h2>Python</h2>
           <p>The C++, Java, and Python Readers serialize operations on one 
native handle across threads. Calling another method on that same handle from 
its input/output callback is rejected as reentrant—even when DiskANN invokes 
the callback from a native query worker—instead of deadlocking or re-entering a 
mutable native handle; use a separate handle if a callback needs vector-index 
work. The Python package loads <code>libpaimon_vindex_ffi</code> with ctypes. A 
single search returns on [...]
diff --git 
a/java/src/main/java/org/apache/paimon/index/vector/CentroidRouter.java 
b/java/src/main/java/org/apache/paimon/index/vector/CentroidRouter.java
new file mode 100644
index 0000000..12836c7
--- /dev/null
+++ b/java/src/main/java/org/apache/paimon/index/vector/CentroidRouter.java
@@ -0,0 +1,93 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.paimon.index.vector;
+
+/** Portable, read-only coarse centers shared by local IVF and DiskANN 
indexes. */
+public final class CentroidRouter implements AutoCloseable {
+    /** Consumes ordinary IVF-FLAT training and takes ownership of its coarse 
centers. */
+    public static CentroidRouter fromTraining(VectorIndexTraining coarse) {
+        return new 
CentroidRouter(VectorIndexNative.routerFromTraining(coarse.takeNativePointer()));
+    }
+
+    private long nativePtr;
+
+    CentroidRouter(long nativePtr) {
+        this.nativePtr = nativePtr;
+    }
+
+    public synchronized byte[] serialize() {
+        return VectorIndexNative.serializeRouter(requireOpen());
+    }
+
+    /** Upper bound for validating stored payload lengths before reading into 
memory. */
+    public static int maxSerializedBytes() {
+        return VectorIndexNative.maxRouterBytes();
+    }
+
+    public static CentroidRouter deserialize(byte[] payload) {
+        if (payload == null) {
+            throw new NullPointerException("payload");
+        }
+        return new 
CentroidRouter(VectorIndexNative.deserializeRouter(payload));
+    }
+
+    public synchronized int nlist() {
+        return VectorIndexNative.routerNlist(requireOpen());
+    }
+
+    public synchronized int assignCentroid(float[] vector) {
+        if (vector == null) {
+            throw new NullPointerException("vector");
+        }
+        return VectorIndexNative.assignCentroid(requireOpen(), vector);
+    }
+
+    public synchronized int[] findNearestCentroids(float[] query, int nprobe) {
+        if (query == null) {
+            throw new NullPointerException("query");
+        }
+        if (nprobe <= 0) {
+            throw new IllegalArgumentException("nprobe must be positive");
+        }
+        return VectorIndexNative.findNearestCentroids(requireOpen(), query, 
nprobe);
+    }
+
+    /** A matchingVectors value of -1 means no row-ID filter. */
+    public synchronized int resolveNprobe(
+            VectorSearchParams params, long totalVectors, long 
matchingVectors) {
+        if (params == null) {
+            throw new NullPointerException("params");
+        }
+        return VectorIndexNative.routerNprobe(requireOpen(), params, 
totalVectors, matchingVectors);
+    }
+
+    @Override
+    public synchronized void close() {
+        if (nativePtr != 0L) {
+            VectorIndexNative.freeRouter(nativePtr);
+            nativePtr = 0L;
+        }
+    }
+
+    private long requireOpen() {
+        if (nativePtr == 0L) {
+            throw new IllegalStateException("CentroidRouter is closed");
+        }
+        return nativePtr;
+    }
+}
diff --git 
a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java 
b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
index cea5c96..38dcd25 100644
--- a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
+++ b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexNative.java
@@ -45,6 +45,8 @@ final class VectorIndexNative {
 
     static native long createTrainer(String[] optionKeys, String[] 
optionValues);
 
+    static native long[] trainerPlanTrainingSample(long ptr, long vectorCount);
+
     static native int trainerDimension(long ptr);
 
     static native void trainerAddTrainingVectors(long ptr, float[] data, int 
n);
@@ -55,6 +57,25 @@ final class VectorIndexNative {
 
     static native long createWriter(long trainingPtr);
 
+    static native byte[] serializeRouter(long ptr);
+
+    static native int maxRouterBytes();
+
+    static native long deserializeRouter(byte[] payload);
+
+    static native int routerNlist(long ptr);
+
+    static native long routerFromTraining(long ptr);
+
+    static native void freeRouter(long ptr);
+
+    static native int routerNprobe(
+            long ptr, VectorSearchParams params, long totalVectors, long 
matchingVectors);
+
+    static native int assignCentroid(long ptr, float[] vector);
+
+    static native int[] findNearestCentroids(long ptr, float[] query, int 
nprobe);
+
     static native int writerDimension(long ptr);
 
     static native void addVectors(long ptr, long[] ids, float[] data, int n);
diff --git 
a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexTrainer.java 
b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexTrainer.java
index fef3101..d3ebfb3 100644
--- a/java/src/main/java/org/apache/paimon/index/vector/VectorIndexTrainer.java
+++ b/java/src/main/java/org/apache/paimon/index/vector/VectorIndexTrainer.java
@@ -94,6 +94,26 @@ public final class VectorIndexTrainer implements 
AutoCloseable {
         }
     }
 
+    /**
+     * Returns zero-based input ordinals in the exact order the streaming 
reservoir would retain
+     * them. Given the same input and options, adding just these rows in 
returned order produces the
+     * same training sample. Call before adding vectors. Repeated calls leave 
the trainer unchanged.
+     * Planning takes O(vectorCount) time and O(retained rows) space and reads 
no vector data.
+     */
+    public long[] planTrainingSample(long vectorCount) {
+        if (vectorCount < 0) {
+            throw new IllegalArgumentException("vectorCount must be 
nonnegative");
+        }
+        synchronized (nativeHandleLock) {
+            enterNativeHandle();
+            try {
+                return 
VectorIndexNative.trainerPlanTrainingSample(requireOpen(), vectorCount);
+            } finally {
+                exitNativeHandle();
+            }
+        }
+    }
+
     public VectorIndexTrainer addTrainingVectors(float[] data, int 
vectorCount) {
         if (data == null) {
             throw new NullPointerException("data");
diff --git 
a/java/src/test/java/org/apache/paimon/index/vector/VectorIndexCentroidShardingTest.java
 
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexCentroidShardingTest.java
new file mode 100644
index 0000000..8ae047c
--- /dev/null
+++ 
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexCentroidShardingTest.java
@@ -0,0 +1,108 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.paimon.index.vector;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import 
org.apache.paimon.index.vector.VectorIndexNativeValidationTest.ByteArrayPositionOutputStream;
+import 
org.apache.paimon.index.vector.VectorIndexNativeValidationTest.ByteArraySeekableInputStream;
+
+/** Exercise the external router and standard shard API through the packaged 
JNI library. */
+public final class VectorIndexCentroidShardingTest {
+    public static void main(String[] args) {
+        VectorIndexNativeLoaderSmokeTest.configureExternalLibrary(args);
+        run();
+    }
+
+    static void run() {
+        float[] rows = new float[256 * 4];
+        for (int i = 0; i < 256; i++) {
+            Arrays.fill(rows, i * 4, i * 4 + 4, (i / 64) * 100 + (i % 64) * 
0.1f);
+        }
+        Map<String, String> options = new HashMap<>();
+        options.put("dimension", "4");
+        options.put("metric", "l2");
+        options.put("nlist", "4");
+        Map<String, String> localOptions = new HashMap<>(options);
+        localOptions.put("index.type", "ivf_sq");
+        try (VectorIndexTraining local = 
VectorIndexTrainer.train(localOptions, rows, 256)) {
+            try {
+                CentroidRouter.fromTraining(local).close();
+                throw new AssertionError("expected IVF-FLAT coarse training");
+            } catch (RuntimeException expected) {
+                check(expected.getMessage().contains("IVF-FLAT"), "coarse 
training validation");
+            }
+        }
+        byte[] payload;
+        options.put("index.type", "ivf_flat");
+        try (VectorIndexTrainer trainer = VectorIndexTrainer.create(options);
+                VectorIndexTraining coarse = trainer.addTrainingVectors(rows, 
256).finishTraining();
+                CentroidRouter router = CentroidRouter.fromTraining(coarse)) {
+            payload = router.serialize();
+        }
+        try (CentroidRouter router = CentroidRouter.deserialize(payload)) {
+            check(payload.length < CentroidRouter.maxSerializedBytes(), 
"router size bound");
+            float[] query = Arrays.copyOf(rows, 4);
+            int selected = router.assignCentroid(query);
+            check(router.findNearestCentroids(query, 1)[0] == selected, 
"routing consistency");
+            check(router.resolveNprobe(VectorSearchParams.ivf(1, 2), 256, -1) 
== 2, "outer width");
+            long[] ids = new long[256];
+            float[] vectors = new float[rows.length];
+            int count = 0;
+            for (int i = 0; i < 256; i++) {
+                float[] row = Arrays.copyOfRange(rows, i * 4, i * 4 + 4);
+                if (selected == router.assignCentroid(row)) {
+                    ids[count] = (1L << 35) + i;
+                    System.arraycopy(row, 0, vectors, count * 4, 4);
+                    count++;
+                }
+            }
+            check(count > 1 && count < 256, "selected local training set");
+            float[] local = Arrays.copyOf(vectors, count * 4);
+            for (String kind : new String[] {"ivf_flat", "ivf_sq", "ivf_pq", 
"ivf_rq", "diskann"}) {
+                Map<String, String> shard = new HashMap<>();
+                shard.put("index.type", kind);
+                shard.put("dimension", "4");
+                shard.put("metric", "l2");
+                if (!"diskann".equals(kind)) {
+                    shard.put("nlist", "2");
+                }
+                ByteArrayPositionOutputStream output = new 
ByteArrayPositionOutputStream();
+                try (VectorIndexTraining training = 
VectorIndexTrainer.train(shard, local, count);
+                        VectorIndexWriter writer = new 
VectorIndexWriter(training)) {
+                    writer.addVectors(Arrays.copyOf(ids, count), local, count);
+                    writer.writeIndex(output);
+                }
+                try (VectorIndexReader reader =
+                        new VectorIndexReader(new 
ByteArraySeekableInputStream(output.toByteArray()))) {
+                    VectorSearchParams params = "diskann".equals(kind)
+                            ? VectorSearchParams.diskAnn(count, 256) : 
VectorSearchParams.ivf(count, 2);
+                    long[] hits = reader.search(query, params).ids();
+                    Arrays.sort(hits);
+                    check(Arrays.equals(hits, Arrays.copyOf(ids, count)), kind 
+ " absolute row IDs");
+                }
+            }
+        }
+    }
+
+    private static void check(boolean condition, String message) {
+        if (!condition) { throw new AssertionError(message); }
+    }
+}
diff --git 
a/java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeValidationTest.java
 
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeValidationTest.java
index 83050ae..74bb74e 100644
--- 
a/java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeValidationTest.java
+++ 
b/java/src/test/java/org/apache/paimon/index/vector/VectorIndexNativeValidationTest.java
@@ -34,6 +34,7 @@ public class VectorIndexNativeValidationTest {
         testWriterValidationComesFromCore();
         testWriterRejectsNonFiniteValues();
         testStagedTrainingRoundtrip();
+        VectorIndexCentroidShardingTest.run();
         testStagedTrainingStateValidation();
         testReaderValidationComesFromCore();
         testReaderRejectsNonFiniteQueries();
diff --git a/jni/src/lib.rs b/jni/src/lib.rs
index a815579..1a351f5 100644
--- a/jni/src/lib.rs
+++ b/jni/src/lib.rs
@@ -17,6 +17,7 @@
 
 mod log_bridge;
 mod range;
+mod router;
 mod stream;
 
 use jni::objects::{JByteArray, JClass, JFloatArray, JLongArray, JObject, 
JValue};
@@ -146,11 +147,11 @@ fn deref_reader(ptr: jlong) -> Option<&'static mut 
VectorIndexReader<JniSeekable
     }
 }
 
-fn build_config_from_options(
+fn read_build_options(
     env: &mut JNIEnv,
     keys: jobjectArray,
     values: jobjectArray,
-) -> Option<VectorIndexConfig> {
+) -> Option<HashMap<String, String>> {
     let keys = unsafe { jni::objects::JObjectArray::from_raw(keys) };
     let values = unsafe { jni::objects::JObjectArray::from_raw(values) };
     let key_len = match env.get_array_length(&keys) {
@@ -211,13 +212,7 @@ fn build_config_from_options(
         options.insert(key, value);
     }
 
-    match VectorIndexConfig::from_options(&options) {
-        Ok(config) => Some(config),
-        Err(e) => {
-            throw_and_return::<()>(env, &format!("invalid vector index 
options: {}", e));
-            None
-        }
-    }
+    Some(options)
 }
 
 fn java_string(env: &mut JNIEnv, object: JObject) -> Result<String, String> {
@@ -497,11 +492,16 @@ pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_cre
     values: jobjectArray,
 ) -> jlong {
     jni_call(env, |env| {
-        let config = match build_config_from_options(env, keys, values) {
-            Some(config) => config,
+        let options = match read_build_options(env, keys, values) {
+            Some(options) => options,
             None => return 0,
         };
-
+        let config = match VectorIndexConfig::from_options(&options) {
+            Ok(config) => config,
+            Err(e) => {
+                return throw_and_return(env, &format!("invalid vector index 
options: {}", e))
+            }
+        };
         let trainer = match VectorIndexTrainer::new(config) {
             Ok(trainer) => trainer,
             Err(e) => return throw_and_return(env, &format!("create trainer: 
{}", e)),
@@ -529,6 +529,46 @@ pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_tra
     })
 }
 
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_trainerPlanTrainingSample(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+    count: jlong,
+) -> jobject {
+    jni_call(env, |env| {
+        let Ok(count) = usize::try_from(count) else {
+            return throw_and_return(env, "invalid training vector count");
+        };
+        let Some(handle) = deref_trainer(ptr) else {
+            return throw_and_return(env, "null trainer pointer");
+        };
+        let positions = match handle.trainer_mut().and_then(|trainer| {
+            trainer
+                .plan_training_sample(count)
+                .map_err(|error| error.to_string())
+        }) {
+            Ok(positions) => positions,
+            Err(error) => return throw_and_return(env, &error),
+        };
+        let Ok(length) = jint::try_from(positions.len()) else {
+            return throw_and_return(env, "sample exceeds Java array capacity");
+        };
+        let array = match env.new_long_array(length) {
+            Ok(array) => array,
+            Err(error) => return throw_and_return(env, &error.to_string()),
+        };
+        // Chunk the conversion so the JNI bridge does not duplicate the full 
plan.
+        for (chunk, positions) in positions.chunks(4096).enumerate() {
+            let values: Vec<jlong> = positions.iter().map(|&i| i as 
jlong).collect();
+            if let Err(error) = env.set_long_array_region(&array, (chunk * 
4096) as jint, &values) {
+                return throw_and_return(env, &error.to_string());
+            }
+        }
+        array.into_raw()
+    })
+}
+
 #[no_mangle]
 pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_trainerAddTrainingVectors(
     env: JNIEnv,
diff --git a/jni/src/router.rs b/jni/src/router.rs
new file mode 100644
index 0000000..9ab4be4
--- /dev/null
+++ b/jni/src/router.rs
@@ -0,0 +1,221 @@
+// 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 paimon_vindex_core::index::CentroidRouter;
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_routerNprobe(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+    params: JObject,
+    total_vectors: jlong,
+    matching_vectors: jlong,
+) -> jint {
+    jni_call(env, |env| {
+        if total_vectors < 0 || matching_vectors < -1 {
+            return throw_and_return(env, "invalid vector count");
+        }
+        let params = match search_params(env, params) {
+            Ok(p) => p,
+            Err(e) => return throw_and_return(env, &e),
+        };
+        match router(ptr).and_then(|t| {
+            t.resolve_nprobe(
+                params,
+                total_vectors as usize,
+                if matching_vectors < 0 {
+                    None
+                } else {
+                    Some(matching_vectors as usize)
+                },
+            )
+            .map_err(|e| e.to_string())
+        }) {
+            Ok(nprobe) => nprobe as jint,
+            Err(e) => throw_and_return(env, &e),
+        }
+    })
+}
+
+fn router(ptr: jlong) -> Result<&'static CentroidRouter, String> {
+    if ptr == 0 {
+        return Err("null router pointer".into());
+    }
+    Ok(unsafe { &*(ptr as *const CentroidRouter) })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_serializeRouter(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+) -> jobject {
+    jni_call(env, |env| {
+        let bytes = match router(ptr).map(CentroidRouter::serialize) {
+            Ok(bytes) => bytes,
+            Err(e) => return throw_and_return(env, &e),
+        };
+        match env.byte_array_from_slice(&bytes) {
+            Ok(array) => array.into_raw(),
+            Err(e) => throw_and_return(env, &e.to_string()),
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_deserializeRouter(
+    env: JNIEnv,
+    _class: JClass,
+    payload: JByteArray,
+) -> jlong {
+    jni_call(env, |env| {
+        let size = match env.get_array_length(&payload) {
+            Ok(size) => size as usize,
+            Err(e) => return throw_and_return(env, &e.to_string()),
+        };
+        let mut header = [0i8; CentroidRouter::HEADER_BYTES];
+        if 
!(header.len()..=CentroidRouter::MAX_SERIALIZED_BYTES).contains(&size) {
+            return throw_and_return(env, "invalid centroid router length");
+        }
+        if let Err(e) = env.get_byte_array_region(&payload, 0, &mut header) {
+            return throw_and_return(env, &e.to_string());
+        }
+        match CentroidRouter::serialized_size(&header.map(|v| v as u8)) {
+            Ok(expected) if expected == size => {}
+            Ok(_) => return throw_and_return(env, "invalid centroid router 
length"),
+            Err(e) => return throw_and_return(env, &e.to_string()),
+        }
+        let bytes = match read_byte_array(env, payload) {
+            Ok(bytes) => bytes,
+            Err(e) => return throw_and_return(env, &e),
+        };
+        match CentroidRouter::deserialize(&bytes) {
+            Ok(t) => Box::into_raw(Box::new(t)) as jlong,
+            Err(e) => throw_and_return(env, &e.to_string()),
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_routerNlist(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+) -> jint {
+    jni_call(env, |env| match router(ptr).map(CentroidRouter::nlist) {
+        Ok(nlist) => nlist as jint,
+        Err(e) => throw_and_return(env, &e),
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_assignCentroid(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+    vector: JFloatArray,
+) -> jint {
+    jni_call(env, |env| {
+        let vector = match read_float_array(env, &vector, "vector") {
+            Ok(vector) => vector,
+            Err(e) => return throw_and_return(env, &e),
+        };
+        match router(ptr).and_then(|t| t.assign_centroid(&vector).map_err(|e| 
e.to_string())) {
+            Ok(centroid) => centroid as jint,
+            Err(e) => throw_and_return(env, &e),
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_findNearestCentroids(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+    query: JFloatArray,
+    nprobe: jint,
+) -> jobject {
+    jni_call(env, |env| {
+        if nprobe <= 0 {
+            return throw_and_return(env, "nprobe must be positive");
+        }
+        let query = match read_float_array(env, &query, "query") {
+            Ok(q) => q,
+            Err(e) => return throw_and_return(env, &e),
+        };
+        let centroids = match router(ptr).and_then(|t| {
+            t.find_nearest_centroids(&query, nprobe as usize)
+                .map_err(|e| e.to_string())
+        }) {
+            Ok(c) => c.into_iter().map(|c| c as jint).collect::<Vec<_>>(),
+            Err(e) => return throw_and_return(env, &e),
+        };
+        let array = match env.new_int_array(centroids.len() as jint) {
+            Ok(a) => a,
+            Err(e) => return throw_and_return(env, &e.to_string()),
+        };
+        match env.set_int_array_region(&array, 0, &centroids) {
+            Ok(()) => array.into_raw(),
+            Err(e) => throw_and_return(env, &e.to_string()),
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_routerFromTraining(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+) -> jlong {
+    jni_call(env, |env| {
+        if ptr == 0 {
+            return throw_and_return(env, "null training pointer");
+        }
+        let mut handle = unsafe { Box::from_raw(ptr as *mut 
JniVectorIndexTraining) };
+        match handle.take().and_then(|training| {
+            CentroidRouter::from_training(training).map_err(|error| 
error.to_string())
+        }) {
+            Ok(router) => Box::into_raw(Box::new(router)) as jlong,
+            Err(error) => throw_and_return(env, &error),
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_freeRouter(
+    env: JNIEnv,
+    _class: JClass,
+    ptr: jlong,
+) {
+    jni_call_void(env, |_env| {
+        if ptr != 0 {
+            unsafe {
+                drop(Box::from_raw(ptr as *mut CentroidRouter));
+            }
+        }
+    })
+}
+
+#[no_mangle]
+pub extern "system" fn 
Java_org_apache_paimon_index_vector_VectorIndexNative_maxRouterBytes(
+    _env: JNIEnv,
+    _class: JClass,
+) -> jint {
+    CentroidRouter::MAX_SERIALIZED_BYTES as jint
+}

Reply via email to