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 fc931574 [core] Validate Data Evolution scalar indexes using build
schema metadata (#1495)
fc931574 is described below
commit fc931574d6c2905634d9c0602016669da3cb7428
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 22 20:51:17 2026 +0800
[core] Validate Data Evolution scalar indexes using build schema metadata
(#1495)
---
.../paimon/src/spec/data_evolution_index_source.rs | 78 +++++-
crates/paimon/src/table/de_vector_scan.rs | 3 +
.../src/table/full_text_index_build_builder.rs | 13 +-
.../src/table/full_text_search_builder/filter.rs | 9 +
.../paimon/src/table/global_index_build_common.rs | 57 +++--
crates/paimon/src/table/global_index_schema.rs | 168 ++++++-------
crates/paimon/src/table/index_build/rtree.rs | 5 +-
crates/paimon/src/table/index_file_path.rs | 28 +--
.../src/table/sorted_global_index_build_builder.rs | 49 +++-
.../sorted_global_index_build_builder/writer.rs | 14 +-
.../src/table/table_commit/auto_index/planning.rs | 18 +-
.../table/table_commit/auto_index_tests/schema.rs | 262 +++++++++++++--------
crates/paimon/src/table/table_scan.rs | 4 +-
.../table/vindex_index_build_builder/centroid.rs | 34 ++-
.../vindex_index_build_builder/centroid_tests.rs | 16 ++
.../src/table/vindex_index_build_builder/writer.rs | 14 +-
16 files changed, 482 insertions(+), 290 deletions(-)
diff --git a/crates/paimon/src/spec/data_evolution_index_source.rs
b/crates/paimon/src/spec/data_evolution_index_source.rs
index 510888dd..7855e894 100644
--- a/crates/paimon/src/spec/data_evolution_index_source.rs
+++ b/crates/paimon/src/spec/data_evolution_index_source.rs
@@ -22,28 +22,47 @@ use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataEvolutionIndexSourceMeta {
scan_snapshot_id: i64,
+ source_schema_id: i64,
}
impl DataEvolutionIndexSourceMeta {
+ pub const UNKNOWN_SCHEMA_ID: i64 = -1;
+
const MAGIC: [u8; 4] = *b"DEIX";
- const VERSION: i32 = 1;
+ const LEGACY_VERSION: i32 = 1;
+ const VERSION: i32 = 2;
pub fn new(scan_snapshot_id: i64) -> Result<Self> {
+ Self::new_with_schema_id(scan_snapshot_id, Self::UNKNOWN_SCHEMA_ID)
+ }
+
+ pub fn new_with_schema_id(scan_snapshot_id: i64, source_schema_id: i64) ->
Result<Self> {
if scan_snapshot_id <= 0 {
return Err(invalid("Scan snapshot id must be positive."));
}
- Ok(Self { scan_snapshot_id })
+ if source_schema_id < Self::UNKNOWN_SCHEMA_ID {
+ return Err(invalid("Source schema id must be -1 or
non-negative."));
+ }
+ Ok(Self {
+ scan_snapshot_id,
+ source_schema_id,
+ })
}
pub fn scan_snapshot_id(&self) -> i64 {
self.scan_snapshot_id
}
+ pub fn source_schema_id(&self) -> i64 {
+ self.source_schema_id
+ }
+
pub fn serialize(&self) -> Vec<u8> {
- let mut bytes = Vec::with_capacity(16);
+ let mut bytes = Vec::with_capacity(24);
bytes.extend_from_slice(&Self::MAGIC);
bytes.extend_from_slice(&Self::VERSION.to_be_bytes());
bytes.extend_from_slice(&self.scan_snapshot_id.to_be_bytes());
+ bytes.extend_from_slice(&self.source_schema_id.to_be_bytes());
bytes
}
@@ -52,16 +71,26 @@ impl DataEvolutionIndexSourceMeta {
}
pub fn deserialize(bytes: &[u8]) -> Result<Self> {
- if bytes.len() != 16 || !Self::is_data_evolution_meta(Some(bytes)) {
+ if bytes.len() < 16 || !Self::is_data_evolution_meta(Some(bytes)) {
return Err(invalid("Invalid data-evolution index source
metadata."));
}
let version = i32::from_be_bytes(bytes[4..8].try_into().unwrap());
- if version != Self::VERSION {
- return Err(invalid(format!(
- "Unsupported data-evolution index source version: {version}."
- )));
- }
- Self::new(i64::from_be_bytes(bytes[8..16].try_into().unwrap()))
+ let source_schema_id = match (version, bytes.len()) {
+ (Self::LEGACY_VERSION, 16) => Self::UNKNOWN_SCHEMA_ID,
+ (Self::VERSION, 24) =>
i64::from_be_bytes(bytes[16..24].try_into().unwrap()),
+ (Self::LEGACY_VERSION | Self::VERSION, _) => {
+ return Err(invalid(
+ "Invalid data-evolution index source metadata length.",
+ ));
+ }
+ _ => {
+ return Err(invalid(format!(
+ "Unsupported data-evolution index source version:
{version}."
+ )));
+ }
+ };
+ let scan_snapshot_id =
i64::from_be_bytes(bytes[8..16].try_into().unwrap());
+ Self::new_with_schema_id(scan_snapshot_id, source_schema_id)
}
}
@@ -78,14 +107,16 @@ mod tests {
#[test]
fn java_wire_format_and_invalid_frames() {
- let java = [0x44, 0x45, 0x49, 0x58, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
42];
- let source = DataEvolutionIndexSourceMeta::new(42).unwrap();
+ let java = [
+ 0x44, 0x45, 0x49, 0x58, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 42, 0, 0,
0, 0, 0, 0, 0, 7,
+ ];
+ let source = DataEvolutionIndexSourceMeta::new_with_schema_id(42,
7).unwrap();
assert_eq!(source.serialize(), java);
assert_eq!(
DataEvolutionIndexSourceMeta::deserialize(&java).unwrap(),
source
);
- for length in 0..16 {
+ for length in 0..java.len() {
assert!(DataEvolutionIndexSourceMeta::deserialize(&java[..length]).is_err());
}
for offset in [0, 7, 15] {
@@ -96,9 +127,30 @@ mod tests {
let mut trailing = java.to_vec();
trailing.push(0);
assert!(DataEvolutionIndexSourceMeta::deserialize(&trailing).is_err());
+ let mut invalid_schema = java;
+ invalid_schema[16..].copy_from_slice(&(-2i64).to_be_bytes());
+
assert!(DataEvolutionIndexSourceMeta::deserialize(&invalid_schema).is_err());
assert!(!DataEvolutionIndexSourceMeta::is_data_evolution_meta(None));
assert!(!DataEvolutionIndexSourceMeta::is_data_evolution_meta(Some(
&[0, 0, 0, 1]
)));
}
+
+ #[test]
+ fn legacy_source_metadata_decodes_to_unknown_schema() {
+ let legacy = [0x44, 0x45, 0x49, 0x58, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
42];
+ let source =
DataEvolutionIndexSourceMeta::deserialize(&legacy).unwrap();
+ assert_eq!(source.scan_snapshot_id(), 42);
+ assert_eq!(
+ source.source_schema_id(),
+ DataEvolutionIndexSourceMeta::UNKNOWN_SCHEMA_ID
+ );
+ let unknown = source.serialize();
+ assert_eq!(&unknown[4..8], &2i32.to_be_bytes());
+ assert_eq!(&unknown[16..], &(-1i64).to_be_bytes());
+ assert_eq!(
+ DataEvolutionIndexSourceMeta::deserialize(&unknown).unwrap(),
+ source
+ );
+ }
}
diff --git a/crates/paimon/src/table/de_vector_scan.rs
b/crates/paimon/src/table/de_vector_scan.rs
index ce44454c..868039bd 100644
--- a/crates/paimon/src/table/de_vector_scan.rs
+++ b/crates/paimon/src/table/de_vector_scan.rs
@@ -328,6 +328,9 @@ impl Scan for DeVectorScan {
}
plan.index_entries = entries;
}
+ plan.index_entries =
super::global_index_schema::GlobalIndexSchema::new(&plan.table)
+ .filter_entries(plan.index_entries)
+ .await;
}
if let Some(timing) = &mut plan.timing {
timing.manifest = manifest_start.map_or(Duration::ZERO, |start|
start.elapsed());
diff --git a/crates/paimon/src/table/full_text_index_build_builder.rs
b/crates/paimon/src/table/full_text_index_build_builder.rs
index 019008e6..351cbf7c 100644
--- a/crates/paimon/src/table/full_text_index_build_builder.rs
+++ b/crates/paimon/src/table/full_text_index_build_builder.rs
@@ -40,7 +40,7 @@ use crate::table::index_build::{
full_text::{self, full_text_config, native_full_text_options,
serialize_index_meta},
IndexFileWriter,
};
-use crate::table::index_file_path::IndexFileLocation;
+use crate::table::index_file_path::{new_global_index_file_name,
IndexFileLocation};
use crate::table::{CommitMessage, DataSplitBuilder, RowRange, Table};
use crate::{Error, Result};
use std::collections::HashMap;
@@ -216,17 +216,18 @@ impl<'a> FullTextIndexBuildBuilder<'a> {
index_field_id,
extra_field_ids: None,
source_meta: Some(
-
crate::spec::DataEvolutionIndexSourceMeta::new(shard.snapshot_id)?.serialize(),
+ crate::spec::DataEvolutionIndexSourceMeta::new_with_schema_id(
+ shard.snapshot_id,
+ self.table.schema().id(),
+ )?
+ .serialize(),
),
index_meta: None,
};
IndexFileWriter::new(
self.table,
FULL_TEXT_GLOBAL_INDEX_TYPE,
- crate::table::global_index_schema::index_file_name(
- FULL_TEXT_GLOBAL_INDEX_TYPE,
- self.table.schema().id(),
- ),
+ new_global_index_file_name(FULL_TEXT_GLOBAL_INDEX_TYPE),
IndexFileLocation::Global {
table_path: self.table.location().trim_end_matches('/'),
},
diff --git a/crates/paimon/src/table/full_text_search_builder/filter.rs
b/crates/paimon/src/table/full_text_search_builder/filter.rs
index ad605e4a..050309fd 100644
--- a/crates/paimon/src/table/full_text_search_builder/filter.rs
+++ b/crates/paimon/src/table/full_text_search_builder/filter.rs
@@ -19,6 +19,7 @@
use super::*;
use crate::table::global_index_scanner::GlobalIndexScanner;
+use crate::table::global_index_schema::GlobalIndexSchema;
use crate::table::global_index_search_filter::matching_row_ids_for_filter;
use crate::table::global_index_types::normalize_queryable_global_index_type;
@@ -134,6 +135,14 @@ pub(super) async fn matching_indexed_rows(
})
.cloned()
.collect::<Vec<_>>();
+ let scalar_entries = match evaluation.table {
+ Some(table) => {
+ GlobalIndexSchema::new(table)
+ .filter_entries(scalar_entries)
+ .await
+ }
+ None => scalar_entries,
+ };
let mut fields = HashSet::new();
field_ids(filter, evaluation.schema_fields, &mut fields);
let detail = if mode == GlobalIndexSearchMode::Detail {
diff --git a/crates/paimon/src/table/global_index_build_common.rs
b/crates/paimon/src/table/global_index_build_common.rs
index 35d77e54..655b4c07 100644
--- a/crates/paimon/src/table/global_index_build_common.rs
+++ b/crates/paimon/src/table/global_index_build_common.rs
@@ -26,7 +26,8 @@
//! each builder.
use crate::spec::{
- DataField, FileKind, IndexManifest, IndexManifestEntry, ManifestEntry,
Predicate, Snapshot,
+ DataField, FileKind, GlobalIndexMeta, IndexManifest, IndexManifestEntry,
ManifestEntry,
+ Predicate, Snapshot,
};
use crate::table::{merge_row_ranges, RowRange, Table};
use crate::{Error, Result};
@@ -277,31 +278,39 @@ fn ranges_overlap(a_start: i64, a_end: i64, b_start: i64,
b_end: i64) -> bool {
a_start <= b_end && b_start <= a_end
}
+pub(super) fn matching_index_meta<'a>(
+ entry: &'a IndexManifestEntry,
+ index_type: &str,
+ index_field_id: i32,
+ extra_field_ids: Option<&[i32]>,
+) -> Option<&'a GlobalIndexMeta> {
+ if entry.kind != FileKind::Add || entry.index_file.index_type !=
index_type {
+ return None;
+ }
+ entry.index_file.global_index_meta.as_ref().filter(|meta| {
+ meta.index_field_id == index_field_id
+ && same_extra_field_ids(
+
super::centroid_index::index_identity_extra_fields(&entry.index_file),
+ extra_field_ids,
+ )
+ })
+}
+
/// Row ranges already covered by `index_type` global-index files for
/// `index_field_id` (and matching `extra_field_ids`). Mirrors Java
/// `GlobalIndexBuilderUtils.indexedRowRanges`.
-pub(crate) fn indexed_row_ranges(
- entries: &[IndexManifestEntry],
+pub(crate) fn indexed_row_ranges<'a>(
+ entries: impl IntoIterator<Item = &'a IndexManifestEntry>,
index_type: &str,
index_field_id: i32,
extra_field_ids: Option<&[i32]>,
) -> Vec<RowRange> {
let mut ranges = Vec::new();
for entry in entries {
- if entry.kind != FileKind::Add || entry.index_file.index_type !=
index_type {
- continue;
- }
- let Some(meta) = &entry.index_file.global_index_meta else {
+ let Some(meta) = matching_index_meta(entry, index_type,
index_field_id, extra_field_ids)
+ else {
continue;
};
- if meta.index_field_id != index_field_id
- || !same_extra_field_ids(
-
super::centroid_index::index_identity_extra_fields(&entry.index_file),
- extra_field_ids,
- )
- {
- continue;
- }
ranges.push(RowRange::new(meta.row_range_start, meta.row_range_end));
}
merge_row_ranges(ranges)
@@ -313,28 +322,18 @@ pub(crate) fn indexed_row_ranges(
/// `indexed_row_ranges` and Java `GlobalIndexIdentifier` -- so a different
index
/// type (or different `extra_field_ids`) on the same field coexists. Two files
/// of the same identity with overlapping ranges are still rejected.
-pub(crate) fn validate_existing_index_overlap(
- entries: &[IndexManifestEntry],
+pub(crate) fn validate_existing_index_overlap<'a>(
+ entries: impl IntoIterator<Item = &'a IndexManifestEntry>,
index_type: &str,
index_field_id: i32,
extra_field_ids: Option<&[i32]>,
planned: &[RowRange],
) -> Result<()> {
for entry in entries {
- if entry.kind != FileKind::Add || entry.index_file.index_type !=
index_type {
- continue;
- }
- let Some(meta) = &entry.index_file.global_index_meta else {
+ let Some(meta) = matching_index_meta(entry, index_type,
index_field_id, extra_field_ids)
+ else {
continue;
};
- if meta.index_field_id != index_field_id
- || !same_extra_field_ids(
-
super::centroid_index::index_identity_extra_fields(&entry.index_file),
- extra_field_ids,
- )
- {
- continue;
- }
if planned
.iter()
.any(|r| ranges_overlap(meta.row_range_start, meta.row_range_end,
r.from(), r.to()))
diff --git a/crates/paimon/src/table/global_index_schema.rs
b/crates/paimon/src/table/global_index_schema.rs
index bdedb9f1..ac712fb5 100644
--- a/crates/paimon/src/table/global_index_schema.rs
+++ b/crates/paimon/src/table/global_index_schema.rs
@@ -15,117 +15,103 @@
// specific language governing permissions and limitations
// under the License.
-//! Prove the logical field type of a global payload before reusing its
coverage.
-//!
-//! Native scalar keys and full-text tokens do not record their logical source
-//! type. New file names identify the actual builder schema, which can differ
-//! from its captured data snapshot.
-//! Java opens manifest file names unchanged, so no native or manifest format
-//! changes are needed. Legacy payloads require an unchanged complete history.
+//! Check Data Evolution scalar index key types against the build schema.
-use crate::spec::DataField;
+use super::global_index_types::normalize_queryable_global_index_type;
+use crate::spec::{DataEvolutionIndexSourceMeta, IndexFileMeta,
IndexManifestEntry, TableSchema};
use crate::table::Table;
+use std::collections::hash_map::Entry;
use std::collections::HashMap;
+use std::sync::Arc;
-pub(super) fn index_file_name(index_type: &str, schema_id: i64) -> String {
- format!(
- "{index_type}-global-index-schema-{schema_id}-{}.index",
- uuid::Uuid::new_v4()
- )
-}
-
-enum BuildSchema {
- Tagged(i64),
- Legacy,
- Invalid,
-}
-
-fn build_schema(file_name: &str, index_type: &str) -> BuildSchema {
- let prefix = format!("{index_type}-global-index-schema-");
- let Some(tag) = file_name.strip_prefix(&prefix) else {
- return BuildSchema::Legacy;
- };
- let Some((id, uuid)) = tag.split_once('-') else {
- return BuildSchema::Invalid;
- };
- let Some(id) = id.parse::<i64>().ok().filter(|id| *id >= 0) else {
- return BuildSchema::Invalid;
- };
- if uuid
- .strip_suffix(".index")
- .and_then(|uuid| uuid::Uuid::parse_str(uuid).ok())
- .is_none()
- {
- return BuildSchema::Invalid;
- }
- BuildSchema::Tagged(id)
-}
+const UNKNOWN_SCHEMA_ID: i64 = DataEvolutionIndexSourceMeta::UNKNOWN_SCHEMA_ID;
-/// One definition and maintenance round share successful and failed lookups.
-/// In particular, a legacy history is not scanned once per payload file.
+/// One query or build shares its source schema loads and per-field checks.
pub(super) struct GlobalIndexSchema<'a> {
table: &'a Table,
- field: &'a DataField,
- schemas: HashMap<i64, bool>,
- legacy: Option<bool>,
+ source_schemas: HashMap<i64, Option<Arc<TableSchema>>>,
+ field_compatibility: HashMap<(i64, i32), bool>,
}
impl<'a> GlobalIndexSchema<'a> {
- pub(super) fn new(table: &'a Table, field: &'a DataField) -> Self {
+ pub(super) fn new(table: &'a Table) -> Self {
Self {
table,
- field,
- schemas: HashMap::new(),
- legacy: None,
+ source_schemas: HashMap::new(),
+ field_compatibility: HashMap::new(),
}
}
- pub(super) async fn compatible(&mut self, file_name: &str, index_type:
&str) -> bool {
- match build_schema(file_name, index_type) {
- BuildSchema::Tagged(id) => self.schema_matches(id).await,
- BuildSchema::Invalid => false,
- BuildSchema::Legacy => {
- if let Some(compatible) = self.legacy {
- return compatible;
- }
- let current = self.table.schema().id();
- let mut compatible = current >= 0;
- for id in 0..=current {
- if !self.schema_matches(id).await {
- compatible = false;
- break;
- }
- }
- self.legacy = Some(compatible);
- compatible
+ pub(super) async fn filter_entries(
+ &mut self,
+ entries: Vec<IndexManifestEntry>,
+ ) -> Vec<IndexManifestEntry> {
+ let mut compatible = Vec::with_capacity(entries.len());
+ for entry in entries {
+ if self.compatible(&entry.index_file).await {
+ compatible.push(entry);
}
}
+ compatible
}
- async fn schema_matches(&mut self, id: i64) -> bool {
- if let Some(&compatible) = self.schemas.get(&id) {
- return compatible;
+ pub(super) async fn compatible(&mut self, file: &IndexFileMeta) -> bool {
+ if !self.table.schema().core_options().data_evolution_enabled()
+ ||
normalize_queryable_global_index_type(&file.index_type).is_none()
+ {
+ return true;
}
- let compatible = if id == self.table.schema().id() {
- // Includes catalog-resolved schemas without filesystem metadata.
- true
- } else {
- self.table
- .schema_manager()
- .schema(id)
- .await
- .ok()
- .is_some_and(|schema| {
- schema.id() == id
- && schema.fields().iter().any(|field| {
- field.id() == self.field.id()
- && field
- .data_type()
-
.equals_ignore_nullable(self.field.data_type())
- })
- })
+ let Some(meta) = &file.global_index_meta else {
+ // The scanner reports missing index metadata.
+ return true;
};
- self.schemas.insert(id, compatible);
- compatible
+ let source_schema_id = match meta.source_meta.as_deref() {
+ Some(bytes) if
DataEvolutionIndexSourceMeta::is_data_evolution_meta(Some(bytes)) => {
+ match DataEvolutionIndexSourceMeta::deserialize(bytes) {
+ Ok(source) => source.source_schema_id(),
+ Err(_) => return false,
+ }
+ }
+ _ => UNKNOWN_SCHEMA_ID,
+ };
+ let read_schema = self.table.schema();
+ let source_fields =
+ if source_schema_id == UNKNOWN_SCHEMA_ID || source_schema_id ==
read_schema.id() {
+ None
+ } else {
+ if let Entry::Vacant(entry) =
self.source_schemas.entry(source_schema_id) {
+ entry.insert(
+ self.table
+ .schema_manager()
+ .schema(source_schema_id)
+ .await
+ .ok()
+ .filter(|schema| schema.id() == source_schema_id),
+ );
+ }
+ let Some(schema) = &self.source_schemas[&source_schema_id]
else {
+ return false;
+ };
+ Some(schema.fields())
+ };
+ std::iter::once(meta.index_field_id)
+ .chain(meta.extra_field_ids.iter().flatten().copied())
+ .all(|field_id| {
+ *self
+ .field_compatibility
+ .entry((source_schema_id, field_id))
+ .or_insert_with(|| {
+ let Some(field) = read_schema.fields().iter().find(|f|
f.id() == field_id)
+ else {
+ return false;
+ };
+ source_fields.is_none_or(|fields| {
+ fields.iter().any(|source| {
+ source.id() == field_id
+ &&
source.data_type().equals_ignore_nullable(field.data_type())
+ })
+ })
+ })
+ })
}
}
diff --git a/crates/paimon/src/table/index_build/rtree.rs
b/crates/paimon/src/table/index_build/rtree.rs
index 46e278b4..3afb1d3d 100644
--- a/crates/paimon/src/table/index_build/rtree.rs
+++ b/crates/paimon/src/table/index_build/rtree.rs
@@ -20,8 +20,7 @@ use super::{error, IndexFileWriter};
use crate::io::FileWrite;
use crate::rtree::{RTreeIndexOptions, RTreeIndexWriter, RTreeOutput};
use crate::spec::{GlobalIndexMeta, IndexFileMeta};
-use crate::table::global_index_schema::index_file_name;
-use crate::table::index_file_path::IndexFileLocation;
+use crate::table::index_file_path::{new_global_index_file_name,
IndexFileLocation};
use crate::table::{ArrowRecordBatchStream, RowRange, Table};
use crate::{Error, Result};
use arrow_array::{Array, BinaryArray, Int64Array};
@@ -37,7 +36,7 @@ struct ShardOutput<'a> {
#[async_trait::async_trait]
impl RTreeOutput for &mut ShardOutput<'_> {
async fn create(&mut self) -> io::Result<(String, Box<dyn FileWrite>)> {
- let name = index_file_name("rtree", self.table.schema().id());
+ let name = new_global_index_file_name("rtree");
let file = IndexFileWriter::new(
self.table,
"rtree",
diff --git a/crates/paimon/src/table/index_file_path.rs
b/crates/paimon/src/table/index_file_path.rs
index 0b740385..0df2fd24 100644
--- a/crates/paimon/src/table/index_file_path.rs
+++ b/crates/paimon/src/table/index_file_path.rs
@@ -34,10 +34,14 @@
//! index kind it reads. Cleanup after a failed commit does not — see
//! [`committed_index_file_path`].
-use crate::spec::IndexFileMeta;
+use crate::spec::{DataEvolutionIndexSourceMeta, IndexFileMeta};
const INDEX_DIR: &str = "index";
+pub(super) fn new_global_index_file_name(prefix: &str) -> String {
+ format!("{prefix}-global-index-{}.index", uuid::Uuid::new_v4())
+}
+
/// How to resolve an index file that carries no explicit external path.
pub(crate) enum IndexFileLocation<'a> {
/// Global index files (data-evolution row-id space) always live under the
@@ -88,11 +92,6 @@ impl IndexFileLocation<'_> {
}
}
-/// `"DEIX"` as a big-endian int, Java `DataEvolutionIndexSourceMeta`'s marker.
-/// `PrimaryKeyIndexSourceMeta` starts with its own version instead, so the
marker
-/// tells the two apart — which is what Java added it for.
-const DATA_EVOLUTION_SOURCE_META_MAGIC: &[u8; 4] = b"DEIX";
-
/// Whether an index file carried by a commit message is a global index file.
///
/// A `_GLOBAL_INDEX` on its own does not say — a source-backed primary-key
index
@@ -101,16 +100,15 @@ const DATA_EVOLUTION_SOURCE_META_MAGIC: &[u8; 4] =
b"DEIX";
/// `PrimaryKeyIndexSourceMeta` starts with its own version. A deletion vector
or
/// the dynamic-bucket hash index carries no `_GLOBAL_INDEX` at all.
///
-/// Absent source metadata is global because the index builders in this crate
-/// write it that way, and they are the only producers of the global index
files
-/// it commits. Java records that predate `_SOURCE_META` cannot reach here: a
-/// commit message is built by this crate's writers, never decoded from Java.
+/// Legacy global index files may carry no source metadata.
fn is_global_index_file(file: &IndexFileMeta) -> bool {
file.global_index_meta
.as_ref()
.is_some_and(|meta| match meta.source_meta.as_deref() {
None => true,
- Some(source_meta) =>
source_meta.starts_with(DATA_EVOLUTION_SOURCE_META_MAGIC),
+ Some(source_meta) => {
+
DataEvolutionIndexSourceMeta::is_data_evolution_meta(Some(source_meta))
+ }
})
}
@@ -312,10 +310,10 @@ mod tests {
#[test]
fn a_global_index_file_is_committed_under_the_table_index_directory() {
- // This crate's index builders leave `_SOURCE_META` empty, and Java
marks
- // its own with `DataEvolutionIndexSourceMeta`'s `DEIX`. Both are
global
- // even when the table keeps index files in the data-file directory.
- for source_meta in [None, Some(data_evolution_source_meta(7))] {
+ let current = DataEvolutionIndexSourceMeta::new_with_schema_id(7, 2)
+ .unwrap()
+ .serialize();
+ for source_meta in [None, Some(data_evolution_source_meta(7)),
Some(current)] {
let file = committed_file(Some(source_meta));
assert_eq!(committed_path(&file), "warehouse/db/tbl/index/idx-0");
}
diff --git a/crates/paimon/src/table/sorted_global_index_build_builder.rs
b/crates/paimon/src/table/sorted_global_index_build_builder.rs
index 40be95f8..285f05eb 100644
--- a/crates/paimon/src/table/sorted_global_index_build_builder.rs
+++ b/crates/paimon/src/table/sorted_global_index_build_builder.rs
@@ -27,7 +27,10 @@ use planning::plan_sorted_index_shards;
use planning::SortedGlobalIndexShard;
use validation::*;
-use super::global_index_build_common::IndexColumns;
+use super::global_index_build_common::{
+ indexed_row_ranges, matching_index_meta, validate_existing_index_overlap,
IndexColumns,
+};
+use super::global_index_schema::GlobalIndexSchema;
use super::global_index_types::{normalize_queryable_global_index_type,
BTREE_GLOBAL_INDEX_TYPE};
#[cfg(test)]
use super::global_index_types::{BITMAP_GLOBAL_INDEX_TYPE,
FM_GLOBAL_INDEX_TYPE};
@@ -177,8 +180,35 @@ impl<'a> SortedGlobalIndexBuildBuilder<'a> {
let manifest_entries = view
.manifest_entries(self.table, self.partition_filter.as_ref())
.await?;
- let indexed =
crate::table::global_index_build_common::indexed_row_ranges(
- view.index_entries(),
+ let mut index_schema = GlobalIndexSchema::new(self.table);
+ let mut retained_indexes = Vec::new();
+ let mut replaced_by_bucket = HashMap::new();
+ let unpartitioned = self.table.schema().partition_keys().is_empty();
+ for entry in view.index_entries() {
+ if matching_index_meta(
+ entry,
+ index_type,
+ index_field.id(),
+ extra_field_ids.as_deref(),
+ )
+ .is_some()
+ && !index_schema.compatible(&entry.index_file).await
+ {
+ let partition = if unpartitioned {
+ Vec::new()
+ } else {
+ entry.partition.clone()
+ };
+ replaced_by_bucket
+ .entry((partition, entry.bucket))
+ .or_insert_with(Vec::new)
+ .push(entry.index_file.clone());
+ } else {
+ retained_indexes.push(entry);
+ }
+ }
+ let indexed = indexed_row_ranges(
+ retained_indexes.iter().copied(),
index_type,
index_field.id(),
extra_field_ids.as_deref(),
@@ -198,8 +228,8 @@ impl<'a> SortedGlobalIndexBuildBuilder<'a> {
return Ok((Some(snapshot.id()), vec![]));
}
-
crate::table::global_index_build_common::validate_existing_index_overlap(
- view.index_entries(),
+ validate_existing_index_overlap(
+ retained_indexes,
index_type,
index_field.id(),
extra_field_ids.as_deref(),
@@ -228,6 +258,15 @@ impl<'a> SortedGlobalIndexBuildBuilder<'a> {
let mut message =
CommitMessage::new(shard.partition_bytes.clone(),
shard.source_bucket, vec![]);
message.new_index_files = index_files;
+ // Retire the old coverage once, together with the new shards in
this bucket.
+ let partition = if unpartitioned {
+ Vec::new()
+ } else {
+ shard.partition_bytes
+ };
+ message.deleted_index_files = replaced_by_bucket
+ .remove(&(partition, shard.source_bucket))
+ .unwrap_or_default();
messages.push(message);
}
diff --git
a/crates/paimon/src/table/sorted_global_index_build_builder/writer.rs
b/crates/paimon/src/table/sorted_global_index_build_builder/writer.rs
index 930e1c7e..b2b25c04 100644
--- a/crates/paimon/src/table/sorted_global_index_build_builder/writer.rs
+++ b/crates/paimon/src/table/sorted_global_index_build_builder/writer.rs
@@ -19,9 +19,11 @@
use super::extraction::build_read_splits_for_shard;
use super::planning::SortedGlobalIndexShard;
use super::{ShardWriteOptions, SortedGlobalIndexBuildBuilder};
-use crate::spec::{DataField, GlobalIndexMeta, IndexFileMeta,
ROW_ID_FIELD_NAME};
+use crate::spec::{
+ DataEvolutionIndexSourceMeta, DataField, GlobalIndexMeta, IndexFileMeta,
ROW_ID_FIELD_NAME,
+};
use crate::table::index_build::{scalar, IndexFileWriter};
-use crate::table::index_file_path::IndexFileLocation;
+use crate::table::index_file_path::{new_global_index_file_name,
IndexFileLocation};
use crate::table::RowRange;
use crate::Result;
@@ -46,7 +48,11 @@ impl SortedGlobalIndexBuildBuilder<'_> {
extra_field_ids: (fields.len() > 1)
.then(|| fields.iter().skip(1).map(|f| f.id()).collect()),
source_meta: Some(
-
crate::spec::DataEvolutionIndexSourceMeta::new(shard.snapshot_id)?.serialize(),
+ DataEvolutionIndexSourceMeta::new_with_schema_id(
+ shard.snapshot_id,
+ self.table.schema().id(),
+ )?
+ .serialize(),
),
index_meta: None,
};
@@ -63,7 +69,7 @@ impl SortedGlobalIndexBuildBuilder<'_> {
IndexFileWriter::new(
self.table,
kind,
- crate::table::global_index_schema::index_file_name(kind,
self.table.schema().id()),
+ new_global_index_file_name(kind),
IndexFileLocation::Global {
table_path: self.table.location().trim_end_matches('/'),
},
diff --git a/crates/paimon/src/table/table_commit/auto_index/planning.rs
b/crates/paimon/src/table/table_commit/auto_index/planning.rs
index e1ef6884..c1883275 100644
--- a/crates/paimon/src/table/table_commit/auto_index/planning.rs
+++ b/crates/paimon/src/table/table_commit/auto_index/planning.rs
@@ -23,6 +23,7 @@ use super::*;
use crate::table::global_index_build_common::{
resolve_index_fields, GlobalIndexBuildView, IndexColumns,
};
+use crate::table::global_index_schema::GlobalIndexSchema;
use crate::table::index_build::full_text::{full_text_config,
native_full_text_options};
use crate::table::source::exclude_row_ranges;
use crate::table::universal_compaction::{Run, UniversalCompaction};
@@ -232,21 +233,12 @@ async fn plan_impl(
.collect::<Vec<_>>();
let mut current: HashMap<UnitKey, Vec<&IndexManifestEntry>> =
HashMap::new();
let mut replaced = HashSet::new();
- let mut index_schema = matches!(
- definition.index_type.as_str(),
- "btree" | "bitmap" | "multivalue" | "fm" | "rtree" | "full-text"
- )
- .then(|| crate::table::global_index_schema::GlobalIndexSchema::new(table,
fields[0]));
+ let mut index_schema = GlobalIndexSchema::new(table);
for entry in selected.iter().copied() {
let meta = entry.index_file.global_index_meta.as_ref().unwrap();
- if let Some(proof) = &mut index_schema {
- if !proof
- .compatible(&entry.index_file.file_name,
&definition.index_type)
- .await
- {
- replaced.insert(index_file_key(entry));
- continue;
- }
+ if !index_schema.compatible(&entry.index_file).await {
+ replaced.insert(index_file_key(entry));
+ continue;
}
if let Some(expected) = &full_text_definition {
// Analyzer options change matching semantics. Independent leaves
diff --git a/crates/paimon/src/table/table_commit/auto_index_tests/schema.rs
b/crates/paimon/src/table/table_commit/auto_index_tests/schema.rs
index afb132bb..ae480dfd 100644
--- a/crates/paimon/src/table/table_commit/auto_index_tests/schema.rs
+++ b/crates/paimon/src/table/table_commit/auto_index_tests/schema.rs
@@ -16,7 +16,10 @@
// under the License.
use super::*;
-use crate::spec::{FloatType, PredicateBuilder, SchemaChange, VarCharType};
+use crate::spec::{
+ DataEvolutionIndexSourceMeta, FloatType, IndexFileMeta, PredicateBuilder,
SchemaChange,
+ VarCharType,
+};
use arrow_array::{ArrayRef, Float32Array, StringArray};
async fn evolve(table: &Table, changes: Vec<SchemaChange>) -> Table {
@@ -111,6 +114,18 @@ async fn assert_scalar_complete(table: &Table, family:
&str) {
.is_empty());
}
+fn index_source(file: &IndexFileMeta) -> DataEvolutionIndexSourceMeta {
+ DataEvolutionIndexSourceMeta::deserialize(
+ file.global_index_meta
+ .as_ref()
+ .unwrap()
+ .source_meta
+ .as_deref()
+ .unwrap(),
+ )
+ .unwrap()
+}
+
#[tokio::test]
async fn scalar_type_changes_retire_same_shard_payloads_in_both_directions() {
for family in ["btree", "bitmap"] {
@@ -245,17 +260,22 @@ async fn
stale_scalar_build_keys_record_the_actual_builder_schema_and_are_retire
.await
.unwrap();
assert_eq!(prepared.len(), 1);
- assert!(prepared[0].new_index_files[0]
- .file_name
- .starts_with(&format!(
- "{family}-global-index-schema-{}-",
- original.schema().id()
- )));
+ let built = index_source(&prepared[0].new_index_files[0]);
+ assert_eq!(built.scan_snapshot_id(), latest(&changed).await.id());
+ assert_eq!(built.source_schema_id(), original.schema().id());
TableCommit::new(changed.clone(), "publish-stale-keys".into())
.commit(prepared)
.await
.unwrap();
let stale = indexes(&changed).await;
+ assert_eq!(
+ matching_ids(&changed, Datum::Float(10.), true).await,
+ vec![1]
+ );
+ assert_eq!(
+ matching_ids(&changed, Datum::Float(20.), true).await,
+ vec![2]
+ );
TableCommit::new(changed.clone(), "replace-stale-keys".into())
.commit(float_messages(&changed, 3, 30.).await)
.await
@@ -272,8 +292,9 @@ async fn
stale_scalar_build_keys_record_the_actual_builder_schema_and_are_retire
);
// A current handle may still intentionally build cast keys from an
- // older captured snapshot. Its name records the FLOAT builder schema,
- // not the INT source snapshot's schema.
+ // older captured snapshot. The source metadata records both the
+ // captured snapshot and the FLOAT builder schema.
+ let source_snapshot_id = source.id();
let prepared = changed
.new_global_index_build_builder()
.with_index_column("value")
@@ -287,12 +308,9 @@ async fn
stale_scalar_build_keys_record_the_actual_builder_schema_and_are_retire
.unwrap();
assert_eq!(prepared.len(), 1);
assert_eq!(prepared[0].new_index_files[0].row_count, 1);
- assert!(prepared[0].new_index_files[0]
- .file_name
- .starts_with(&format!(
- "{family}-global-index-schema-{}-",
- changed.schema().id()
- )));
+ let built = index_source(&prepared[0].new_index_files[0]);
+ assert_eq!(built.scan_snapshot_id(), source_snapshot_id);
+ assert_eq!(built.source_schema_id(), changed.schema().id());
TableCommit::new(changed.clone(), "abort-cast-probe".into())
.abort(&prepared)
.await
@@ -301,25 +319,110 @@ async fn
stale_scalar_build_keys_record_the_actual_builder_schema_and_are_retire
}
#[tokio::test]
-async fn
scalar_build_schema_proof_does_not_depend_on_source_snapshot_retention() {
+async fn
manual_scalar_build_replaces_incompatible_coverage_after_schema_only_change() {
for family in ["btree", "bitmap"] {
let original = scalar_table(family).await;
- TableCommit::new(original.clone(), "retained-payload".into())
+ TableCommit::new(original.clone(), "manual-build-source".into())
.commit(messages(&original, vec![1]).await)
.await
.unwrap();
+ let snapshot = latest(&original).await;
let previous = indexes(&original).await;
- let source = crate::spec::DataEvolutionIndexSourceMeta::deserialize(
- previous[0]
- .index_file
- .global_index_meta
- .as_ref()
- .unwrap()
- .source_meta
- .as_deref()
- .unwrap(),
+ assert_eq!(previous.len(), 1);
+
+ let changed = evolve(
+ &original,
+ vec![SchemaChange::UpdateColumnType {
+ field_names: vec!["value".into()],
+ new_data_type: DataType::Float(FloatType::new()),
+ keep_nullability: true,
+ }],
)
+ .await;
+ assert_eq!(latest(&changed).await.id(), snapshot.id());
+ assert_eq!(
+ matching_ids(&changed, Datum::Float(10.), true).await,
+ vec![1]
+ );
+
+ let count = changed
+ .new_global_index_build_builder()
+ .with_index_column("value")
+ .with_index_type(family)
+ .execute()
+ .await
+ .unwrap();
+ assert_eq!(count, 1);
+ let current = indexes(&changed).await;
+ assert_eq!(current.len(), 1);
+ assert_ne!(
+ previous[0].index_file.file_name,
+ current[0].index_file.file_name
+ );
+ let built = index_source(¤t[0].index_file);
+ assert_eq!(built.scan_snapshot_id(), snapshot.id());
+ assert_eq!(built.source_schema_id(), changed.schema().id());
+ assert_eq!(
+ matching_ids(&changed, Datum::Float(10.), true).await,
+ vec![1]
+ );
+ }
+}
+
+#[tokio::test]
+async fn scalar_compatibility_uses_each_source_schema_and_composite_field() {
+ let original = scalar_table("btree").await;
+ TableCommit::new(original.clone(), "composite-field-source".into())
+ .commit(messages(&original, vec![1]).await)
+ .await
.unwrap();
+ let changed = evolve(
+ &original,
+ vec![SchemaChange::UpdateColumnType {
+ field_names: vec!["value".into()],
+ new_data_type: DataType::Float(FloatType::new()),
+ keep_nullability: true,
+ }],
+ )
+ .await;
+ let mut file = indexes(&original).await.remove(0).index_file;
+ let source = index_source(&file);
+ let mut schema =
crate::table::global_index_schema::GlobalIndexSchema::new(&changed);
+
+ assert!(!schema.compatible(&file).await);
+ let meta = file.global_index_meta.as_mut().unwrap();
+ let changed_field = meta.index_field_id;
+ meta.index_field_id = changed.schema().fields()[0].id();
+ assert!(schema.compatible(&file).await);
+
+ file.global_index_meta.as_mut().unwrap().extra_field_ids =
Some(vec![changed_field]);
+ assert!(!schema.compatible(&file).await);
+ for index_type in ["full-text", "ivf-pq"] {
+ file.index_type = index_type.into();
+ assert!(schema.compatible(&file).await);
+ }
+ file.index_type = "btree".into();
+ file.global_index_meta.as_mut().unwrap().source_meta = Some(
+ DataEvolutionIndexSourceMeta::new_with_schema_id(
+ source.scan_snapshot_id(),
+ changed.schema().id(),
+ )
+ .unwrap()
+ .serialize(),
+ );
+ assert!(schema.compatible(&file).await);
+}
+
+#[tokio::test]
+async fn
scalar_build_schema_proof_does_not_depend_on_source_snapshot_retention() {
+ for family in ["btree", "bitmap"] {
+ let original = scalar_table(family).await;
+ TableCommit::new(original.clone(), "retained-payload".into())
+ .commit(messages(&original, vec![1]).await)
+ .await
+ .unwrap();
+ let previous = indexes(&original).await;
+ let source = index_source(&previous[0].index_file);
let source_path = original
.snapshot_manager()
.snapshot_path(source.scan_snapshot_id());
@@ -350,11 +453,12 @@ async fn legacy_payloads(table: &Table) ->
Vec<IndexManifestEntry> {
for entry in indexes(table).await {
let old = entry.index_file;
let mut legacy = old.clone();
- legacy.file_name = format!(
- "{}-global-index-{}.index",
- old.index_type,
- uuid::Uuid::new_v4()
- );
+ legacy.file_name =
+
crate::table::index_file_path::new_global_index_file_name(&old.index_type);
+ let mut source = b"DEIX".to_vec();
+ source.extend_from_slice(&1i32.to_be_bytes());
+
source.extend_from_slice(&index_source(&old).scan_snapshot_id().to_be_bytes());
+ legacy.global_index_meta.as_mut().unwrap().source_meta = Some(source);
table
.file_io()
.copy_file(
@@ -368,7 +472,7 @@ async fn legacy_payloads(table: &Table) ->
Vec<IndexManifestEntry> {
message.new_index_files.push(legacy);
messages.push(message);
}
- TableCommit::new(table.clone(), "legacy-file-names".into())
+ TableCommit::new(table.clone(), "legacy-source-metadata".into())
.commit(messages)
.await
.unwrap();
@@ -376,7 +480,7 @@ async fn legacy_payloads(table: &Table) ->
Vec<IndexManifestEntry> {
}
#[tokio::test]
-async fn legacy_scalar_files_require_a_complete_unchanged_type_history() {
+async fn legacy_scalar_files_skip_type_history_validation() {
for family in ["btree", "bitmap"] {
for history in ["same-type", "round-trip", "missing"] {
let original = scalar_table(family).await;
@@ -426,9 +530,8 @@ async fn
legacy_scalar_files_require_a_complete_unchanged_type_history() {
.await
.unwrap();
let current = indexes(&changed).await;
- assert_eq!(
+ assert!(
previous.iter().all(|entry| current.contains(entry)),
- history == "same-type",
"{family}, history={history}"
);
assert_eq!(matching_ids(&changed, Datum::Int(10), true).await,
vec![1]);
@@ -482,75 +585,47 @@ async fn text_matches(table: &Table, query: &str, mode:
&str) -> Vec<u64> {
}
#[tokio::test]
-async fn
full_text_narrowing_rebuilds_same_shard_tokens_to_match_current_text() {
+async fn full_text_split_read_rechecks_scalar_index_schema() {
let original = evolve(
- &table(Some(true), false).await,
- vec![
-
SchemaChange::remove_option("global-index.btree.index-columns".into()),
-
SchemaChange::remove_option("global-index.bitmap.index-columns".into()),
- SchemaChange::add_column(
- "text".into(),
- DataType::VarChar(VarCharType::new(100).unwrap()),
- ),
-
SchemaChange::set_option("global-index.full-text.index-columns".into(),
"text".into()),
-
SchemaChange::set_option("global-index.row-count-per-shard".into(),
"64".into()),
- ],
+ &analyzer_table().await,
+ vec![SchemaChange::set_option(
+ "global-index.btree.index-columns".into(),
+ "value".into(),
+ )],
)
.await;
- TableCommit::new(original.clone(), "wide-text".into())
+ TableCommit::new(original.clone(), "mixed-search-source".into())
.commit(text_messages(&original, 1, "sentinel").await)
.await
.unwrap();
- let previous = indexes(&original).await;
- assert_eq!(text_matches(&original, "sentinel", "fast").await, vec![0]);
let changed = evolve(
&original,
- vec![SchemaChange::UpdateColumnType {
- field_names: vec!["text".into()],
- new_data_type: DataType::VarChar(VarCharType::new(3).unwrap()),
- keep_nullability: true,
- }],
+ vec![
+ SchemaChange::UpdateColumnType {
+ field_names: vec!["value".into()],
+ new_data_type: DataType::Float(FloatType::new()),
+ keep_nullability: true,
+ },
+
SchemaChange::set_option("scalar-index.prefilter.search-mode".into(),
"full".into()),
+ ],
)
.await;
- TableCommit::new(changed.clone(), "narrow-text".into())
- .commit(text_messages(&changed, 2, "new").await)
- .await
- .unwrap();
- let native = [
- ("sentinel", text_matches(&changed, "sentinel", "fast").await),
- ("sen", text_matches(&changed, "sen", "fast").await),
- ];
- assert!(
- native[0].1.is_empty(),
- "old tokens must not match truncated text"
- );
- assert_eq!(
- native[1].1,
- vec![0],
- "current text must be indexed as 'sen'"
+ let mut search = changed.new_full_text_search_builder();
+ search
+ .with_text_column("text")
+ .with_query_text("sentinel")
+ .with_limit(10);
+ let plan = search.new_scan().unwrap().scan().await.unwrap();
+ search.with_filter(
+ PredicateBuilder::new(changed.schema().fields())
+ .equal("value", Datum::Float(10.))
+ .unwrap(),
);
- let current = indexes(&changed).await;
- assert!(previous.iter().all(|entry| !current.contains(entry)));
- // Remove index references to force the existing raw FULL/DETAIL paths.
- // Their document text is read through the same real VARCHAR narrowing.
- changed
- .new_global_index_drop_builder()
- .with_index_column("text")
- .with_index_type("full-text")
- .execute()
- .await
- .unwrap();
- assert!(indexes(&changed).await.is_empty());
- for mode in ["full", "detail"] {
- for (query, expected) in &native {
- assert_eq!(
- text_matches(&changed, query, mode).await,
- *expected,
- "{query}, {mode}"
- );
- }
- }
+ let direct = search.execute().await.unwrap();
+ assert_eq!(direct.row_ids().unwrap().row_ids, vec![0]);
+ let split_read = search.new_read().unwrap().read(plan).await.unwrap();
+ assert_eq!(split_read.row_ids().unwrap().row_ids, vec![0]);
}
async fn analyzer_table() -> Table {
@@ -683,8 +758,7 @@ async fn
full_text_unproven_analyzer_metadata_requires_rebuilding() {
.unwrap();
let previous = indexes(&table).await.remove(0);
let mut legacy = previous.index_file.clone();
- legacy.file_name =
- crate::table::global_index_schema::index_file_name("full-text",
table.schema().id());
+ legacy.file_name =
crate::table::index_file_path::new_global_index_file_name("full-text");
legacy.global_index_meta.as_mut().unwrap().index_meta = index_meta;
table
.file_io()
diff --git a/crates/paimon/src/table/table_scan.rs
b/crates/paimon/src/table/table_scan.rs
index 1d411af0..757e22cf 100644
--- a/crates/paimon/src/table/table_scan.rs
+++ b/crates/paimon/src/table/table_scan.rs
@@ -2575,6 +2575,7 @@ impl<'a> PaimonTableScan<'a> {
HashSet::new()
};
let mut entries = Vec::new();
+ let mut index_schema =
super::global_index_schema::GlobalIndexSchema::new(&self.table);
for entry in IndexManifest::read(self.table.file_io(), &path).await? {
if retain_index_manifest_entry_for_scan(
&entry,
@@ -2582,7 +2583,8 @@ impl<'a> PaimonTableScan<'a> {
deletion_vectors_needed,
self.partition_filter.as_ref(),
&predicate_field_ids,
- )? {
+ )? && index_schema.compatible(&entry.index_file).await
+ {
entries.push(entry);
}
}
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 ea0cdf32..3e229662 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/centroid.rs
@@ -29,7 +29,7 @@ use crate::table::index_build::{
vector::{serialize_writer, VectorSpill},
IndexFileWriter, IndexPayload,
};
-use crate::table::index_file_path::IndexFileLocation;
+use crate::table::index_file_path::{new_global_index_file_name,
IndexFileLocation};
use crate::table::partition_filter::PartitionFilter;
use crate::table::{CommitMessage, RowRange, Table};
use crate::vindex::VindexVectorIndexOptions;
@@ -300,7 +300,12 @@ impl VindexIndexBuildBuilder<'_> {
{
let row_count = rows.vector_count() as i64;
let file = self
- .centroid_file_writer(shard, field_id, &extra_fields)
+ .centroid_file_writer(
+ shard,
+ field_id,
+ &extra_fields,
+ new_global_index_file_name("centroid-bitmap"),
+ )
.await?
.write(self.table, |output| async move {
bitmap
@@ -397,8 +402,17 @@ impl VindexIndexBuildBuilder<'_> {
writer: Option<VectorIndexWriter>,
bytes: Vec<u8>,
) -> Result<IndexFileMeta> {
+ let prefix = format!("vector-{}", self.index_type);
+ let file_name = if matches!(descriptor.role, Role::Router(_)) {
+ format!(
+ "{prefix}-global-index-training-model-{}.index",
+ descriptor.model_id
+ )
+ } else {
+ new_global_index_file_name(&prefix)
+ };
let index_meta = descriptor.encode()?;
- self.centroid_file_writer(shard, field_id, extra_fields)
+ self.centroid_file_writer(shard, field_id, extra_fields, file_name)
.await?
.write(self.table, |output| async move {
match writer {
@@ -418,18 +432,20 @@ impl VindexIndexBuildBuilder<'_> {
shard: &VectorIndexShard,
field_id: i32,
extra_fields: &[i32],
+ file_name: String,
) -> Result<IndexFileWriter> {
- let file_name = format!(
- "vector-{}-global-index-{}.index",
- self.index_type,
- uuid::Uuid::new_v4()
- );
let meta = GlobalIndexMeta {
row_range_start: shard.row_range_start,
row_range_end: shard.row_range_end,
index_field_id: field_id,
extra_field_ids: (!extra_fields.is_empty()).then(||
extra_fields.to_vec()),
- source_meta:
Some(DataEvolutionIndexSourceMeta::new(shard.snapshot_id)?.serialize()),
+ source_meta: Some(
+ DataEvolutionIndexSourceMeta::new_with_schema_id(
+ shard.snapshot_id,
+ self.table.schema().id(),
+ )?
+ .serialize(),
+ ),
index_meta: None,
};
IndexFileWriter::new(
diff --git
a/crates/paimon/src/table/vindex_index_build_builder/centroid_tests.rs
b/crates/paimon/src/table/vindex_index_build_builder/centroid_tests.rs
index 6decbdd0..ed0c04a3 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/centroid_tests.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/centroid_tests.rs
@@ -623,6 +623,22 @@ async fn
centroid_bitmaps_prefilter_or_before_ranking_and_drop_with_the_vector_c
let groups = centroid_index::group(&entries).unwrap();
let group = &groups[0];
assert_eq!(group.bitmaps.len(), 2);
+ assert_eq!(
+ group.router.index_file.file_name,
+ format!(
+ "vector-ivf-flat-global-index-training-model-{}.index",
+ group.descriptor.model_id
+ )
+ );
+ for entry in group.bitmaps.values() {
+ let id = entry
+ .index_file
+ .file_name
+ .strip_prefix("centroid-bitmap-global-index-")
+ .and_then(|name| name.strip_suffix(".index"))
+ .unwrap();
+ assert!(uuid::Uuid::parse_str(id).is_ok());
+ }
// A shard with no bitmap match must not open the ANN payload at all.
let field = table
diff --git a/crates/paimon/src/table/vindex_index_build_builder/writer.rs
b/crates/paimon/src/table/vindex_index_build_builder/writer.rs
index 520d4d3c..b8be1959 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/writer.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/writer.rs
@@ -35,7 +35,7 @@ use crate::table::index_build::{
vector::{serialize_writer, TrainedVectors, VectorSpill},
IndexFileWriter, IndexPayload,
};
-use crate::table::index_file_path::IndexFileLocation;
+use crate::table::index_file_path::{new_global_index_file_name,
IndexFileLocation};
use crate::table::RowRange;
pub(super) struct BuiltIndexFile {
@@ -241,18 +241,18 @@ impl<'a> VindexIndexBuildBuilder<'a> {
index_meta: Vec<u8>,
row_count: i64,
) -> Result<IndexFileMeta> {
- let file_name = format!(
- "vector-{}-global-index-{}.index",
- self.index_type,
- uuid::Uuid::new_v4()
- );
+ let file_name = new_global_index_file_name(&format!("vector-{}",
self.index_type));
let meta = GlobalIndexMeta {
row_range_start: shard.row_range_start,
row_range_end: shard.row_range_end,
index_field_id,
extra_field_ids: None,
source_meta: Some(
-
crate::spec::DataEvolutionIndexSourceMeta::new(shard.snapshot_id)?.serialize(),
+ crate::spec::DataEvolutionIndexSourceMeta::new_with_schema_id(
+ shard.snapshot_id,
+ self.table.schema().id(),
+ )?
+ .serialize(),
),
index_meta: None,
};