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 c4045ac5 [Build] Upgrade paimon-vindex-core to 0.6.0 (#1502)
c4045ac5 is described below
commit c4045ac5623c9cdbc92cb82ae972d987185487d3
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 23 13:15:12 2026 +0800
[Build] Upgrade paimon-vindex-core to 0.6.0 (#1502)
---
Cargo.lock | 4 +-
DEPENDENCIES.rust.tsv | 2 +-
benchmarks/tpcds/DEPENDENCIES.rust.tsv | 2 +-
bindings/c/Cargo.toml | 2 +-
bindings/c/DEPENDENCIES.rust.tsv | 2 +-
bindings/go/DEPENDENCIES.rust.tsv | 2 +-
bindings/python/Cargo.toml | 2 +-
bindings/python/DEPENDENCIES.rust.tsv | 2 +-
crates/integration_tests/DEPENDENCIES.rust.tsv | 2 +-
.../integrations/datafusion/DEPENDENCIES.rust.tsv | 2 +-
crates/paimon-rest-server/DEPENDENCIES.rust.tsv | 2 +-
crates/paimon/Cargo.toml | 2 +-
crates/paimon/DEPENDENCIES.rust.tsv | 2 +-
crates/paimon/src/table/centroid_index.rs | 148 +++++----------------
crates/paimon/src/table/de_vector_read/centroid.rs | 11 +-
.../table/de_vector_read/centroid_joint_tests.rs | 18 ++-
crates/paimon/src/table/index_build/vector.rs | 13 +-
.../table/vindex_index_build_builder/centroid.rs | 39 +++---
crates/paimon/src/vindex/reader.rs | 26 ++--
19 files changed, 108 insertions(+), 175 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index c9e6cf34..6730f1f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5133,9 +5133,9 @@ dependencies = [
[[package]]
name = "paimon-vindex-core"
-version = "0.5.0"
+version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9e7541c9afa7804c8e68c0b7795f05cefa41a6403548a8b86f79088f7045301a"
+checksum = "c17442460f95709968b242a266fa0eb72332f5d8fb4b5412a2e569e9dac3292d"
dependencies = [
"half",
"matrixmultiply",
diff --git a/DEPENDENCIES.rust.tsv b/DEPENDENCIES.rust.tsv
index 22271225..e19f3198 100644
--- a/DEPENDENCIES.rust.tsv
+++ b/DEPENDENCIES.rust.tsv
@@ -426,7 +426,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
[email protected] X
X
diff --git a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
index ddbb27bc..c5ce1c8c 100644
--- a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
+++ b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
@@ -325,7 +325,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
[email protected] X
diff --git a/bindings/c/Cargo.toml b/bindings/c/Cargo.toml
index b82aea27..c582a727 100644
--- a/bindings/c/Cargo.toml
+++ b/bindings/c/Cargo.toml
@@ -52,6 +52,6 @@ base64 = "0.22"
opendal = { package = "opendal-core", version = "0.59.5" }
# Test-only: the vector-search integration tests build a real primary-key
vindex
# IVF-flat ANN segment fixture in-process. Versions match crates/paimon.
-paimon-vindex-core = "0.5.0"
+paimon-vindex-core = "0.6.0"
tempfile = "3"
url = "2.5.2"
diff --git a/bindings/c/DEPENDENCIES.rust.tsv b/bindings/c/DEPENDENCIES.rust.tsv
index bb00f4b5..a8d2bd7a 100644
--- a/bindings/c/DEPENDENCIES.rust.tsv
+++ b/bindings/c/DEPENDENCIES.rust.tsv
@@ -271,7 +271,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/go/DEPENDENCIES.rust.tsv
b/bindings/go/DEPENDENCIES.rust.tsv
index bb00f4b5..a8d2bd7a 100644
--- a/bindings/go/DEPENDENCIES.rust.tsv
+++ b/bindings/go/DEPENDENCIES.rust.tsv
@@ -271,7 +271,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml
index 2ae397ce..a8f80e80 100644
--- a/bindings/python/Cargo.toml
+++ b/bindings/python/Cargo.toml
@@ -38,7 +38,7 @@ datafusion-ffi = { workspace = true }
futures = "0.3"
paimon = { path = "../../crates/paimon", features = ["storage-all",
"internal-api"] }
paimon-datafusion = { path = "../../crates/integrations/datafusion" }
-paimon-vindex-core = "0.5.0"
+paimon-vindex-core = "0.6.0"
pyo3 = { version = "0.29", features = ["abi3-py310", "chrono"] }
roaring = "0.11"
serde_json = "1.0"
diff --git a/bindings/python/DEPENDENCIES.rust.tsv
b/bindings/python/DEPENDENCIES.rust.tsv
index f590f570..0609c369 100644
--- a/bindings/python/DEPENDENCIES.rust.tsv
+++ b/bindings/python/DEPENDENCIES.rust.tsv
@@ -353,7 +353,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
[email protected] X
diff --git a/crates/integration_tests/DEPENDENCIES.rust.tsv
b/crates/integration_tests/DEPENDENCIES.rust.tsv
index 6c120d09..b3513ebd 100644
--- a/crates/integration_tests/DEPENDENCIES.rust.tsv
+++ b/crates/integration_tests/DEPENDENCIES.rust.tsv
@@ -255,7 +255,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
diff --git a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
index 21aa7d64..b985c4ca 100644
--- a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
+++ b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
@@ -365,7 +365,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
index d22c457a..072862f1 100644
--- a/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
+++ b/crates/paimon-rest-server/DEPENDENCIES.rust.tsv
@@ -259,7 +259,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon/Cargo.toml b/crates/paimon/Cargo.toml
index 55bddfe6..0d44eb48 100644
--- a/crates/paimon/Cargo.toml
+++ b/crates/paimon/Cargo.toml
@@ -160,7 +160,7 @@ uuid = { version = "1", features = ["v4"] }
paimon-mosaic-core = "0.3.0"
paimon-ftindex-core = "0.2.0"
tempfile = "3"
-paimon-vindex-core = "0.5.0"
+paimon-vindex-core = "0.6.0"
# Also used by paimon-vindex-core for the single-precision matrix multiply.
matrixmultiply = "0.3.11"
vortex = { version = "0.90.0", features = ["tokio"], optional = true }
diff --git a/crates/paimon/DEPENDENCIES.rust.tsv
b/crates/paimon/DEPENDENCIES.rust.tsv
index c03bf34a..e87ab9c4 100644
--- a/crates/paimon/DEPENDENCIES.rust.tsv
+++ b/crates/paimon/DEPENDENCIES.rust.tsv
@@ -347,7 +347,7 @@ [email protected]
X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
[email protected] X
X
[email protected] X
X
diff --git a/crates/paimon/src/table/centroid_index.rs
b/crates/paimon/src/table/centroid_index.rs
index b8eabb11..f9f65579 100644
--- a/crates/paimon/src/table/centroid_index.rs
+++ b/crates/paimon/src/table/centroid_index.rs
@@ -21,17 +21,14 @@ use super::index_file_path::IndexFileLocation;
use crate::io::{FileIO, FileRead};
use crate::spec::{IndexFileMeta, IndexManifestEntry};
use crate::{Error, Result};
-use paimon_vindex_core::distance::{fvec_l2sqr, fvec_normalize, MetricType};
+use paimon_vindex_core::distance::MetricType;
+use paimon_vindex_core::index::CentroidRouter;
use serde::{Deserialize, Serialize};
-use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
const META_MAGIC: &[u8; 8] = b"PAIMCENT";
const META_HEADER: usize = 22;
-const ROUTER_MAGIC: &[u8; 8] = b"PVROUT01";
-const ROUTER_HEADER: usize = 20;
const MAX_ENVELOPE: usize = 65536;
-const MAX_CENTERS_BYTES: usize = 512 * 1024 * 1024;
pub(super) const EMPTY_SHARD: &[u8] = b"PCEMPTY1";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -301,60 +298,25 @@ struct Envelope<'a> {
model_id: &'a str,
}
+pub(super) fn encode_router_envelope(model_id: &str) -> Result<Vec<u8>> {
+ let header = serde_json::to_vec(&Envelope {
+ version: 1,
+ shard_mode: "centroid-based",
+ model_id,
+ })
+ .map_err(|error| invalid(format!("Cannot encode centroid router envelope:
{error}")))?;
+ let mut bytes = Vec::with_capacity(4 + header.len());
+ bytes.extend((header.len() as u32).to_be_bytes());
+ bytes.extend(&header);
+ Ok(bytes)
+}
+
pub(super) struct Router {
pub(super) metric: MetricType,
- pub(super) dimension: usize,
- centers: Vec<f32>,
+ pub(super) model: CentroidRouter,
}
impl Router {
- pub(super) fn new(metric: MetricType, dimension: usize, centers: Vec<f32>)
-> Result<Self> {
- if dimension == 0
- || dimension > i32::MAX as usize
- || !centers.len().is_multiple_of(dimension)
- || centers.is_empty()
- || centers.len() > MAX_CENTERS_BYTES / 4
- || centers.iter().any(|value| !value.is_finite())
- {
- return Err(invalid("Invalid centroid routing centers or
dimensions"));
- }
- Ok(Self {
- metric,
- dimension,
- centers,
- })
- }
-
- pub(super) fn nlist(&self) -> usize {
- self.centers.len() / self.dimension
- }
-
- pub(super) fn encode(&self, model_id: &str) -> Result<Vec<u8>> {
- let mut bytes = Self::encode_empty(model_id)?;
- bytes.reserve(ROUTER_HEADER + self.centers.len() * 4);
- bytes.extend(ROUTER_MAGIC);
- bytes.extend((self.dimension as u32).to_le_bytes());
- bytes.extend((self.nlist() as u32).to_le_bytes());
- bytes.extend((self.metric as u32).to_le_bytes());
- for center in &self.centers {
- bytes.extend(center.to_le_bytes());
- }
- Ok(bytes)
- }
-
- pub(super) fn encode_empty(model_id: &str) -> Result<Vec<u8>> {
- let header = serde_json::to_vec(&Envelope {
- version: 1,
- shard_mode: "centroid-based",
- model_id,
- })
- .map_err(|error| invalid(format!("Cannot encode centroid router
envelope: {error}")))?;
- let mut bytes = Vec::with_capacity(4 + header.len());
- bytes.extend((header.len() as u32).to_be_bytes());
- bytes.extend(&header);
- Ok(bytes)
- }
-
pub(super) async fn load(
file_io: &FileIO,
table_path: &str,
@@ -367,9 +329,8 @@ impl Router {
let path = IndexFileLocation::Global { table_path }
.resolve(&file.file_name, file.external_path.as_deref());
let size = usize::try_from(file.file_size).unwrap_or_default();
- if !(4 + ROUTER_HEADER..=4 + MAX_ENVELOPE + ROUTER_HEADER +
MAX_CENTERS_BYTES)
- .contains(&size)
- {
+ let max_size = 4 + MAX_ENVELOPE + CentroidRouter::MAX_SERIALIZED_BYTES;
+ if !(4 + CentroidRouter::HEADER_BYTES..=max_size).contains(&size) {
return Err(invalid("Invalid centroid routing file size"));
}
let input = file_io.new_input(&path)?.reader().await?;
@@ -387,7 +348,7 @@ impl Router {
return Err(invalid());
}
let len = read_u32(bytes, 0, true) as usize;
- if len == 0 || len > MAX_ENVELOPE || bytes.len() < 4 + len +
ROUTER_HEADER {
+ if len == 0 || len > MAX_ENVELOPE || bytes.len() < 4 + len {
return Err(invalid());
}
let header: Envelope<'_> =
@@ -396,72 +357,16 @@ impl Router {
if header.version != 1
|| header.shard_mode != "centroid-based"
|| header.model_id != model_id
- || !payload.starts_with(ROUTER_MAGIC)
{
return Err(invalid());
}
- let dimension = read_u32(payload, 8, false) as usize;
- if read_u32(payload, 12, false) as usize != nlist
- || dimension.checked_mul(nlist).and_then(|n| n.checked_mul(4))
- != Some(payload.len() - ROUTER_HEADER)
- {
+ let model =
CentroidRouter::deserialize(payload).map_err(router_error)?;
+ if model.nlist() != nlist {
return Err(invalid());
}
+ // Vector Index 0.6.0 validates the metric in the header but exposes
no getter.
let metric = MetricType::from_code(read_u32(payload, 16,
false)).ok_or_else(invalid)?;
- let centers = payload[ROUTER_HEADER..]
- .as_chunks::<4>()
- .0
- .iter()
- .copied()
- .map(f32::from_le_bytes)
- .collect();
- Self::new(metric, dimension, centers)
- }
-
- fn distances<'a>(
- &'a self,
- vector: &'a [f32],
- ) -> Result<impl Iterator<Item = (usize, f32)> + 'a> {
- if vector.len() != self.dimension || vector.iter().any(|value|
!value.is_finite()) {
- return Err(invalid(format!(
- "Centroid routing expects {} finite coordinates, got {}",
- self.dimension,
- vector.len()
- )));
- }
- let mut point = Cow::Borrowed(vector);
- if self.metric == MetricType::Cosine {
- fvec_normalize(point.to_mut());
- }
- // Like native training, coarse assignment is Euclidean in the metric's
- // training space, including when the local index ranks by inner
product.
- Ok(self
- .centers
- .chunks_exact(self.dimension)
- .enumerate()
- .map(move |(id, center)| (id, fvec_l2sqr(&point, center))))
- }
-
- pub(super) fn nearest(&self, vector: &[f32]) -> Result<Vec<usize>> {
- let mut distances = self.distances(vector)?.collect::<Vec<_>>();
- if distances.iter().any(|(_, distance)| !distance.is_finite()) {
- return Err(invalid("Non-finite centroid distance"));
- }
- distances.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then_with(||
a.0.cmp(&b.0)));
- Ok(distances.into_iter().map(|(id, _)| id).collect())
- }
-
- pub(super) fn assign(&self, vector: &[f32]) -> Result<usize> {
- let mut nearest = (0, f32::INFINITY);
- for (id, distance) in self.distances(vector)? {
- if !distance.is_finite() {
- return Err(invalid("Non-finite centroid distance"));
- }
- if distance < nearest.1 {
- nearest = (id, distance);
- }
- }
- Ok(nearest.0)
+ Ok(Self { metric, model })
}
}
@@ -531,3 +436,10 @@ pub(super) fn invalid(message: impl Into<String>) -> Error
{
source: None,
}
}
+
+pub(super) fn router_error(error: std::io::Error) -> Error {
+ Error::DataInvalid {
+ message: format!("Invalid centroid router: {error}"),
+ source: Some(Box::new(error)),
+ }
+}
diff --git a/crates/paimon/src/table/de_vector_read/centroid.rs
b/crates/paimon/src/table/de_vector_read/centroid.rs
index d78b02d3..0af147b9 100644
--- a/crates/paimon/src/table/de_vector_read/centroid.rs
+++ b/crates/paimon/src/table/de_vector_read/centroid.rs
@@ -264,11 +264,11 @@ pub(super) async fn execute_work(
if work
.queries
.iter()
- .any(|query| query.vector.len() != router.dimension)
+ .any(|query| query.vector.len() != router.model.dimension())
{
return Err(centroid_index::invalid(format!(
"Query vector dimension mismatch: centroid router expects {}",
- router.dimension
+ router.model.dimension()
)));
}
@@ -377,7 +377,7 @@ impl RoutedSearch<'_> {
) -> Result<Vec<ScoredRowIds>> {
let group = self.group;
let router = self.router;
- let nlist = router.nlist();
+ let nlist = router.model.nlist();
let explicit_width = self.explicit_width;
let mut routes = Vec::with_capacity(queries.len());
for search in queries {
@@ -404,7 +404,10 @@ impl RoutedSearch<'_> {
} else if explicit_width.is_none() && router.metric ==
MetricType::InnerProduct {
(0..nlist).collect()
} else {
- router.nearest(&search.vector)?
+ router
+ .model
+ .find_nearest_centroids(&search.vector,
explicit_width.unwrap_or(nlist))
+ .map_err(centroid_index::router_error)?
};
routes.push(Route {
nearest,
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
index 6d3a917c..793ceac9 100644
--- a/crates/paimon/src/table/de_vector_read/centroid_joint_tests.rs
+++ b/crates/paimon/src/table/de_vector_read/centroid_joint_tests.rs
@@ -20,6 +20,7 @@ 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::index::{CentroidRouter, VectorIndexConfig,
VectorIndexTrainer};
use paimon_vindex_core::io::PosWriter;
use paimon_vindex_core::ivfflat::IVFFlatIndex;
use paimon_vindex_core::ivfflat_io::write_ivfflat_index;
@@ -178,13 +179,18 @@ async fn run(
#[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(),
- )
+ let config = VectorIndexConfig::from_options(&HashMap::from([
+ ("index.type".into(), "ivf_flat".into()),
+ ("dimension".into(), "1".into()),
+ ("metric".into(), "l2".into()),
+ ("nlist".into(), "64".into()),
+ ]))
.unwrap();
- let bytes = router.encode("test-router").unwrap();
+ let centers = (0..64).map(|i| i as f32 * 10.0).collect::<Vec<_>>();
+ let training = VectorIndexTrainer::train(config, ¢ers,
centers.len()).unwrap();
+ let router = CentroidRouter::from_training(training).unwrap();
+ let mut bytes =
centroid_index::encode_router_envelope("test-router").unwrap();
+ bytes.extend(router.serialize());
let router_entry = entry(Role::Router(64), bytes.len(), 0, None);
store(&io, &router_entry, bytes).await;
let mut entries = vec![router_entry];
diff --git a/crates/paimon/src/table/index_build/vector.rs
b/crates/paimon/src/table/index_build/vector.rs
index 4b5ae039..fe39b10a 100644
--- a/crates/paimon/src/table/index_build/vector.rs
+++ b/crates/paimon/src/table/index_build/vector.rs
@@ -30,7 +30,9 @@ use arrow_array::RecordBatch;
use arrow_buffer::MutableBuffer;
use futures::TryStreamExt;
use paimon_vindex_core::autotune::default_training_vector_count;
-use paimon_vindex_core::index::{VectorIndexConfig, VectorIndexTrainer,
VectorIndexWriter};
+use paimon_vindex_core::index::{
+ VectorIndexConfig, VectorIndexTrainer, VectorIndexTraining,
VectorIndexWriter,
+};
use paimon_vindex_core::io::PosWriter;
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::Range;
@@ -355,7 +357,8 @@ fn train_and_add_spilled_vectors(
timing_enabled: bool,
) -> std::io::Result<(VectorIndexWriter, Duration, Duration, Duration)> {
let train_start = timing_enabled.then(Instant::now);
- let mut writer = train_spilled_model(&mut raw_file, config, vector_count,
dimension, ratio)?;
+ let training = train_spilled_model(&mut raw_file, config, vector_count,
dimension, ratio)?;
+ let mut writer = VectorIndexWriter::new(training);
let batch_rows = batch_rows(vector_count, dimension)?;
let mut buffer = MutableBuffer::new(checked_std_vector_bytes(batch_rows,
dimension)?);
let train_finish = train_start.map_or(Duration::ZERO, |start|
start.elapsed());
@@ -405,7 +408,7 @@ fn train_spilled_model(
vector_count: usize,
dimension: usize,
ratio: f64,
-) -> std::io::Result<VectorIndexWriter> {
+) -> std::io::Result<VectorIndexTraining> {
let samples =
checked_training_vector_count(vector_count,
ratio).map_err(std::io::Error::other)?;
let batch_rows = batch_rows(vector_count, dimension)?;
@@ -441,7 +444,7 @@ fn train_spilled_model(
"vindex training sample count mismatch",
));
}
- Ok(VectorIndexWriter::new(trainer.finish()?))
+ trainer.finish()
}
/// Keep one pair of files open for all centroids. Each source batch
contributes
@@ -473,7 +476,7 @@ impl SpilledVectors {
&mut self,
config: VectorIndexConfig,
ratio: f64,
- ) -> Result<VectorIndexWriter> {
+ ) -> Result<VectorIndexTraining> {
train_spilled_model(&mut self.raw, config, self.count, self.dimension,
ratio)
.map_err(spill_error)
}
diff --git a/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
b/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
index 3e229662..4335692e 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
@@ -23,7 +23,7 @@ use crate::spec::{
DataEvolutionIndexSourceMeta, FileKind, GlobalIndexMeta, IndexFileMeta,
IndexManifestEntry,
ROW_ID_FIELD_NAME,
};
-use crate::table::centroid_index::{self, Descriptor, Role, Router,
EMPTY_SHARD};
+use crate::table::centroid_index::{self, Descriptor, Role, EMPTY_SHARD};
use crate::table::global_index_build_common::{vector::VectorIndexShard,
GlobalIndexBuildView};
use crate::table::index_build::{
vector::{serialize_writer, VectorSpill},
@@ -34,8 +34,9 @@ use crate::table::partition_filter::PartitionFilter;
use crate::table::{CommitMessage, RowRange, Table};
use crate::vindex::VindexVectorIndexOptions;
use crate::{Error, Result};
+use bytes::Bytes;
use futures::TryStreamExt;
-use paimon_vindex_core::index::{VectorIndexConfig, VectorIndexWriter};
+use paimon_vindex_core::index::{CentroidRouter, VectorIndexConfig,
VectorIndexWriter};
use std::collections::HashMap;
pub(in crate::table) struct CentroidBuildOptions {
@@ -264,17 +265,18 @@ impl VindexIndexBuildBuilder<'_> {
.unwrap_or_default();
let metric = &options.native_options["metric"];
let router_meta = json_options(&options.native_options)?;
- let (nlist, model_file) = if let Some(mut spill) =
spill.finish().await? {
+ let mut model_file =
vec![centroid_index::encode_router_envelope(model_id)?.into()];
+ let nlist = if let Some(mut spill) = spill.finish().await? {
let config = centroid.router_config(options,
spill.vector_count())?;
let ratio = options.train_sample_ratio;
- let dimension = options.dimension();
let (router, mut routed) = tokio::task::spawn_blocking(move || {
- let VectorIndexWriter::IvfFlat(flat) =
spill.train_router(config, ratio)? else {
- unreachable!("router configuration uses IVF-FLAT");
- };
- let router =
- Router::new(flat.metric, dimension,
flat.quantizer_centroids().to_vec())?;
- let routed = spill.route(router.nlist(), |vector|
router.assign(vector))?;
+ let router =
CentroidRouter::from_training(spill.train_router(config, ratio)?)
+ .map_err(centroid_index::router_error)?;
+ let routed = spill.route(router.nlist(), |vector| {
+ router
+ .assign_centroid(vector)
+ .map_err(centroid_index::router_error)
+ })?;
Ok::<_, Error>((router, routed))
})
.await
@@ -362,14 +364,15 @@ impl VindexIndexBuildBuilder<'_> {
},
count,
index,
- EMPTY_SHARD.to_vec(),
+ vec![Bytes::from_static(EMPTY_SHARD)],
)
.await?,
);
}
- (router.nlist(), router.encode(model_id)?)
+ model_file.push(router.serialize().into());
+ router.nlist()
} else {
- (0, Router::encode_empty(model_id)?)
+ 0
};
files.push(
self.write_centroid_file(
@@ -400,7 +403,7 @@ impl VindexIndexBuildBuilder<'_> {
descriptor: Descriptor<'_>,
row_count: i64,
writer: Option<VectorIndexWriter>,
- bytes: Vec<u8>,
+ parts: Vec<Bytes>,
) -> Result<IndexFileMeta> {
let prefix = format!("vector-{}", self.index_type);
let file_name = if matches!(descriptor.role, Role::Router(_)) {
@@ -417,7 +420,13 @@ impl VindexIndexBuildBuilder<'_> {
.write(self.table, |output| async move {
match writer {
Some(writer) => serialize_writer(writer, output).await?,
- None => output.write(bytes.into()).await?,
+ None => {
+ let mut output = output.writer().await?;
+ for part in parts {
+ output.write(part).await?;
+ }
+ output.close().await?;
+ }
}
Ok(Some(IndexPayload {
row_count,
diff --git a/crates/paimon/src/vindex/reader.rs
b/crates/paimon/src/vindex/reader.rs
index 73cb6ec8..b40f0dd4 100644
--- a/crates/paimon/src/vindex/reader.rs
+++ b/crates/paimon/src/vindex/reader.rs
@@ -1224,17 +1224,19 @@ mod tests {
query_for_cluster(0, 10)
}
+ fn uncached_ivf_flat_options() -> HashMap<String, String> {
+ // Disable partition caching so read counts measure reuse within a
batch.
+ HashMap::from([
+ (NPROBE_PARAMETER.to_string(), "1".to_string()),
+ (READER_MEMORY_BUDGET_PARAMETER.to_string(), "0".to_string()),
+ ])
+ }
+
async fn tracked_batch_search(
index: Bytes,
query_count: usize,
) -> (Vec<Option<HashMap<u64, f32>>>, usize) {
- tracked_batch_search_with_options(
- index,
- query_count,
- HashMap::from([(NPROBE_PARAMETER.to_string(), "1".to_string())]),
- 1,
- )
- .await
+ tracked_batch_search_with_options(index, query_count,
uncached_ivf_flat_options(), 1).await
}
async fn tracked_batch_search_with_options(
@@ -1951,7 +1953,7 @@ mod tests {
async fn batch_search_reuses_probed_lists_and_avoids_full_file_read() {
let index = build_ivf_flat_index();
let batch_index = index.clone();
- let options = HashMap::from([(NPROBE_PARAMETER.to_string(),
"1".to_string())]);
+ let options = uncached_ivf_flat_options();
let search = query();
let scalar_tracking = TrackingIndexRead::new(index.clone());
@@ -2025,7 +2027,7 @@ mod tests {
async fn filtered_batch_matches_scalar_searches_and_reuses_probed_lists() {
let index = build_ivf_flat_index();
let batch_index = index.clone();
- let options = HashMap::from([(NPROBE_PARAMETER.to_string(),
"1".to_string())]);
+ let options = uncached_ivf_flat_options();
let mut include_row_ids = roaring::RoaringTreemap::new();
for row_id in (0..256).step_by(16) {
include_row_ids.insert(row_id);
@@ -2132,10 +2134,8 @@ mod tests {
rq_bits: None,
diskann: None,
};
- let options = HashMap::from([
- (NPROBE_PARAMETER.to_string(), "1".to_string()),
- ("global-index.thread-num".to_string(), "1".to_string()),
- ]);
+ let mut options = uncached_ivf_flat_options();
+ options.insert("global-index.thread-num".to_string(), "1".to_string());
let prepared = prepare_search(&metadata, &options, &query())
.unwrap()
.unwrap();