From 31a118721f968f63032e49987debe2bfc66b66d6 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 17:26:36 -0800 Subject: [PATCH 01/23] feat: collect zone map write seeds for unindexed columns from dataset config Add two dataset config keys. `lance.zone_write_seeds.enabled` makes writes embed a zone map seed for every top-level column of a supported scalar type that no seeded ZoneMap index covers, so a ZoneMap index created later can be built from seeds instead of scanning. `lance.zone_write_seeds.rows_per_zone` sets the rows per seed zone for those columns (default 8192). A column with a seeded ZoneMap index keeps following that index. The commit that enables the setting also sets the seed feature flags; binary-copy compaction declares the same zone size for carried seeds. Co-Authored-By: Claude --- .../lance/src/dataset/optimize/binary_copy.rs | 7 +- .../optimize/binary_copy/seed_carry.rs | 41 ++- .../dataset/tests/dataset_zone_map_seeds.rs | 335 +++++++++++++++++- rust/lance/src/dataset/write.rs | 1 + rust/lance/src/dataset/write/seeds.rs | 312 ++++++++++++++-- 5 files changed, 646 insertions(+), 50 deletions(-) diff --git a/rust/lance/src/dataset/optimize/binary_copy.rs b/rust/lance/src/dataset/optimize/binary_copy.rs index e8f70fabd41..7d80d5b032f 100644 --- a/rust/lance/src/dataset/optimize/binary_copy.rs +++ b/rust/lance/src/dataset/optimize/binary_copy.rs @@ -177,6 +177,7 @@ pub async fn rewrite_files_binary_copy( // Seeds of the inputs feeding the current output file, in copy order. let mut seed_acc = OutputSeedAccumulator::default(); let index_rows_per_zone = seed_carry::index_rows_per_zone(dataset).await?; + let unindexed_rows_per_zone = seed_carry::unindexed_rows_per_zone(dataset); // Visit each fragment and all of its data files (a fragment may contain multiple files) for frag in fragments.iter() { @@ -387,7 +388,8 @@ pub async fn rewrite_files_binary_copy( // Accumulate rows for the current output file and flush when reaching the threshold total_rows_in_current += file_meta.num_rows; if total_rows_in_current >= max_rows_per_file { - let output_seeds = seed_acc.finish(&schema, &index_rows_per_zone)?; + let output_seeds = + seed_acc.finish(&schema, &index_rows_per_zone, unindexed_rows_per_zone)?; let fragment_out = finalize_current_output_file( &schema, version, @@ -420,7 +422,8 @@ pub async fn rewrite_files_binary_copy( // Flush remaining rows as a final output file init_writer_if_necessary(dataset, version, &mut current_writer, &mut current_filename) .await?; - let output_seeds = seed_acc.finish(&schema, &index_rows_per_zone)?; + let output_seeds = + seed_acc.finish(&schema, &index_rows_per_zone, unindexed_rows_per_zone)?; let frag = finalize_current_output_file( &schema, version, diff --git a/rust/lance/src/dataset/optimize/binary_copy/seed_carry.rs b/rust/lance/src/dataset/optimize/binary_copy/seed_carry.rs index 73ac227c895..83281b34623 100644 --- a/rust/lance/src/dataset/optimize/binary_copy/seed_carry.rs +++ b/rust/lance/src/dataset/optimize/binary_copy/seed_carry.rs @@ -27,6 +27,7 @@ use lance_table::format::DataFile; use crate::Dataset; use crate::Result; +use crate::dataset::write::seeds::ZoneWriteSeedsConfig; use crate::datatypes::Schema; /// One input column's recognized seed. @@ -40,14 +41,26 @@ pub enum SourceColumnSeed { } /// The `rows_per_zone` an output column's locator declares: the current -/// index specification for the column when one exists, else the writer -/// default. It is write-time configuration; zones are located by length. -pub fn output_rows_per_zone(index_rows_per_zone: Option) -> u64 { - index_rows_per_zone.unwrap_or(lance_index::scalar::zonemap::ROWS_PER_ZONE_DEFAULT) +/// seeded index specification for the column when one exists, else +/// `unindexed_rows_per_zone`. It is write-time configuration; zones are +/// located by length. +pub fn output_rows_per_zone(index_rows_per_zone: Option, unindexed_rows_per_zone: u64) -> u64 { + index_rows_per_zone.unwrap_or(unindexed_rows_per_zone) } -/// The configured `rows_per_zone` of each column's current usable ZoneMap -/// index, by field id. +/// The `rows_per_zone` the write path uses for a column without a seeded +/// ZoneMap index: the dataset's zone write seed setting when enabled, else +/// the writer default. +pub fn unindexed_rows_per_zone(dataset: &Dataset) -> u64 { + ZoneWriteSeedsConfig::from_config(dataset.config()).map_or( + lance_index::scalar::zonemap::ROWS_PER_ZONE_DEFAULT, + |config| config.rows_per_zone, + ) +} + +/// The seed `rows_per_zone` of each column with a current usable seeded +/// ZoneMap index, by field id: the smallest among its seeded indices, as +/// the write path chooses it. pub async fn index_rows_per_zone(dataset: &Dataset) -> Result> { use crate::index::scalar::fetch_index_details; use crate::index::{loading::load_all_indices, segment::index_is_usable}; @@ -74,9 +87,13 @@ pub async fn index_rows_per_zone(dataset: &Dataset) -> Result> continue; }; if let Ok(zone_map) = details.to_msg::() + && zone_map.use_seeds.unwrap_or(false) && let Some(configured) = zone_map.rows_per_zone { - rows_per_zone.insert(field_id, configured); + rows_per_zone + .entry(field_id) + .and_modify(|rows: &mut u64| *rows = (*rows).min(configured)) + .or_insert(configured); } } Ok(rows_per_zone) @@ -246,8 +263,8 @@ impl OutputSeedAccumulator { /// A column is kept only when every input carries a version 1 seed of one /// value type; zones are located by length, so differing collection /// granularities concatenate freely and the output locator declares the - /// column's current `rows_per_zone` from `index_rows_per_zone` (or the - /// writer default). Each column is decided on its own: an input without + /// column's current `rows_per_zone` from `index_rows_per_zone` (or + /// `unindexed_rows_per_zone`). Each column is decided on its own: an input without /// a seed, with a version this build cannot interpret, or with a version /// 0 seed drops that column (no conversion or relabeling), and the data /// still copies. @@ -255,6 +272,7 @@ impl OutputSeedAccumulator { &mut self, current_schema: &Schema, index_rows_per_zone: &HashMap, + unindexed_rows_per_zone: u64, ) -> Result> { let sources = std::mem::take(&mut self.sources); let Some(first) = sources.first() else { @@ -329,7 +347,10 @@ impl OutputSeedAccumulator { }; output.push(OutputSeed { column_name: current_field.name.clone(), - rows_per_zone: output_rows_per_zone(index_rows_per_zone.get(field_id).copied()), + rows_per_zone: output_rows_per_zone( + index_rows_per_zone.get(field_id).copied(), + unindexed_rows_per_zone, + ), bytes, }); } diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index a6eada97e1a..fbc621f9af4 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -12,11 +12,13 @@ use std::sync::Arc; use arrow::compute::concat_batches; +use arrow_array::types::Float32Type; use arrow_array::{ - Array, ArrayRef, BinaryArray, BinaryViewArray, Int32Array, RecordBatch, RecordBatchIterator, - StringArray, StringViewArray, StructArray, + Array, ArrayRef, BinaryArray, BinaryViewArray, FixedSizeListArray, Int32Array, Int64Array, + RecordBatch, RecordBatchIterator, StringArray, StringViewArray, StructArray, + TimestampMicrosecondArray, }; -use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; +use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema, TimeUnit}; use bytes::Bytes; use futures::{TryStreamExt, stream}; use lance_core::datatypes::Schema as LanceSchema; @@ -41,6 +43,9 @@ use crate::dataset::optimize::CompactionScope; use crate::dataset::schema_evolution::{ColumnAlteration, NewColumnTransform}; use crate::dataset::transaction::{DataReplacementGroup, Operation, Transaction}; use crate::dataset::write::merge_insert::{WhenMatched, WhenNotMatched}; +use crate::dataset::write::seeds::{ + ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, +}; use crate::dataset::{ CommitBuilder, DATA_DIR, InsertBuilder, MergeInsertBuilder, MergeInsertWriteMode, UpdateBuilder, WriteDestination, WriteMode, WriteParams, @@ -1902,6 +1907,7 @@ async fn reopen_with_seed_flags_cleared(dataset: &Dataset) -> Dataset { manifest.writer_feature_flags &= !FLAG_ZONE_WRITE_SEEDS; manifest.version += 1; let indices = load_all_indices(dataset).await.unwrap().as_ref().clone(); + let index_count = indices.len(); write_manifest_file( dataset.object_store.as_ref(), dataset.commit_handler.as_ref(), @@ -1921,7 +1927,7 @@ async fn reopen_with_seed_flags_cleared(dataset: &Dataset) -> Dataset { let mut reopened = dataset.clone(); reopened.checkout_latest().await.unwrap(); assert!(!seed_flags_set(&reopened)); - assert_eq!(reopened.load_indices().await.unwrap().len(), 1); + assert_eq!(reopened.load_indices().await.unwrap().len(), index_count); reopened } @@ -2560,3 +2566,324 @@ async fn test_binary_copy_translates_remapped_seed_fields() { ); assert_eq!(indexed.try_into_batch().await.unwrap().num_rows(), expected); } + +// --- Zone write seeds from the dataset config -------------------------------- +// +// `lance.zone_write_seeds.*` seeds every column that no seeded ZoneMap index +// covers, so an index created later can be built from the seeds. + +const CONFIG_COLUMNS: [&str; 4] = ["id", "val", "name", "ts"]; +/// Columns of [`config_schema`] whose types the config never seeds. +const UNSEEDED_CONFIG_COLUMNS: [&str; 2] = ["vec", "meta"]; + +fn config_meta_field() -> Arc { + Arc::new(ArrowField::new("a", DataType::Int32, true)) +} + +fn config_schema() -> Arc { + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int64, false), + ArrowField::new("val", DataType::Int64, true), + ArrowField::new("name", DataType::Utf8, true), + ArrowField::new("ts", DataType::Timestamp(TimeUnit::Microsecond, None), true), + ArrowField::new( + "vec", + DataType::FixedSizeList( + Arc::new(ArrowField::new("item", DataType::Float32, true)), + 4, + ), + true, + ), + ArrowField::new( + "meta", + DataType::Struct(vec![config_meta_field()].into()), + true, + ), + ])) +} + +fn config_rows(ids: std::ops::Range) -> RecordBatch { + RecordBatch::try_new( + config_schema(), + vec![ + Arc::new(Int64Array::from_iter_values(ids.clone())), + Arc::new(Int64Array::from_iter( + ids.clone().map(|i| (i % 7 != 3).then_some(i)), + )), + Arc::new(StringArray::from_iter( + ids.clone() + .map(|i| (i % 5 != 2).then(|| format!("n{i:03}"))), + )), + Arc::new(TimestampMicrosecondArray::from_iter( + ids.clone() + .map(|i| Some(1_700_000_000_000_000 + i * 1_000_000)), + )), + Arc::new( + FixedSizeListArray::from_iter_primitive::( + ids.clone().map(|i| Some(vec![Some(i as f32); 4])), + 4, + ), + ), + Arc::new(StructArray::from(vec![( + config_meta_field(), + Arc::new(Int32Array::from_iter(ids.map(|i| Some(i as i32)))) as ArrayRef, + )])), + ], + ) + .unwrap() +} + +/// Ten rows in one fragment, written before any config is set. +async fn dataset_with_config_rows(uri: &str) -> Dataset { + Dataset::write( + RecordBatchIterator::new([Ok(config_rows(0..10))], config_schema()), + uri, + None, + ) + .await + .unwrap() +} + +async fn append_config_rows(dataset: &mut Dataset, ids: std::ops::Range) { + dataset + .append( + RecordBatchIterator::new([Ok(config_rows(ids))], config_schema()), + None, + ) + .await + .unwrap(); +} + +async fn enable_zone_write_seeds(dataset: &mut Dataset, rows_per_zone: u64) { + let rows_per_zone = rows_per_zone.to_string(); + dataset + .update_config([ + (ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), + (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, rows_per_zone.as_str()), + ]) + .await + .unwrap(); +} + +/// The `rows_per_zone` the seed locator of `column` declares in the data file +/// serving it, or `None` when that file carries no seed for the column. +async fn seed_locator_rows_per_zone( + dataset: &Dataset, + fragment: &Fragment, + column: &str, +) -> Option { + let file = serving_file(fragment, field_id(dataset, column)); + let reader = open_data_file(dataset, &file.path).await; + let value = reader + .metadata() + .file_schema + .metadata + .get(&format!("{SEED_META_KEY_PREFIX}{column}"))? + .clone(); + Some(value.split_once(':').unwrap().1.parse().unwrap()) +} + +/// The commit that enables the setting publishes the seed flags, so the next +/// append seeds every column at the configured size; earlier files stay +/// unseeded. +#[tokio::test] +async fn test_config_seeds_columns_without_index() { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + assert!(!seed_flags_set(&dataset)); + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + assert_seed_flags_set(&dataset); + + append_config_rows(&mut dataset, 10..20).await; + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), 2); + for column in CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[0], column).await, + None, + "first file, column {column}" + ); + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], column).await, + Some(ROWS_PER_ZONE), + "appended file, column {column}" + ); + } + for column in UNSEEDED_CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], column).await, + None, + "appended file, unsupported column {column}" + ); + } +} + +/// A snapshot that enables the setting but does not carry the seed flags +/// writes no seed; its commit sets the flags and the next write is seeded. +#[tokio::test] +async fn test_config_seeds_wait_for_seed_flags() { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + let mut legacy = reopen_with_seed_flags_cleared(&dataset).await; + + append_config_rows(&mut legacy, 10..20).await; + assert_seed_flags_set(&legacy); + append_config_rows(&mut legacy, 20..30).await; + let fragments = legacy.fragments().clone(); + assert_eq!(fragments.len(), 3); + for column in CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(&legacy, &fragments[1], column).await, + None, + "append without flags, column {column}" + ); + assert_eq!( + seed_locator_rows_per_zone(&legacy, &fragments[2], column).await, + Some(ROWS_PER_ZONE), + "append with flags, column {column}" + ); + } +} + +/// Without the setting, or with it set to false, appends carry no seeds and +/// the seed flags stay unset. +#[rstest::rstest] +#[case::absent(None)] +#[case::disabled(Some("false"))] +#[tokio::test] +async fn test_config_seeds_off(#[case] enabled: Option<&'static str>) { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + if let Some(enabled) = enabled { + dataset + .update_config([ + (ZONE_WRITE_SEEDS_ENABLED_KEY, enabled), + (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4"), + ]) + .await + .unwrap(); + } + append_config_rows(&mut dataset, 10..20).await; + assert!(!seed_flags_set(&dataset)); + let fragments = dataset.fragments().clone(); + for column in CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], column).await, + None, + "column {column}" + ); + } +} + +/// A ZoneMap index created after a seeded append reuses the configured seeds +/// for that fragment and answers queries like a scan. +#[tokio::test] +async fn test_index_built_from_config_seeds() { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 10..20).await; + let appended = dataset.fragments()[1].id; + + // Configured seeds record null counts, not positions, so the index + // keeps no null bitmap to reuse them. + let params = + ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ + "rows_per_zone": ROWS_PER_ZONE, + "use_seeds": true, + "store_null_bitmap": false, + })); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1); + assert_eq!(reports[0].reused_fragments, vec![appended]); + + for filter in ["val >= 5 AND val < 15", "val = 12", "val IS NULL"] { + let mut indexed = dataset.scan(); + indexed.filter(filter).unwrap().project(&["id"]).unwrap(); + let indexed = indexed.try_into_batch().await.unwrap(); + let mut unindexed = dataset.scan(); + unindexed + .use_scalar_index(false) + .filter(filter) + .unwrap() + .project(&["id"]) + .unwrap(); + let expected = unindexed.try_into_batch().await.unwrap(); + assert!(expected.num_rows() > 0, "filter {filter}"); + assert_eq!(indexed, expected, "filter {filter}"); + } +} + +/// A column with a seeded ZoneMap index follows that index's zone size even +/// when the configured size is smaller; a ZoneMap index without seeds does +/// not take part, so its column gets the configured size like any other. +#[rstest::rstest] +#[case::seeded_index(true, 8)] +#[case::unseeded_index(false, ROWS_PER_ZONE)] +#[tokio::test] +async fn test_config_seed_size_with_zone_map_index( + #[case] use_seeds: bool, + #[case] expected_val_rows_per_zone: u64, +) { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + let params = ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap) + .with_params(&serde_json::json!({"rows_per_zone": 8, "use_seeds": use_seeds})); + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 10..20).await; + + let appended = dataset.fragments()[1].clone(); + for column in CONFIG_COLUMNS { + let expected = if column == "val" { + expected_val_rows_per_zone + } else { + ROWS_PER_ZONE + }; + assert_eq!( + seed_locator_rows_per_zone(&dataset, &appended, column).await, + Some(expected), + "column {column}" + ); + } +} + +/// Binary-copy compaction declares the configured zone size for carried +/// seeds of columns without a seeded index, as the write path does. +#[tokio::test] +async fn test_binary_copy_declares_configured_rows_per_zone() { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 10..20).await; + append_config_rows(&mut dataset, 20..30).await; + // Drop the unseeded first fragment so every compaction input is seeded. + dataset.delete("id < 10").await.unwrap(); + assert_eq!(dataset.fragments().len(), 2); + + let metrics = force_binary_copy(&mut dataset, 1_000_000).await; + assert_eq!(metrics.fragments_added, 1); + let output = dataset.fragments()[0].clone(); + assert_eq!(output.physical_rows, Some(20)); + for column in CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(&dataset, &output, column).await, + Some(ROWS_PER_ZONE), + "column {column}" + ); + } +} diff --git a/rust/lance/src/dataset/write.rs b/rust/lance/src/dataset/write.rs index 7743a80bd20..483930159db 100644 --- a/rust/lance/src/dataset/write.rs +++ b/rust/lance/src/dataset/write.rs @@ -76,6 +76,7 @@ pub use super::progress::{WriteProgressFn, WriteStats}; pub use commit::{CommitBuilder, DEFAULT_COMMIT_TIMEOUT}; pub use delete::{DeleteBuilder, DeleteResult, UncommittedDelete}; pub use insert::InsertBuilder; +pub use seeds::{ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}; impl Dataset { pub(super) fn validate_data_file_target(&self, target: &DataFileTarget) -> Result<()> { diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 3b9ff930549..f702dcf2efe 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -15,16 +15,36 @@ //! commit path sets them for every index that requests such a seed //! ([`apply_seed_feature_flags`]), so no manifest references a seed its flags //! do not announce. +//! +//! Columns without a seeded index get seeds only when the dataset config +//! asks for them ([`ZoneWriteSeedsConfig`]): +//! +//! - `lance.zone_write_seeds.enabled`: `"true"` collects a zone map seed for +//! every top-level column of a supported scalar type that no seeded +//! ZoneMap index covers, so a ZoneMap index created later can be built +//! from seeds instead of scanning. Nested, vector, dictionary, view, +//! extension and blob columns are never seeded by the config. Absent +//! or `"false"` disables this; any other value is treated as disabled with +//! a warning. +//! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those +//! columns, a positive integer. Absent, zero or unparsable values use +//! [`ROWS_PER_ZONE_DEFAULT`] (the latter two with a warning). +//! +//! A column with a seeded ZoneMap index keeps following that index's +//! `rows_per_zone`. Enable the setting with [`Dataset::update_config`]; the +//! commit that sets it also sets the seed feature flags, and writes based on +//! later versions embed the seeds. use std::collections::{HashMap, HashSet}; use arrow_array::RecordBatch; +use arrow_schema::DataType; use lance_core::Result; -use lance_core::datatypes::Schema; +use lance_core::datatypes::{Field, Schema}; use lance_file::version::ConcreteFileVersion; use lance_index::pbold; use lance_index::scalar::seed::IndexSeedWriter; -use lance_index::scalar::zonemap::ZoneMapSeedWriter; +use lance_index::scalar::zonemap::{ROWS_PER_ZONE_DEFAULT, ZoneMapSeedWriter}; use lance_table::format::{IndexMetadata, Manifest}; use super::GenericWriter; @@ -37,6 +57,55 @@ use crate::index::{loading::load_all_indices, segment::index_is_usable}; /// reported once per process and at debug level afterwards. static SEED_CONFLICT_WARNED: std::sync::Once = std::sync::Once::new(); +/// Dataset config key that enables zone map seeds for columns without a +/// seeded ZoneMap index (`"true"` / `"false"`). +pub const ZONE_WRITE_SEEDS_ENABLED_KEY: &str = "lance.zone_write_seeds.enabled"; +/// Dataset config key for the rows per seed zone of those columns. +pub const ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY: &str = "lance.zone_write_seeds.rows_per_zone"; + +/// The dataset-level zone write seed setting, parsed from the dataset config. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ZoneWriteSeedsConfig { + /// Rows per seed zone for columns without a seeded ZoneMap index. + pub rows_per_zone: u64, +} + +impl ZoneWriteSeedsConfig { + /// The setting in `config`, or `None` when it is disabled. + /// + /// Invalid values never fail a write: an unparsable `enabled` disables + /// the setting and an invalid `rows_per_zone` falls back to + /// [`ROWS_PER_ZONE_DEFAULT`], both with a warning. + pub fn from_config(config: &HashMap) -> Option { + let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; + match enabled.parse::() { + Ok(true) => {} + Ok(false) => return None, + Err(err) => { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_ENABLED_KEY}={enabled:?} ({err}); zone write \ + seeds stay disabled" + ); + return None; + } + } + let rows_per_zone = match config.get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) { + None => ROWS_PER_ZONE_DEFAULT, + Some(value) => match value.parse::() { + Ok(rows) if rows > 0 => rows, + _ => { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected a \ + positive integer; using {ROWS_PER_ZONE_DEFAULT}" + ); + ROWS_PER_ZONE_DEFAULT + } + }, + }; + Some(Self { rows_per_zone }) + } +} + /// Collects write seeds for the columns of one data file. #[derive(Debug, Default)] pub struct SeedCollector { @@ -53,9 +122,11 @@ impl SeedCollector { /// /// A column gets a seed writer when an existing, usable index on it asks /// for one through its plugin and the dataset already carries the feature - /// flags that seed format requires. `consult_indices` is false for writes - /// that discard the dataset's indices (overwrite), where seeds have no - /// consumer. + /// flags that seed format requires. With zone write seeds enabled in the + /// dataset config ([`ZoneWriteSeedsConfig`]), every other column the zone + /// map supports gets a zone map seed under the same flag rule. + /// `consult_indices` is false for writes that discard the dataset's + /// indices (overwrite), where seeds have no consumer. pub async fn for_write( version: ConcreteFileVersion, dataset: Option<&Dataset>, @@ -72,27 +143,34 @@ impl SeedCollector { let indices = load_all_indices(dataset).await?; let manifest = dataset.manifest.as_ref(); - let writers = seed_writers_for(dataset, &indices, write_schema, SeedWriterPurpose::Collect) - .await? - .into_iter() - .filter(|writer| { - let required = writer.required_feature_flags(); - let activated = manifest.reader_feature_flags & required == required - && manifest.writer_feature_flags & required == required; - if !activated { - // Readers could not be told about this seed yet; the next - // commit activates the flags and later writes embed it. - log::debug!( - "skipping write seed for column {}: dataset version {} does not \ + let config = ZoneWriteSeedsConfig::from_config(&manifest.config); + let writers = seed_writers_for( + dataset, + &indices, + write_schema, + config, + SeedWriterPurpose::Collect, + ) + .await? + .into_iter() + .filter(|writer| { + let required = writer.required_feature_flags(); + let activated = manifest.reader_feature_flags & required == required + && manifest.writer_feature_flags & required == required; + if !activated { + // Readers could not be told about this seed yet; the next + // commit activates the flags and later writes embed it. + log::debug!( + "skipping write seed for column {}: dataset version {} does not \ carry feature flags {:#x}", - writer.column_name(), - manifest.version, - required - ); - } - activated - }) - .collect(); + writer.column_name(), + manifest.version, + required + ); + } + activated + }) + .collect(); Ok(Self { writers }) } @@ -132,12 +210,6 @@ impl SeedCollector { } } -/// The seed writers that the usable indices in `indices` request for the -/// top-level columns of `schema`. -/// -/// `dataset` resolves index details that are not inline in the metadata; it -/// only has to share its index store with `indices`, which may belong to a -/// manifest that is still being built. /// Why seed writers are being selected. #[derive(Clone, Copy, PartialEq, Eq)] enum SeedWriterPurpose { @@ -150,10 +222,18 @@ enum SeedWriterPurpose { FeatureFlags, } +/// The seed writers that the usable indices in `indices` request for the +/// top-level columns of `schema`, plus, when `config` is set, a zone map seed +/// of the configured size for every other column the zone map supports. +/// +/// `dataset` resolves index details that are not inline in the metadata; it +/// only has to share its index store with `indices`, which may belong to a +/// manifest that is still being built. async fn seed_writers_for( dataset: &Dataset, indices: &[IndexMetadata], schema: &Schema, + config: Option, purpose: SeedWriterPurpose, ) -> Result>> { let mut writers: Vec> = Vec::new(); @@ -226,6 +306,22 @@ async fn seed_writers_for( writers.push(writer); } } + // A column served by a seeded index follows that index; the configured + // size only applies to the rest. + let config_columns: Vec<_> = config + .map(|config| { + schema + .fields + .iter() + .filter(|field| { + !zone_map_columns.contains_key(&field.id) + && !other_columns.contains(&field.id) + && config_seed_supports(field) + }) + .map(|field| (field, config.rows_per_zone)) + .collect() + }) + .unwrap_or_default(); for (field_id, consumers) in zone_map_columns { let Some(field) = schema.fields.iter().find(|f| f.id == field_id) else { continue; @@ -274,9 +370,58 @@ async fn seed_writers_for( .with_null_positions(positions), )); } + // Configured seeds have no index whose null bitmap they could feed. A + // writer that cannot be created is skipped rather than failing the write. + for (field, rows_per_zone) in config_columns { + match ZoneMapSeedWriter::new(&field.name, rows_per_zone, field.data_type()) { + Ok(writer) => writers.push(Box::new(writer.with_null_positions(false))), + Err(err) => log::debug!( + "column {}: no configured zone write seed ({err})", + field.name + ), + } + } Ok(writers) } +/// Whether the dataset config seeds `field`: flat scalar columns only, whose +/// zone statistics are cheap to collect on every write. Blob and +/// extension-typed columns are excluded because the written values are not +/// the column's logical values. +fn config_seed_supports(field: &Field) -> bool { + if field.is_blob() || field.is_blob_v2() || field.extension_name().is_some() { + return false; + } + matches!( + field.data_type(), + DataType::Boolean + | DataType::Int8 + | DataType::Int16 + | DataType::Int32 + | DataType::Int64 + | DataType::UInt8 + | DataType::UInt16 + | DataType::UInt32 + | DataType::UInt64 + | DataType::Float16 + | DataType::Float32 + | DataType::Float64 + | DataType::Date32 + | DataType::Date64 + | DataType::Time32(_) + | DataType::Time64(_) + | DataType::Timestamp(_, _) + | DataType::Duration(_) + | DataType::Utf8 + | DataType::LargeUtf8 + | DataType::Binary + | DataType::LargeBinary + | DataType::FixedSizeBinary(_) + | DataType::Decimal128(_, _) + | DataType::Decimal256(_, _) + ) +} + /// The feature flags the seeds of `writers` require, combined. fn required_seed_feature_flags(writers: &[Box]) -> u64 { writers @@ -285,12 +430,13 @@ fn required_seed_feature_flags(writers: &[Box]) -> u64 { } /// Set, in both feature words of a manifest being built, the flags required -/// by every seed its indices request. +/// by every seed its indices or its zone write seed config request. /// /// `indices` is the prepared index list of that manifest. An index that /// requests a flagged seed format activates the flags in the commit that /// publishes it (`CreateIndex` of a seeded ZoneMap), before any file carries -/// such a seed; an index left behind by a build that did not set them +/// such a seed; a commit whose config enables zone write seeds activates +/// them in that same commit; an index left behind by a build that did not set them /// activates them in the next commit of any kind. Until then the write path /// embeds no such seed ([`SeedCollector::for_write`]), and afterwards the /// flags are sticky, so no manifest references a seed its flags do not @@ -301,13 +447,15 @@ pub async fn apply_seed_feature_flags( indices: &[IndexMetadata], dataset: &Dataset, ) -> Result<()> { - if indices.is_empty() { + let config = ZoneWriteSeedsConfig::from_config(&manifest.config); + if indices.is_empty() && config.is_none() { return Ok(()); } let writers = seed_writers_for( dataset, indices, &manifest.schema, + config, SeedWriterPurpose::FeatureFlags, ) .await?; @@ -320,6 +468,8 @@ pub async fn apply_seed_feature_flags( #[cfg(test)] mod tests { use super::*; + use std::sync::Arc; + use arrow_array::ArrayRef; use arrow_schema::DataType; use bytes::Bytes; @@ -352,6 +502,100 @@ mod tests { } } + #[rstest::rstest] + #[case::absent(&[], None)] + #[case::disabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")], None)] + #[case::size_without_enabled(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], None)] + #[case::unparsable_enabled( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], + None + )] + #[case::default_size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")], Some(ROWS_PER_ZONE_DEFAULT))] + #[case::explicit_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], + Some(16) + )] + #[case::zero_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")], + Some(ROWS_PER_ZONE_DEFAULT) + )] + #[case::negative_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")], + Some(ROWS_PER_ZONE_DEFAULT) + )] + #[case::unparsable_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")], + Some(ROWS_PER_ZONE_DEFAULT) + )] + fn test_zone_write_seeds_config_from_config( + #[case] entries: &[(&str, &str)], + #[case] expected_rows_per_zone: Option, + ) { + let config: HashMap = entries + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(); + assert_eq!( + ZoneWriteSeedsConfig::from_config(&config), + expected_rows_per_zone.map(|rows_per_zone| ZoneWriteSeedsConfig { rows_per_zone }) + ); + } + + #[rstest::rstest] + #[case::boolean(DataType::Boolean, true)] + #[case::int64(DataType::Int64, true)] + #[case::uint8(DataType::UInt8, true)] + #[case::float16(DataType::Float16, true)] + #[case::date32(DataType::Date32, true)] + #[case::time64(DataType::Time64(arrow_schema::TimeUnit::Nanosecond), true)] + #[case::timestamp_tz( + DataType::Timestamp(arrow_schema::TimeUnit::Millisecond, Some("UTC".into())), + true + )] + #[case::duration(DataType::Duration(arrow_schema::TimeUnit::Second), true)] + #[case::utf8(DataType::Utf8, true)] + #[case::large_binary(DataType::LargeBinary, true)] + #[case::fixed_size_binary(DataType::FixedSizeBinary(16), true)] + #[case::decimal128(DataType::Decimal128(10, 2), true)] + #[case::utf8_view(DataType::Utf8View, false)] + #[case::null(DataType::Null, false)] + #[case::fixed_size_list( + DataType::FixedSizeList( + Arc::new(arrow_schema::Field::new("item", DataType::Float32, true)), + 4 + ), + false + )] + #[case::list( + DataType::List(Arc::new(arrow_schema::Field::new("item", DataType::Int32, true))), + false + )] + #[case::struct_( + DataType::Struct(vec![arrow_schema::Field::new("a", DataType::Int32, true)].into()), + false + )] + #[case::dictionary( + DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), + false + )] + fn test_config_seed_supports_type(#[case] data_type: DataType, #[case] expected: bool) { + let field = Field::try_from(&arrow_schema::Field::new("col", data_type, true)).unwrap(); + assert_eq!(config_seed_supports(&field), expected); + } + + #[test] + fn test_config_seed_skips_blob_columns() { + let blob_v2 = Field::try_from(&crate::blob::blob_field("blob", true)).unwrap(); + assert!(!config_seed_supports(&blob_v2)); + let legacy_blob = Field::try_from( + &arrow_schema::Field::new("blob", DataType::LargeBinary, true).with_metadata( + HashMap::from([(lance_arrow::BLOB_META_KEY.to_string(), "true".to_string())]), + ), + ) + .unwrap(); + assert!(!config_seed_supports(&legacy_blob)); + } + #[test] fn test_required_flags_follow_the_seed_format() { let plain: Vec> = vec![Box::new(PlainSeedWriter)]; From 1e00abbc6956637eeefbd69d6f9c7fa1e4f7a0f0 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 17:40:40 -0800 Subject: [PATCH 02/23] feat: validate zone write seed config when it is set Reject an invalid lance.zone_write_seeds.* value in the commit that sets it, as the auto-cleanup keys are validated, instead of falling back on later writes. Add lifecycle, per-type round-trip and binary-copy carry tests. Co-Authored-By: Claude --- rust/lance-table/src/feature_flags.rs | 84 ++++ .../src/transaction/manifest_build.rs | 33 +- .../dataset/tests/dataset_zone_map_seeds.rs | 379 ++++++++++++++++++ rust/lance/src/dataset/write/seeds.rs | 72 ++-- 4 files changed, 536 insertions(+), 32 deletions(-) diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index 7bc1c7c7086..1502ac57dce 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -308,6 +308,55 @@ pub fn validate_auto_cleanup_config(manifest: &Manifest) -> Result<()> { Ok(()) } +/// Prefix of the dataset config keys that control zone write seeds. +pub const ZONE_WRITE_SEEDS_CONFIG_PREFIX: &str = "lance.zone_write_seeds."; +/// Dataset config key that enables zone map seeds for columns without a +/// seeded ZoneMap index (`"true"` / `"false"`). +pub const ZONE_WRITE_SEEDS_ENABLED_KEY: &str = "lance.zone_write_seeds.enabled"; +/// Dataset config key for the rows per seed zone of those columns. +pub const ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY: &str = "lance.zone_write_seeds.rows_per_zone"; + +/// Validate a change to the zone write seed configuration. +/// +/// `lance.zone_write_seeds.enabled` must be `"true"` or `"false"`, and +/// `lance.zone_write_seeds.rows_per_zone` an integer in `1..=u32::MAX`: +/// per-zone null and NaN counts are 32-bit, as are the row offsets a zone +/// spans within a fragment. No other key may use the prefix. Call before +/// publishing a change to these keys. +pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { + for (key, value) in manifest.config.iter() { + if !key.starts_with(ZONE_WRITE_SEEDS_CONFIG_PREFIX) { + continue; + } + match key.as_str() { + ZONE_WRITE_SEEDS_ENABLED_KEY => { + if value != "true" && value != "false" { + return Err(Error::invalid_input(format!( + "{key} must be \"true\" or \"false\", got {value:?}" + ))); + } + } + ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY => { + let valid = value + .parse::() + .is_ok_and(|rows| rows > 0 && rows <= u64::from(u32::MAX)); + if !valid { + return Err(Error::invalid_input(format!( + "{key} must be an integer between 1 and {}, got {value:?}", + u32::MAX + ))); + } + } + _ => { + return Err(Error::invalid_input(format!( + "Unknown zone write seeds configuration key: {key}={value:?}" + ))); + } + } + } + Ok(()) +} + /// Set the reader and writer feature flags in the manifest based on the contents of the manifest. pub fn apply_feature_flags( manifest: &mut Manifest, @@ -1016,6 +1065,41 @@ mod tests { assert_eq!(destination.writer_feature_flags, FLAG_ZONE_WRITE_SEEDS); } + #[rstest::rstest] + #[case::absent(&[])] + #[case::enabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")])] + #[case::disabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")])] + #[case::size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "8")])] + #[case::size_without_enabled(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "1")])] + #[case::largest_size(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967295")])] + #[case::unrelated_key(&[("lance.zone_write_seedsx", "1"), ("other.key", "x")])] + fn test_zone_write_seeds_config_accepts_valid_values(#[case] entries: &[(&str, &str)]) { + let mut manifest = empty_manifest(); + for (key, value) in entries { + manifest.config.insert(key.to_string(), value.to_string()); + } + validate_zone_write_seeds_config(&manifest).unwrap(); + } + + #[rstest::rstest] + #[case::enabled_yes(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes")] + #[case::enabled_uppercase(ZONE_WRITE_SEEDS_ENABLED_KEY, "TRUE")] + #[case::enabled_empty(ZONE_WRITE_SEEDS_ENABLED_KEY, "")] + #[case::zero_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")] + #[case::negative_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")] + #[case::garbage_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")] + #[case::too_large_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")] + #[case::unknown_key("lance.zone_write_seeds.rows_per_zonee", "8")] + fn test_zone_write_seeds_config_rejects_invalid_values(#[case] key: &str, #[case] value: &str) { + let mut manifest = empty_manifest(); + manifest.config.insert(key.to_string(), value.to_string()); + let error = validate_zone_write_seeds_config(&manifest).unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. }), "{error}"); + let message = error.to_string(); + assert!(message.contains(key), "{message}"); + assert!(message.contains(&format!("{value:?}")), "{message}"); + } + #[test] fn test_zone_write_seeds_require_both_feature_bits() { for (reader, writer) in [(true, false), (false, true)] { diff --git a/rust/lance-table/src/transaction/manifest_build.rs b/rust/lance-table/src/transaction/manifest_build.rs index 268442f52ad..48faca53e5d 100644 --- a/rust/lance-table/src/transaction/manifest_build.rs +++ b/rust/lance-table/src/transaction/manifest_build.rs @@ -12,10 +12,11 @@ use crate::feature_flags::{ FLAG_COVERED_INDEX_METADATA, FLAG_FRAGMENT_REUSE_INDEX, FLAG_INDEPENDENT_COVERING_FIELDS, - FLAG_MANAGED_BLOBS, FLAG_NON_REUSABLE_FIELD_IDS, FLAG_STABLE_ROW_IDS, apply_feature_flags, - apply_index_object_metadata_flag, apply_row_addr_index_feature_flag, ensure_can_read_manifest, - ensure_can_write_manifest, inherit_sticky_feature_flags, managed_blobs_enabled, - validate_auto_cleanup_config, validate_non_reusable_field_id_flags, + FLAG_MANAGED_BLOBS, FLAG_NON_REUSABLE_FIELD_IDS, FLAG_STABLE_ROW_IDS, + ZONE_WRITE_SEEDS_CONFIG_PREFIX, apply_feature_flags, apply_index_object_metadata_flag, + apply_row_addr_index_feature_flag, ensure_can_read_manifest, ensure_can_write_manifest, + inherit_sticky_feature_flags, managed_blobs_enabled, validate_auto_cleanup_config, + validate_non_reusable_field_id_flags, validate_zone_write_seeds_config, }; use crate::format::clustering::{ChangedReferences, validate_clustering_of}; @@ -141,6 +142,27 @@ fn changes_auto_cleanup_config(operation: &Operation) -> bool { } } +fn changes_zone_write_seeds_config(operation: &Operation) -> bool { + let is_zone_write_seeds_key = |key: &str| key.starts_with(ZONE_WRITE_SEEDS_CONFIG_PREFIX); + match operation { + Operation::Overwrite { + config_upsert_values: Some(values), + .. + } => values.keys().any(|key| is_zone_write_seeds_key(key)), + Operation::UpdateConfig { + config_updates: Some(update), + .. + } => { + update.replace + || update + .update_entries + .iter() + .any(|entry| is_zone_write_seeds_key(&entry.key)) + } + _ => false, + } +} + /// Re-encode inline row id sequences in their smallest wire form when the /// table has opted in. /// @@ -2058,6 +2080,9 @@ impl Transaction { if changes_auto_cleanup_config(&self.operation) { validate_auto_cleanup_config(&manifest)?; } + if changes_zone_write_seeds_config(&self.operation) { + validate_zone_write_seeds_config(&manifest)?; + } apply_range_segments(&mut manifest, current_manifest)?; diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index fbc621f9af4..76ee6da75e4 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -2887,3 +2887,382 @@ async fn test_binary_copy_declares_configured_rows_per_zone() { ); } } + +/// Setting an invalid zone write seed value is rejected by its commit and +/// leaves the config as it was; unrelated config changes still commit. +#[rstest::rstest] +#[case::enabled(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes")] +#[case::rows_per_zone(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")] +#[tokio::test] +async fn test_config_rejects_invalid_zone_write_seeds_value( + #[case] key: &'static str, + #[case] value: &'static str, +) { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + let before = dataset.config().clone(); + let version = dataset.manifest.version; + + let err = dataset.update_config([(key, value)]).await.unwrap_err(); + assert!(err.to_string().contains(key), "{err}"); + assert_eq!(dataset.config(), &before); + let reopened = Dataset::open(dir.as_str()).await.unwrap(); + assert_eq!(reopened.manifest.version, version); + assert_eq!(reopened.config(), &before); + + dataset + .update_config([("app.owner", "analytics")]) + .await + .unwrap(); + assert_eq!( + dataset.config().get("app.owner").map(String::as_str), + Some("analytics") + ); + assert_eq!( + dataset + .config() + .get(ZONE_WRITE_SEEDS_ENABLED_KEY) + .map(String::as_str), + Some("true") + ); +} + +/// Disabling the setting stops seeding new files while the flags and the +/// seeds already written stay; re-enabling with another size seeds new files +/// at that size, also after a reopen. +#[tokio::test] +async fn test_config_seeds_lifecycle() { + const RESIZED_ROWS_PER_ZONE: u64 = 8; + + async fn assert_locators(dataset: &Dataset, expected: &[Option]) { + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), expected.len()); + for (fragment, expected) in fragments.iter().zip(expected) { + for column in CONFIG_COLUMNS { + assert_eq!( + seed_locator_rows_per_zone(dataset, fragment, column).await, + *expected, + "fragment {}, column {column}", + fragment.id + ); + } + } + } + + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 10..20).await; + assert_locators(&dataset, &[None, Some(ROWS_PER_ZONE)]).await; + + dataset + .update_config([(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")]) + .await + .unwrap(); + append_config_rows(&mut dataset, 20..30).await; + assert_seed_flags_set(&dataset); + assert_locators(&dataset, &[None, Some(ROWS_PER_ZONE), None]).await; + + enable_zone_write_seeds(&mut dataset, RESIZED_ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 30..40).await; + assert_locators( + &dataset, + &[None, Some(ROWS_PER_ZONE), None, Some(RESIZED_ROWS_PER_ZONE)], + ) + .await; + + let mut dataset = Dataset::open(dir.as_str()).await.unwrap(); + append_config_rows(&mut dataset, 40..50).await; + assert_locators( + &dataset, + &[ + None, + Some(ROWS_PER_ZONE), + None, + Some(RESIZED_ROWS_PER_ZONE), + Some(RESIZED_ROWS_PER_ZONE), + ], + ) + .await; +} + +/// Indexed results of `filters` on `dataset` equal those of a scan without +/// scalar indices, compared as sorted `id` lists. +async fn assert_indexed_ids_match_scan(dataset: &Dataset, filters: &[&str], context: &str) { + use arrow::array::AsArray; + use arrow::datatypes::Int64Type; + + fn sorted_ids(batch: &RecordBatch) -> Vec { + let mut ids = batch["id"].as_primitive::().values().to_vec(); + ids.sort_unstable(); + ids + } + + for filter in filters { + let mut indexed = dataset.scan(); + indexed.filter(filter).unwrap().project(&["id"]).unwrap(); + let indexed = sorted_ids(&indexed.try_into_batch().await.unwrap()); + let mut unindexed = dataset.scan(); + unindexed + .use_scalar_index(false) + .filter(filter) + .unwrap() + .project(&["id"]) + .unwrap(); + let expected = sorted_ids(&unindexed.try_into_batch().await.unwrap()); + assert!(!expected.is_empty(), "{context}: filter {filter}"); + assert_eq!(indexed, expected, "{context}: filter {filter}"); + } +} + +/// ZoneMap params that build from seeds without a null bitmap, which +/// configured seeds cannot feed. +fn config_seed_index_params(rows_per_zone: u64) -> ScalarIndexParams { + ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ + "rows_per_zone": rows_per_zone, + "use_seeds": true, + "store_null_bitmap": false, + })) +} + +fn typed_schema(data_type: &DataType) -> Arc { + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int64, false), + ArrowField::new("col", data_type.clone(), true), + ])) +} + +/// Deterministic values in `0..61` with a null every ninth row. +fn typed_value(i: i64) -> Option { + (i % 9 != 4).then_some((i * 7) % 61) +} + +/// [`typed_value`] as a float, with NaN, infinities and negative zero mixed in. +fn typed_float(i: i64) -> Option { + typed_value(i).map(|v| match i % 13 { + 0 => f64::NAN, + 1 => f64::INFINITY, + 2 => f64::NEG_INFINITY, + 3 => -0.0, + _ => v as f64 / 2.0, + }) +} + +fn typed_column(data_type: &DataType, ids: std::ops::Range) -> ArrayRef { + use arrow_array::{ + BooleanArray, Date32Array, Decimal128Array, DurationMicrosecondArray, FixedSizeBinaryArray, + Float32Array, Float64Array, Int8Array, LargeBinaryArray, LargeStringArray, + Time32SecondArray, TimestampMillisecondArray, TimestampNanosecondArray, UInt16Array, + UInt64Array, + }; + + let values = ids.clone().map(typed_value); + match data_type { + DataType::Boolean => Arc::new(BooleanArray::from_iter( + values.map(|v| v.map(|v| v % 3 == 0)), + )), + DataType::Int8 => Arc::new(Int8Array::from_iter(values.map(|v| v.map(|v| v as i8)))), + DataType::Int32 => Arc::new(Int32Array::from_iter(values.map(|v| v.map(|v| v as i32)))), + DataType::Int64 => Arc::new(Int64Array::from_iter(values)), + DataType::UInt16 => Arc::new(UInt16Array::from_iter(values.map(|v| v.map(|v| v as u16)))), + DataType::UInt64 => Arc::new(UInt64Array::from_iter(values.map(|v| v.map(|v| v as u64)))), + DataType::Float32 => Arc::new(Float32Array::from_iter( + ids.map(|i| typed_float(i).map(|v| v as f32)), + )), + DataType::Float64 => Arc::new(Float64Array::from_iter(ids.map(typed_float))), + DataType::Date32 => Arc::new(Date32Array::from_iter( + values.map(|v| v.map(|v| 19_000 + v as i32)), + )), + DataType::Timestamp(TimeUnit::Millisecond, None) => { + Arc::new(TimestampMillisecondArray::from_iter( + values.map(|v| v.map(|v| 1_700_000_000_000 + v * 1_000)), + )) + } + DataType::Timestamp(TimeUnit::Nanosecond, Some(tz)) => Arc::new( + TimestampNanosecondArray::from_iter( + values.map(|v| v.map(|v| 1_700_000_000_000_000_000 + v * 1_000)), + ) + .with_timezone(tz.clone()), + ), + DataType::Duration(TimeUnit::Microsecond) => Arc::new(DurationMicrosecondArray::from_iter( + values.map(|v| v.map(|v| v * 1_000)), + )), + DataType::Time32(TimeUnit::Second) => Arc::new(Time32SecondArray::from_iter( + values.map(|v| v.map(|v| (v * 60) as i32)), + )), + DataType::Utf8 => Arc::new(StringArray::from_iter( + values.map(|v| v.map(|v| format!("v{v:03}"))), + )), + DataType::LargeUtf8 => Arc::new(LargeStringArray::from_iter( + values.map(|v| v.map(|v| format!("v{v:03}"))), + )), + DataType::Binary => Arc::new(BinaryArray::from_iter( + values.map(|v| v.map(|v| v.to_be_bytes().to_vec())), + )), + DataType::LargeBinary => Arc::new(LargeBinaryArray::from_iter( + values.map(|v| v.map(|v| v.to_be_bytes().to_vec())), + )), + DataType::FixedSizeBinary(4) => Arc::new( + FixedSizeBinaryArray::try_from_sparse_iter_with_size( + values.map(|v| v.map(|v| (v as u32).to_be_bytes())), + 4, + ) + .unwrap(), + ), + DataType::Decimal128(precision, scale) => Arc::new( + Decimal128Array::from_iter(values.map(|v| v.map(|v| v as i128 * 10_000))) + .with_precision_and_scale(*precision, *scale) + .unwrap(), + ), + other => panic!("no generator for {other}"), + } +} + +fn typed_rows(data_type: &DataType, ids: std::ops::Range) -> RecordBatch { + RecordBatch::try_new( + typed_schema(data_type), + vec![ + Arc::new(Int64Array::from_iter_values(ids.clone())), + typed_column(data_type, ids), + ], + ) + .unwrap() +} + +const INT_FILTERS: &[&str] = &["col >= 10 AND col < 30", "col = 21"]; +const FLOAT_FILTERS: &[&str] = &["col >= 2.0 AND col < 20.0", "col > 1000.0"]; +const STRING_FILTERS: &[&str] = &["col >= 'v010' AND col < 'v030'", "col = 'v021'"]; + +/// For every candidate type family, an append after enabling the setting +/// seeds the column, a ZoneMap index created afterwards reuses that seed for +/// the appended fragment, and indexed filters match a scan. `filters` adds +/// value predicates to the null checks every type runs. +#[rstest::rstest] +#[case::boolean(DataType::Boolean, &["col = true"])] +#[case::int8(DataType::Int8, INT_FILTERS)] +#[case::int32(DataType::Int32, INT_FILTERS)] +#[case::int64(DataType::Int64, INT_FILTERS)] +#[case::uint16(DataType::UInt16, INT_FILTERS)] +#[case::uint64(DataType::UInt64, INT_FILTERS)] +#[case::float32(DataType::Float32, FLOAT_FILTERS)] +#[case::float64(DataType::Float64, FLOAT_FILTERS)] +#[case::date32(DataType::Date32, &[])] +#[case::timestamp_ms(DataType::Timestamp(TimeUnit::Millisecond, None), &[])] +#[case::timestamp_ns_utc(DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())), &[])] +#[case::duration_us(DataType::Duration(TimeUnit::Microsecond), &[])] +#[case::time32_s(DataType::Time32(TimeUnit::Second), &[])] +#[case::utf8(DataType::Utf8, STRING_FILTERS)] +#[case::large_utf8(DataType::LargeUtf8, STRING_FILTERS)] +#[case::binary(DataType::Binary, &[])] +#[case::large_binary(DataType::LargeBinary, &[])] +#[case::fixed_size_binary(DataType::FixedSizeBinary(4), &[])] +#[case::decimal128(DataType::Decimal128(38, 4), &[])] +#[tokio::test] +async fn test_config_seed_round_trip_per_type( + #[case] data_type: DataType, + #[case] filters: &'static [&'static str], +) { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + const TYPED_ROWS_PER_ZONE: u64 = 8; + + let dir = TempStrDir::default(); + let schema = typed_schema(&data_type); + let mut dataset = Dataset::write( + RecordBatchIterator::new([Ok(typed_rows(&data_type, 0..40))], schema.clone()), + dir.as_str(), + None, + ) + .await + .unwrap(); + enable_zone_write_seeds(&mut dataset, TYPED_ROWS_PER_ZONE).await; + dataset + .append( + RecordBatchIterator::new([Ok(typed_rows(&data_type, 40..140))], schema), + None, + ) + .await + .unwrap(); + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), 2, "{data_type}"); + let appended = fragments[1].id; + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], "col").await, + Some(TYPED_ROWS_PER_ZONE), + "{data_type}" + ); + + let params = config_seed_index_params(TYPED_ROWS_PER_ZONE); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["col"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1, "{data_type}"); + assert_eq!(reports[0].reused_fragments, vec![appended], "{data_type}"); + + let mut all_filters: Vec<&str> = filters.to_vec(); + all_filters.extend(["col IS NULL", "col IS NOT NULL"]); + assert_indexed_ids_match_scan(&dataset, &all_filters, &data_type.to_string()).await; +} + +/// Binary-copy compaction of files whose configured seeds were written at +/// different sizes still carries a seed, and an index built from it answers +/// filters like a scan. +#[tokio::test] +async fn test_binary_copy_carries_config_seeds_of_different_sizes() { + const RESIZED_ROWS_PER_ZONE: u64 = 8; + + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 10..20).await; + enable_zone_write_seeds(&mut dataset, RESIZED_ROWS_PER_ZONE).await; + append_config_rows(&mut dataset, 20..30).await; + // Drop the unseeded first fragment so every compaction input is seeded. + dataset.delete("id < 10").await.unwrap(); + let inputs = dataset.fragments().clone(); + assert_eq!(inputs.len(), 2); + assert_eq!( + seed_locator_rows_per_zone(&dataset, &inputs[0], "val").await, + Some(ROWS_PER_ZONE) + ); + assert_eq!( + seed_locator_rows_per_zone(&dataset, &inputs[1], "val").await, + Some(RESIZED_ROWS_PER_ZONE) + ); + + let metrics = force_binary_copy(&mut dataset, 1_000_000).await; + assert_eq!(metrics.fragments_added, 1); + let output = dataset.fragments()[0].clone(); + assert_eq!(output.physical_rows, Some(20)); + for column in CONFIG_COLUMNS { + assert!( + seed_locator_rows_per_zone(&dataset, &output, column) + .await + .is_some(), + "column {column}" + ); + } + + dataset + .create_index( + &["val"], + IndexType::ZoneMap, + None, + &config_seed_index_params(RESIZED_ROWS_PER_ZONE), + false, + ) + .await + .unwrap(); + assert_indexed_ids_match_scan( + &dataset, + &["val >= 12 AND val < 22", "val = 25", "val IS NULL"], + "binary copy", + ) + .await; +} diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index f702dcf2efe..cb38eeeabfa 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -20,20 +20,25 @@ //! asks for them ([`ZoneWriteSeedsConfig`]): //! //! - `lance.zone_write_seeds.enabled`: `"true"` collects a zone map seed for -//! every top-level column of a supported scalar type that no seeded +//! every top-level column of a candidate scalar type that no seeded //! ZoneMap index covers, so a ZoneMap index created later can be built //! from seeds instead of scanning. Nested, vector, dictionary, view, //! extension and blob columns are never seeded by the config. Absent -//! or `"false"` disables this; any other value is treated as disabled with -//! a warning. +//! or `"false"` disables this. //! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those -//! columns, a positive integer. Absent, zero or unparsable values use -//! [`ROWS_PER_ZONE_DEFAULT`] (the latter two with a warning). +//! columns, an integer in `1..=u32::MAX`. Absent, it is +//! [`ROWS_PER_ZONE_DEFAULT`]. +//! +//! Setting either key to an invalid value, or any other key under +//! `lance.zone_write_seeds.`, is rejected by the commit that sets it. //! //! A column with a seeded ZoneMap index keeps following that index's -//! `rows_per_zone`. Enable the setting with [`Dataset::update_config`]; the -//! commit that sets it also sets the seed feature flags, and writes based on -//! later versions embed the seeds. +//! `rows_per_zone`. When a seeded index's requirements cannot be resolved +//! for a file (its details or stored null-bitmap policy cannot be read), the +//! column falls back to the configured seed if the setting is on. Enable the +//! setting with [`Dataset::update_config`]; the commit that sets it also sets +//! the seed feature flags, and writes based on later versions embed the +//! seeds. use std::collections::{HashMap, HashSet}; @@ -45,6 +50,9 @@ use lance_file::version::ConcreteFileVersion; use lance_index::pbold; use lance_index::scalar::seed::IndexSeedWriter; use lance_index::scalar::zonemap::{ROWS_PER_ZONE_DEFAULT, ZoneMapSeedWriter}; +pub use lance_table::feature_flags::{ + ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, +}; use lance_table::format::{IndexMetadata, Manifest}; use super::GenericWriter; @@ -57,12 +65,6 @@ use crate::index::{loading::load_all_indices, segment::index_is_usable}; /// reported once per process and at debug level afterwards. static SEED_CONFLICT_WARNED: std::sync::Once = std::sync::Once::new(); -/// Dataset config key that enables zone map seeds for columns without a -/// seeded ZoneMap index (`"true"` / `"false"`). -pub const ZONE_WRITE_SEEDS_ENABLED_KEY: &str = "lance.zone_write_seeds.enabled"; -/// Dataset config key for the rows per seed zone of those columns. -pub const ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY: &str = "lance.zone_write_seeds.rows_per_zone"; - /// The dataset-level zone write seed setting, parsed from the dataset config. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ZoneWriteSeedsConfig { @@ -73,9 +75,12 @@ pub struct ZoneWriteSeedsConfig { impl ZoneWriteSeedsConfig { /// The setting in `config`, or `None` when it is disabled. /// - /// Invalid values never fail a write: an unparsable `enabled` disables - /// the setting and an invalid `rows_per_zone` falls back to - /// [`ROWS_PER_ZONE_DEFAULT`], both with a warning. + /// Values are validated when they are set + /// (`validate_zone_write_seeds_config`), so this read is lenient: an + /// unparsable `enabled` disables the setting and an invalid + /// `rows_per_zone` falls back to [`ROWS_PER_ZONE_DEFAULT`], both with a + /// warning. That only matters for a manifest written by a build that did + /// not validate them. pub fn from_config(config: &HashMap) -> Option { let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; match enabled.parse::() { @@ -92,11 +97,12 @@ impl ZoneWriteSeedsConfig { let rows_per_zone = match config.get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) { None => ROWS_PER_ZONE_DEFAULT, Some(value) => match value.parse::() { - Ok(rows) if rows > 0 => rows, + Ok(rows) if rows > 0 && rows <= u64::from(u32::MAX) => rows, _ => { log::warn!( - "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected a \ - positive integer; using {ROWS_PER_ZONE_DEFAULT}" + "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected an \ + integer between 1 and {}; using {ROWS_PER_ZONE_DEFAULT}", + u32::MAX ); ROWS_PER_ZONE_DEFAULT } @@ -123,8 +129,8 @@ impl SeedCollector { /// A column gets a seed writer when an existing, usable index on it asks /// for one through its plugin and the dataset already carries the feature /// flags that seed format requires. With zone write seeds enabled in the - /// dataset config ([`ZoneWriteSeedsConfig`]), every other column the zone - /// map supports gets a zone map seed under the same flag rule. + /// dataset config ([`ZoneWriteSeedsConfig`]), every other column of a + /// candidate scalar type gets a zone map seed under the same flag rule. /// `consult_indices` is false for writes that discard the dataset's /// indices (overwrite), where seeds have no consumer. pub async fn for_write( @@ -224,7 +230,11 @@ enum SeedWriterPurpose { /// The seed writers that the usable indices in `indices` request for the /// top-level columns of `schema`, plus, when `config` is set, a zone map seed -/// of the configured size for every other column the zone map supports. +/// of the configured size for every other column of a candidate scalar type. +/// +/// When a seeded index's requirements cannot be resolved for a file (its +/// details or stored null-bitmap policy cannot be read), the column falls +/// back to the configured seed if the setting is on. /// /// `dataset` resolves index details that are not inline in the metadata; it /// only has to share its index store with `indices`, which may belong to a @@ -371,7 +381,9 @@ async fn seed_writers_for( )); } // Configured seeds have no index whose null bitmap they could feed. A - // writer that cannot be created is skipped rather than failing the write. + // column whose seed writer cannot be constructed gets no configured + // seed; errors while observing batches or finishing a seed still fail + // the write, as for index-requested seeds. for (field, rows_per_zone) in config_columns { match ZoneMapSeedWriter::new(&field.name, rows_per_zone, field.data_type()) { Ok(writer) => writers.push(Box::new(writer.with_null_positions(false))), @@ -384,10 +396,10 @@ async fn seed_writers_for( Ok(writers) } -/// Whether the dataset config seeds `field`: flat scalar columns only, whose -/// zone statistics are cheap to collect on every write. Blob and -/// extension-typed columns are excluded because the written values are not -/// the column's logical values. +/// Whether the dataset config seeds `field`: flat columns of a candidate +/// scalar type only. The list is a conservative gate, not a guarantee about +/// collection cost. Blob and extension-typed columns are excluded because +/// the written values are not the column's logical values. fn config_seed_supports(field: &Field) -> bool { if field.is_blob() || field.is_blob_v2() || field.extension_name().is_some() { return false; @@ -527,6 +539,10 @@ mod tests { &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")], Some(ROWS_PER_ZONE_DEFAULT) )] + #[case::too_large_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")], + Some(ROWS_PER_ZONE_DEFAULT) + )] fn test_zone_write_seeds_config_from_config( #[case] entries: &[(&str, &str)], #[case] expected_rows_per_zone: Option, From ec350417049d1bf02fb2501e3224734577a151e3 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 18:00:06 -0800 Subject: [PATCH 03/23] fix: leave fixed-size binary columns out of configured zone write seeds Zone statistics have no min/max for fixed-size binary, so a seed for such a column is always rejected by the index build. Also check unseeded nested columns in the test through every file of the fragment. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 33 ++++++++++--------- rust/lance/src/dataset/write/seeds.rs | 8 +++-- 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 76ee6da75e4..d9cf097550c 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -2710,14 +2710,26 @@ async fn test_config_seeds_columns_without_index() { ); } for column in UNSEEDED_CONFIG_COLUMNS { - assert_eq!( - seed_locator_rows_per_zone(&dataset, &fragments[1], column).await, - None, + assert!( + !fragment_has_seed_locator(&dataset, &fragments[1], column).await, "appended file, unsupported column {column}" ); } } +/// Whether any data file of `fragment` carries a seed locator for `column`. +/// Nested columns may have no file that stores the parent field itself. +async fn fragment_has_seed_locator(dataset: &Dataset, fragment: &Fragment, column: &str) -> bool { + let key = format!("{SEED_META_KEY_PREFIX}{column}"); + for file in &fragment.files { + let reader = open_data_file(dataset, &file.path).await; + if reader.metadata().file_schema.metadata.contains_key(&key) { + return true; + } + } + false +} + /// A snapshot that enables the setting but does not carry the seed flags /// writes no seed; its commit sets the flags and the next write is seeded. #[tokio::test] @@ -3051,10 +3063,9 @@ fn typed_float(i: i64) -> Option { fn typed_column(data_type: &DataType, ids: std::ops::Range) -> ArrayRef { use arrow_array::{ - BooleanArray, Date32Array, Decimal128Array, DurationMicrosecondArray, FixedSizeBinaryArray, - Float32Array, Float64Array, Int8Array, LargeBinaryArray, LargeStringArray, - Time32SecondArray, TimestampMillisecondArray, TimestampNanosecondArray, UInt16Array, - UInt64Array, + BooleanArray, Date32Array, Decimal128Array, DurationMicrosecondArray, Float32Array, + Float64Array, Int8Array, LargeBinaryArray, LargeStringArray, Time32SecondArray, + TimestampMillisecondArray, TimestampNanosecondArray, UInt16Array, UInt64Array, }; let values = ids.clone().map(typed_value); @@ -3103,13 +3114,6 @@ fn typed_column(data_type: &DataType, ids: std::ops::Range) -> ArrayRef { DataType::LargeBinary => Arc::new(LargeBinaryArray::from_iter( values.map(|v| v.map(|v| v.to_be_bytes().to_vec())), )), - DataType::FixedSizeBinary(4) => Arc::new( - FixedSizeBinaryArray::try_from_sparse_iter_with_size( - values.map(|v| v.map(|v| (v as u32).to_be_bytes())), - 4, - ) - .unwrap(), - ), DataType::Decimal128(precision, scale) => Arc::new( Decimal128Array::from_iter(values.map(|v| v.map(|v| v as i128 * 10_000))) .with_precision_and_scale(*precision, *scale) @@ -3156,7 +3160,6 @@ const STRING_FILTERS: &[&str] = &["col >= 'v010' AND col < 'v030'", "col = 'v021 #[case::large_utf8(DataType::LargeUtf8, STRING_FILTERS)] #[case::binary(DataType::Binary, &[])] #[case::large_binary(DataType::LargeBinary, &[])] -#[case::fixed_size_binary(DataType::FixedSizeBinary(4), &[])] #[case::decimal128(DataType::Decimal128(38, 4), &[])] #[tokio::test] async fn test_config_seed_round_trip_per_type( diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index cb38eeeabfa..816513ab01e 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -399,7 +399,9 @@ async fn seed_writers_for( /// Whether the dataset config seeds `field`: flat columns of a candidate /// scalar type only. The list is a conservative gate, not a guarantee about /// collection cost. Blob and extension-typed columns are excluded because -/// the written values are not the column's logical values. +/// the written values are not the column's logical values. FixedSizeBinary +/// is excluded at every width: the statistics accumulator computes no bounds +/// for it, and a seed without bounds is never reused. fn config_seed_supports(field: &Field) -> bool { if field.is_blob() || field.is_blob_v2() || field.extension_name().is_some() { return false; @@ -428,7 +430,6 @@ fn config_seed_supports(field: &Field) -> bool { | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary - | DataType::FixedSizeBinary(_) | DataType::Decimal128(_, _) | DataType::Decimal256(_, _) ) @@ -571,7 +572,8 @@ mod tests { #[case::duration(DataType::Duration(arrow_schema::TimeUnit::Second), true)] #[case::utf8(DataType::Utf8, true)] #[case::large_binary(DataType::LargeBinary, true)] - #[case::fixed_size_binary(DataType::FixedSizeBinary(16), true)] + #[case::fixed_size_binary_narrow(DataType::FixedSizeBinary(4), false)] + #[case::fixed_size_binary_wide(DataType::FixedSizeBinary(16), false)] #[case::decimal128(DataType::Decimal128(10, 2), true)] #[case::utf8_view(DataType::Utf8View, false)] #[case::null(DataType::Null, false)] From d2021bfa14cf4f945a200cb55e7ef929b79ab267 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 18:08:08 -0800 Subject: [PATCH 04/23] fix: validate zone write seed config on the composite commit path Check the final manifest once after all actions, as the auto-cleanup settings are checked. Assert seed reuse in the binary-copy carry test and add value predicates to the per-type round trip. Co-Authored-By: Claude --- .../src/transaction/action/apply.rs | 23 +++++--- .../src/transaction/action/config_update.rs | 52 +++++++++++++++++++ .../src/transaction/manifest_build.rs | 30 +++++++++++ .../dataset/tests/dataset_zone_map_seeds.rs | 50 ++++++++++++------ rust/lance/src/dataset/write/seeds.rs | 5 +- 5 files changed, 135 insertions(+), 25 deletions(-) diff --git a/rust/lance-table/src/transaction/action/apply.rs b/rust/lance-table/src/transaction/action/apply.rs index 1fca7afd498..668130e7eb6 100644 --- a/rust/lance-table/src/transaction/action/apply.rs +++ b/rust/lance-table/src/transaction/action/apply.rs @@ -25,8 +25,9 @@ use super::{CompositeOperation, FieldId, FieldRef, Ref}; use crate::feature_flags::{ - FLAG_MANAGED_BLOBS, apply_index_object_metadata_flag, inherit_sticky_feature_flags, - managed_blobs_enabled, validate_auto_cleanup_config, + FLAG_MANAGED_BLOBS, ZONE_WRITE_SEEDS_CONFIG_PREFIX, apply_index_object_metadata_flag, + inherit_sticky_feature_flags, managed_blobs_enabled, validate_auto_cleanup_config, + validate_zone_write_seeds_config, }; use crate::format::overlay::staleness::field_affects_index; use crate::format::{ @@ -421,11 +422,16 @@ impl<'a> ApplyState<'a> { manifest.table_metadata = table_metadata; // Only a change is validated: settings inherited as they were, even // invalid ones, must not block an unrelated commit. - if auto_cleanup_settings(¤t_manifest.config) - != auto_cleanup_settings(&manifest.config) + if settings_with_prefix(¤t_manifest.config, AUTO_CLEANUP_CONFIG_PREFIX) + != settings_with_prefix(&manifest.config, AUTO_CLEANUP_CONFIG_PREFIX) { validate_auto_cleanup_config(&manifest)?; } + if settings_with_prefix(¤t_manifest.config, ZONE_WRITE_SEEDS_CONFIG_PREFIX) + != settings_with_prefix(&manifest.config, ZONE_WRITE_SEEDS_CONFIG_PREFIX) + { + validate_zone_write_seeds_config(&manifest)?; + } // Both read the final schema and config, so they come after those land. apply_range_segments(&mut manifest, Some(current_manifest))?; if managed_blobs_enabled(&manifest.schema)? { @@ -1406,10 +1412,15 @@ fn check_schema(schema: &Schema) -> Result<()> { schema.validate() } -fn auto_cleanup_settings(config: &HashMap) -> BTreeMap<&str, &str> { +const AUTO_CLEANUP_CONFIG_PREFIX: &str = "lance.auto_cleanup."; + +fn settings_with_prefix<'a>( + config: &'a HashMap, + prefix: &str, +) -> BTreeMap<&'a str, &'a str> { config .iter() - .filter(|(key, _)| key.starts_with("lance.auto_cleanup.")) + .filter(|(key, _)| key.starts_with(prefix)) .map(|(key, value)| (key.as_str(), value.as_str())) .collect() } diff --git a/rust/lance-table/src/transaction/action/config_update.rs b/rust/lance-table/src/transaction/action/config_update.rs index bd5c0058ce4..ef93ad904ea 100644 --- a/rust/lance-table/src/transaction/action/config_update.rs +++ b/rust/lance-table/src/transaction/action/config_update.rs @@ -268,6 +268,7 @@ impl TryFrom for ConfigUpdate { #[cfg(test)] mod tests { use super::*; + use crate::feature_flags::{ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}; use crate::format::Manifest; use crate::transaction::action::test_support::{ added_field, apply, backed_manifest, footprint, @@ -608,6 +609,57 @@ mod tests { apply(&manifest, vec![set_config(&[("unrelated", Some("1"))])]).unwrap(); } + #[test] + fn test_config_update_rejects_an_invalid_zone_write_seeds_value() { + let error = apply( + &backed_manifest(), + vec![set_config(&[( + ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + Some("0"), + )])], + ) + .unwrap_err(); + + assert!( + error + .to_string() + .contains(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY), + "unexpected error: {error}" + ); + } + + /// Only the settings the whole operation leaves are validated, so a later + /// update may repair a value an earlier one set. + #[test] + fn test_config_update_validates_the_zone_write_seeds_settings_it_leaves() { + let next = apply( + &backed_manifest(), + vec![ + set_config(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, Some("0"))]), + set_config(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, Some("8"))]), + ], + ) + .unwrap(); + + assert_eq!( + next.config + .get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) + .map(String::as_str), + Some("8") + ); + } + + #[test] + fn test_zone_write_seeds_settings_invalid_before_the_commit_do_not_block_it() { + let mut manifest = backed_manifest(); + manifest + .config + .insert(ZONE_WRITE_SEEDS_ENABLED_KEY.into(), "yes".into()); + assert!(crate::feature_flags::validate_zone_write_seeds_config(&manifest).is_err()); + + apply(&manifest, vec![set_config(&[("unrelated", Some("1"))])]).unwrap(); + } + #[test] fn test_edits_to_different_keys_commute() { let update = |key: &str| { diff --git a/rust/lance-table/src/transaction/manifest_build.rs b/rust/lance-table/src/transaction/manifest_build.rs index 48faca53e5d..b58aa610b26 100644 --- a/rust/lance-table/src/transaction/manifest_build.rs +++ b/rust/lance-table/src/transaction/manifest_build.rs @@ -4269,6 +4269,36 @@ mod tests { ); } + #[test] + fn zone_write_seeds_settings_invalid_before_the_commit_do_not_block_it() { + let mut manifest = sample_manifest(); + manifest.config.insert( + crate::feature_flags::ZONE_WRITE_SEEDS_ENABLED_KEY.into(), + "yes".into(), + ); + assert!(validate_zone_write_seeds_config(&manifest).is_err()); + let transaction = Transaction::new( + manifest.version, + Operation::UpdateConfig { + config_updates: Some(crate::transaction::UpdateMap { + update_entries: vec![crate::transaction::update_map::UpdateMapEntry { + key: "unrelated".into(), + value: Some("1".into()), + }], + replace: false, + }), + table_metadata_updates: None, + schema_metadata_updates: None, + field_metadata_updates: HashMap::new(), + }, + None, + ); + + transaction + .build_manifest(Some(&manifest), vec![], "txn", &default_build_config()) + .unwrap(); + } + fn covered_index(name: &str, fields: Vec, covering_fields: Vec) -> IndexMetadata { IndexMetadata { fields, diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index d9cf097550c..21c7c650735 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3151,16 +3151,22 @@ const STRING_FILTERS: &[&str] = &["col >= 'v010' AND col < 'v030'", "col = 'v021 #[case::uint64(DataType::UInt64, INT_FILTERS)] #[case::float32(DataType::Float32, FLOAT_FILTERS)] #[case::float64(DataType::Float64, FLOAT_FILTERS)] -#[case::date32(DataType::Date32, &[])] -#[case::timestamp_ms(DataType::Timestamp(TimeUnit::Millisecond, None), &[])] +#[case::date32(DataType::Date32, &["col >= DATE '2022-02-07'"])] +#[case::timestamp_ms( + DataType::Timestamp(TimeUnit::Millisecond, None), + &["col >= TIMESTAMP '2023-11-14 22:13:50'"] +)] #[case::timestamp_ns_utc(DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())), &[])] #[case::duration_us(DataType::Duration(TimeUnit::Microsecond), &[])] -#[case::time32_s(DataType::Time32(TimeUnit::Second), &[])] +#[case::time32_s( + DataType::Time32(TimeUnit::Second), + &["col >= arrow_cast(1800, 'Time32(Second)')"] +)] #[case::utf8(DataType::Utf8, STRING_FILTERS)] #[case::large_utf8(DataType::LargeUtf8, STRING_FILTERS)] -#[case::binary(DataType::Binary, &[])] -#[case::large_binary(DataType::LargeBinary, &[])] -#[case::decimal128(DataType::Decimal128(38, 4), &[])] +#[case::binary(DataType::Binary, &["col >= X'000000000000001E'"])] +#[case::large_binary(DataType::LargeBinary, &["col >= X'000000000000001E'"])] +#[case::decimal128(DataType::Decimal128(38, 4), &["col >= 30"])] #[tokio::test] async fn test_config_seed_round_trip_per_type( #[case] data_type: DataType, @@ -3214,11 +3220,15 @@ async fn test_config_seed_round_trip_per_type( } /// Binary-copy compaction of files whose configured seeds were written at -/// different sizes still carries a seed, and an index built from it answers +/// different sizes still carries a seed, an index whose zones end at the +/// input file boundaries is built from it without a scan, and it answers /// filters like a scan. #[tokio::test] async fn test_binary_copy_carries_config_seeds_of_different_sizes() { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; const RESIZED_ROWS_PER_ZONE: u64 = 8; + // Each input holds 10 rows, so no carried record crosses a target zone. + const INDEX_ROWS_PER_ZONE: u64 = 10; let dir = TempStrDir::default(); let mut dataset = dataset_with_config_rows(dir.as_str()).await; @@ -3252,16 +3262,22 @@ async fn test_binary_copy_carries_config_seeds_of_different_sizes() { ); } - dataset - .create_index( - &["val"], - IndexType::ZoneMap, - None, - &config_seed_index_params(RESIZED_ROWS_PER_ZONE), - false, - ) - .await - .unwrap(); + let params = config_seed_index_params(INDEX_ROWS_PER_ZONE); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1); + assert_eq!(reports[0].reused_fragments, vec![output.id]); + assert!(reports[0].partial_fragments.is_empty()); + assert!(reports[0].scanned_fragments.is_empty()); + assert_eq!(reports[0].scanned_rows, 0); + assert_indexed_ids_match_scan( &dataset, &["val >= 12 AND val < 22", "val = 25", "val IS NULL"], diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 816513ab01e..648cb6a2730 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -400,8 +400,9 @@ async fn seed_writers_for( /// scalar type only. The list is a conservative gate, not a guarantee about /// collection cost. Blob and extension-typed columns are excluded because /// the written values are not the column's logical values. FixedSizeBinary -/// is excluded at every width: the statistics accumulator computes no bounds -/// for it, and a seed without bounds is never reused. +/// is excluded at every width: zone statistics compute no min/max bounds for +/// fixed-size binary values, so a seed zone holding non-null values cannot be +/// validated by an index build. fn config_seed_supports(field: &Field) -> bool { if field.is_blob() || field.is_blob_v2() || field.extension_name().is_some() { return false; From 60120951004b685f46547271b398ee0f56768847 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 18:22:14 -0800 Subject: [PATCH 05/23] test: drop the view-type case from the zone write seed type gate A Lance field stores view types as their base string or binary type, so the case asserted on a type the gate never sees. Co-Authored-By: Claude --- rust/lance/src/dataset/write/seeds.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 648cb6a2730..c74b85b199e 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -22,7 +22,7 @@ //! - `lance.zone_write_seeds.enabled`: `"true"` collects a zone map seed for //! every top-level column of a candidate scalar type that no seeded //! ZoneMap index covers, so a ZoneMap index created later can be built -//! from seeds instead of scanning. Nested, vector, dictionary, view, +//! from seeds instead of scanning. Nested, vector, dictionary, //! extension and blob columns are never seeded by the config. Absent //! or `"false"` disables this. //! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those @@ -576,7 +576,6 @@ mod tests { #[case::fixed_size_binary_narrow(DataType::FixedSizeBinary(4), false)] #[case::fixed_size_binary_wide(DataType::FixedSizeBinary(16), false)] #[case::decimal128(DataType::Decimal128(10, 2), true)] - #[case::utf8_view(DataType::Utf8View, false)] #[case::null(DataType::Null, false)] #[case::fixed_size_list( DataType::FixedSizeList( From 23f9e9718ec632cff2183fac71fa7cda149d7075 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 21:05:32 -0800 Subject: [PATCH 06/23] feat: record null positions in configured zone write seeds Add lance.zone_write_seeds.store_null_bitmap (default true) so seeds collected from the dataset config can serve a zone map that stores a null bitmap. Co-Authored-By: Claude --- rust/lance-table/src/feature_flags.rs | 15 +++- .../dataset/tests/dataset_zone_map_seeds.rs | 71 +++++++++++++++++- rust/lance/src/dataset/write.rs | 5 +- rust/lance/src/dataset/write/seeds.rs | 75 ++++++++++++++----- 4 files changed, 139 insertions(+), 27 deletions(-) diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index 1502ac57dce..2fe37d0723c 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -315,11 +315,16 @@ pub const ZONE_WRITE_SEEDS_CONFIG_PREFIX: &str = "lance.zone_write_seeds."; pub const ZONE_WRITE_SEEDS_ENABLED_KEY: &str = "lance.zone_write_seeds.enabled"; /// Dataset config key for the rows per seed zone of those columns. pub const ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY: &str = "lance.zone_write_seeds.rows_per_zone"; +/// Dataset config key that makes those seeds record null positions, so they +/// can serve a ZoneMap index that stores a null bitmap (`"true"` / `"false"`, +/// absent means `"true"`). +pub const ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY: &str = "lance.zone_write_seeds.store_null_bitmap"; /// Validate a change to the zone write seed configuration. /// -/// `lance.zone_write_seeds.enabled` must be `"true"` or `"false"`, and -/// `lance.zone_write_seeds.rows_per_zone` an integer in `1..=u32::MAX`: +/// `lance.zone_write_seeds.enabled` and +/// `lance.zone_write_seeds.store_null_bitmap` must be `"true"` or `"false"`, +/// and `lance.zone_write_seeds.rows_per_zone` an integer in `1..=u32::MAX`: /// per-zone null and NaN counts are 32-bit, as are the row offsets a zone /// spans within a fragment. No other key may use the prefix. Call before /// publishing a change to these keys. @@ -329,7 +334,7 @@ pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { continue; } match key.as_str() { - ZONE_WRITE_SEEDS_ENABLED_KEY => { + ZONE_WRITE_SEEDS_ENABLED_KEY | ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY => { if value != "true" && value != "false" { return Err(Error::invalid_input(format!( "{key} must be \"true\" or \"false\", got {value:?}" @@ -1072,6 +1077,8 @@ mod tests { #[case::size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "8")])] #[case::size_without_enabled(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "1")])] #[case::largest_size(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967295")])] + #[case::null_bitmap(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")])] + #[case::no_null_bitmap(&[(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false")])] #[case::unrelated_key(&[("lance.zone_write_seedsx", "1"), ("other.key", "x")])] fn test_zone_write_seeds_config_accepts_valid_values(#[case] entries: &[(&str, &str)]) { let mut manifest = empty_manifest(); @@ -1085,6 +1092,8 @@ mod tests { #[case::enabled_yes(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes")] #[case::enabled_uppercase(ZONE_WRITE_SEEDS_ENABLED_KEY, "TRUE")] #[case::enabled_empty(ZONE_WRITE_SEEDS_ENABLED_KEY, "")] + #[case::null_bitmap_yes(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")] + #[case::null_bitmap_empty(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "")] #[case::zero_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")] #[case::negative_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")] #[case::garbage_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")] diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 21c7c650735..6727835ef75 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -45,6 +45,7 @@ use crate::dataset::transaction::{DataReplacementGroup, Operation, Transaction}; use crate::dataset::write::merge_insert::{WhenMatched, WhenNotMatched}; use crate::dataset::write::seeds::{ ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, }; use crate::dataset::{ CommitBuilder, DATA_DIR, InsertBuilder, MergeInsertBuilder, MergeInsertWriteMode, @@ -2800,8 +2801,7 @@ async fn test_index_built_from_config_seeds() { append_config_rows(&mut dataset, 10..20).await; let appended = dataset.fragments()[1].id; - // Configured seeds record null counts, not positions, so the index - // keeps no null bitmap to reuse them. + // An index without a null bitmap ignores the positions the seeds carry. let params = ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ "rows_per_zone": ROWS_PER_ZONE, @@ -2837,6 +2837,69 @@ async fn test_index_built_from_config_seeds() { } } +/// Whether a ZoneMap index on `val` built from configured seeds reuses the +/// appended fragment, depending on the null-position setting of the seeds +/// (`None` leaves the key absent) and the index's `store_null_bitmap`. +/// Results of null filters always match a scan. +#[rstest::rstest] +#[case::default_seeds_bitmap_index(None, true, true)] +#[case::default_seeds_no_bitmap_index(None, false, true)] +#[case::explicit_seeds_bitmap_index(Some("true"), true, true)] +#[case::no_position_seeds_bitmap_index(Some("false"), true, false)] +#[tokio::test] +async fn test_config_seed_null_positions_serve_index( + #[case] seeds_store_null_bitmap: Option<&'static str>, + #[case] index_store_null_bitmap: bool, + #[case] expect_reuse: bool, +) { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + if let Some(value) = seeds_store_null_bitmap { + dataset + .update_config([(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, value)]) + .await + .unwrap(); + } + append_config_rows(&mut dataset, 10..20).await; + let appended = dataset.fragments()[1].id; + + let params = + ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ + "rows_per_zone": ROWS_PER_ZONE, + "use_seeds": true, + "store_null_bitmap": index_store_null_bitmap, + })); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1); + if expect_reuse { + assert_eq!(reports[0].reused_fragments, vec![appended]); + assert!(!reports[0].scanned_fragments.contains(&appended)); + } else { + // A seed without null positions is rejected and its fragment scanned. + assert!(reports[0].reused_fragments.is_empty()); + assert!(reports[0].partial_fragments.is_empty()); + assert!(reports[0].scanned_fragments.contains(&appended)); + } + + assert_indexed_ids_match_scan( + &dataset, + &["val IS NULL", "val IS NOT NULL", "val >= 5 AND val < 15"], + "null positions", + ) + .await; +} + /// A column with a seeded ZoneMap index follows that index's zone size even /// when the configured size is smaller; a ZoneMap index without seeds does /// not take part, so its column gets the configured size like any other. @@ -2905,6 +2968,7 @@ async fn test_binary_copy_declares_configured_rows_per_zone() { #[rstest::rstest] #[case::enabled(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes")] #[case::rows_per_zone(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")] +#[case::store_null_bitmap(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")] #[tokio::test] async fn test_config_rejects_invalid_zone_write_seeds_value( #[case] key: &'static str, @@ -3028,8 +3092,7 @@ async fn assert_indexed_ids_match_scan(dataset: &Dataset, filters: &[&str], cont } } -/// ZoneMap params that build from seeds without a null bitmap, which -/// configured seeds cannot feed. +/// ZoneMap params that build from seeds without a null bitmap. fn config_seed_index_params(rows_per_zone: u64) -> ScalarIndexParams { ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ "rows_per_zone": rows_per_zone, diff --git a/rust/lance/src/dataset/write.rs b/rust/lance/src/dataset/write.rs index 483930159db..337477a2c3e 100644 --- a/rust/lance/src/dataset/write.rs +++ b/rust/lance/src/dataset/write.rs @@ -76,7 +76,10 @@ pub use super::progress::{WriteProgressFn, WriteStats}; pub use commit::{CommitBuilder, DEFAULT_COMMIT_TIMEOUT}; pub use delete::{DeleteBuilder, DeleteResult, UncommittedDelete}; pub use insert::InsertBuilder; -pub use seeds::{ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}; +pub use seeds::{ + ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, +}; impl Dataset { pub(super) fn validate_data_file_target(&self, target: &DataFileTarget) -> Result<()> { diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index c74b85b199e..4fb71837310 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -28,12 +28,17 @@ //! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those //! columns, an integer in `1..=u32::MAX`. Absent, it is //! [`ROWS_PER_ZONE_DEFAULT`]. +//! - `lance.zone_write_seeds.store_null_bitmap`: whether those seeds record +//! null positions, so they can serve a ZoneMap index with +//! `store_null_bitmap = true` (the index default). Absent or `"true"`, +//! they do; `"false"` records none, and the seeds then only serve indexes +//! that store no null bitmap. //! -//! Setting either key to an invalid value, or any other key under +//! Setting any of these keys to an invalid value, or any other key under //! `lance.zone_write_seeds.`, is rejected by the commit that sets it. //! //! A column with a seeded ZoneMap index keeps following that index's -//! `rows_per_zone`. When a seeded index's requirements cannot be resolved +//! `rows_per_zone` and null-position policy. When a seeded index's requirements cannot be resolved //! for a file (its details or stored null-bitmap policy cannot be read), the //! column falls back to the configured seed if the setting is on. Enable the //! setting with [`Dataset::update_config`]; the commit that sets it also sets @@ -52,6 +57,7 @@ use lance_index::scalar::seed::IndexSeedWriter; use lance_index::scalar::zonemap::{ROWS_PER_ZONE_DEFAULT, ZoneMapSeedWriter}; pub use lance_table::feature_flags::{ ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, }; use lance_table::format::{IndexMetadata, Manifest}; @@ -70,6 +76,8 @@ static SEED_CONFLICT_WARNED: std::sync::Once = std::sync::Once::new(); pub struct ZoneWriteSeedsConfig { /// Rows per seed zone for columns without a seeded ZoneMap index. pub rows_per_zone: u64, + /// Whether those seeds record null positions. + pub store_null_bitmap: bool, } impl ZoneWriteSeedsConfig { @@ -77,9 +85,9 @@ impl ZoneWriteSeedsConfig { /// /// Values are validated when they are set /// (`validate_zone_write_seeds_config`), so this read is lenient: an - /// unparsable `enabled` disables the setting and an invalid - /// `rows_per_zone` falls back to [`ROWS_PER_ZONE_DEFAULT`], both with a - /// warning. That only matters for a manifest written by a build that did + /// unparsable `enabled` disables the setting, an invalid `rows_per_zone` + /// falls back to [`ROWS_PER_ZONE_DEFAULT`] and an unparsable + /// `store_null_bitmap` records null positions, each with a warning. That only matters for a manifest written by a build that did /// not validate them. pub fn from_config(config: &HashMap) -> Option { let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; @@ -108,7 +116,20 @@ impl ZoneWriteSeedsConfig { } }, }; - Some(Self { rows_per_zone }) + let store_null_bitmap = match config.get(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY) { + None => true, + Some(value) => value.parse::().unwrap_or_else(|err| { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?} ({err}); zone \ + write seeds record null positions" + ); + true + }), + }; + Some(Self { + rows_per_zone, + store_null_bitmap, + }) } } @@ -328,7 +349,7 @@ async fn seed_writers_for( && !other_columns.contains(&field.id) && config_seed_supports(field) }) - .map(|field| (field, config.rows_per_zone)) + .map(|field| (field, config.rows_per_zone, config.store_null_bitmap)) .collect() }) .unwrap_or_default(); @@ -380,13 +401,13 @@ async fn seed_writers_for( .with_null_positions(positions), )); } - // Configured seeds have no index whose null bitmap they could feed. A - // column whose seed writer cannot be constructed gets no configured + // Configured seeds record null positions unless the config turns them + // off. A column whose seed writer cannot be constructed gets no configured // seed; errors while observing batches or finishing a seed still fail // the write, as for index-requested seeds. - for (field, rows_per_zone) in config_columns { + for (field, rows_per_zone, positions) in config_columns { match ZoneMapSeedWriter::new(&field.name, rows_per_zone, field.data_type()) { - Ok(writer) => writers.push(Box::new(writer.with_null_positions(false))), + Ok(writer) => writers.push(Box::new(writer.with_null_positions(positions))), Err(err) => log::debug!( "column {}: no configured zone write seed ({err})", field.name @@ -524,30 +545,43 @@ mod tests { &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], None )] - #[case::default_size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")], Some(ROWS_PER_ZONE_DEFAULT))] + #[case::default_size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")], Some((ROWS_PER_ZONE_DEFAULT, true)))] #[case::explicit_size( &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], - Some(16) + Some((16, true)) )] #[case::zero_size( &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")], - Some(ROWS_PER_ZONE_DEFAULT) + Some((ROWS_PER_ZONE_DEFAULT, true)) )] #[case::negative_size( &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")], - Some(ROWS_PER_ZONE_DEFAULT) + Some((ROWS_PER_ZONE_DEFAULT, true)) )] #[case::unparsable_size( &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")], - Some(ROWS_PER_ZONE_DEFAULT) + Some((ROWS_PER_ZONE_DEFAULT, true)) )] #[case::too_large_size( &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")], - Some(ROWS_PER_ZONE_DEFAULT) + Some((ROWS_PER_ZONE_DEFAULT, true)) )] + #[case::null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::no_null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false")], + Some((ROWS_PER_ZONE_DEFAULT, false)) + )] + #[case::unparsable_null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::null_bitmap_without_enabled(&[(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], None)] fn test_zone_write_seeds_config_from_config( #[case] entries: &[(&str, &str)], - #[case] expected_rows_per_zone: Option, + #[case] expected: Option<(u64, bool)>, ) { let config: HashMap = entries .iter() @@ -555,7 +589,10 @@ mod tests { .collect(); assert_eq!( ZoneWriteSeedsConfig::from_config(&config), - expected_rows_per_zone.map(|rows_per_zone| ZoneWriteSeedsConfig { rows_per_zone }) + expected.map(|(rows_per_zone, store_null_bitmap)| ZoneWriteSeedsConfig { + rows_per_zone, + store_null_bitmap, + }) ); } From 9f6336648789d8f3f3538c21de9090521b2cd5b0 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 23:25:11 -0800 Subject: [PATCH 07/23] test: cover seed and index zone boundaries for configured write seeds Adds a matrix over seed size, index size, fragment length and batch size that checks which fragments are reused, partly scanned or scanned, and compares indexed results row by row with the generator and an unindexed scan. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 266 ++++++++++++++++++ 1 file changed, 266 insertions(+) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 6727835ef75..dc2e2f109d5 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3348,3 +3348,269 @@ async fn test_binary_copy_carries_config_seeds_of_different_sizes() { ) .await; } + +/// Rows of the creating write in [`test_config_seed_boundary_matrix`]; that +/// write happens before the config is enabled and carries no seed. +const BOUNDARY_CREATE_ROWS: i64 = 11; +/// Fragments appended after the config is enabled. +const BOUNDARY_APPENDED_FRAGMENTS: i64 = 3; + +fn boundary_schema() -> Arc { + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int64, false), + ArrowField::new("val", DataType::Int64, true), + ])) +} + +/// The generator every expectation is computed from: three times the row +/// position, null on every seventh position. +fn boundary_value(position: i64) -> Option { + (position % 7 != 0).then_some(position * 3) +} + +fn boundary_rows(positions: std::ops::Range) -> RecordBatch { + RecordBatch::try_new( + boundary_schema(), + vec![ + Arc::new(Int64Array::from_iter_values(positions.clone())), + Arc::new(Int64Array::from_iter(positions.map(boundary_value))), + ], + ) + .unwrap() +} + +/// Appends `positions` as one fragment, streamed in batches of `batch_size`. +async fn append_boundary_fragment( + dataset: &mut Dataset, + positions: std::ops::Range, + batch_size: i64, +) { + let mut batches = Vec::new(); + let mut start = positions.start; + while start < positions.end { + let end = (start + batch_size).min(positions.end); + batches.push(boundary_rows(start..end)); + start = end; + } + dataset + .append( + RecordBatchIterator::new( + batches + .into_iter() + .map(Ok::), + boundary_schema(), + ), + None, + ) + .await + .unwrap(); +} + +/// Sorted `(id, val)` pairs a filter returns. +async fn boundary_query( + dataset: &Dataset, + filter: &str, + use_index: bool, +) -> Vec<(i64, Option)> { + use arrow::array::AsArray; + use arrow::datatypes::Int64Type; + + let mut scan = dataset.scan(); + scan.use_scalar_index(use_index) + .filter(filter) + .unwrap() + .project(&["id", "val"]) + .unwrap(); + let batch = scan.try_into_batch().await.unwrap(); + let mut rows: Vec<(i64, Option)> = batch["id"] + .as_primitive::() + .values() + .iter() + .copied() + .zip(batch["val"].as_primitive::().iter()) + .collect(); + rows.sort_unstable(); + rows +} + +/// Configured seeds of one zone size serve a ZoneMap index of another size +/// across fragment and batch boundaries. A seed record is reused when it lies +/// inside one index zone (index zones restart at every fragment); records that +/// cross an index zone boundary leave their fragment partly scanned. Indexed +/// results always match both the generator and an unindexed scan. +#[rstest::rstest] +#[case::equal_aligned(8, 8, 64, 64)] +#[case::equal_partial_final_zone(8, 8, 61, 61)] +#[case::batches_cross_zones(8, 8, 61, 5)] +#[case::coarsen_multiple(8, 32, 64, 13)] +#[case::coarsen_multiple_partial_fragment(8, 32, 61, 13)] +#[case::coarsen_not_multiple(8, 20, 64, 13)] +#[case::seed_coarser_than_index(32, 8, 64, 13)] +#[case::fragment_shorter_than_seed_zone(8, 8, 5, 5)] +#[tokio::test] +async fn test_config_seed_boundary_matrix( + #[case] seed_rows_per_zone: u64, + #[case] index_rows_per_zone: u64, + #[case] rows_per_fragment: i64, + #[case] batch_size: i64, +) { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + let context = format!( + "seed {seed_rows_per_zone}, index {index_rows_per_zone}, \ + fragment {rows_per_fragment}, batch {batch_size}" + ); + let dir = TempStrDir::default(); + let mut dataset = Dataset::write( + RecordBatchIterator::new( + [Ok(boundary_rows(0..BOUNDARY_CREATE_ROWS))], + boundary_schema(), + ), + dir.as_str(), + None, + ) + .await + .unwrap(); + let creating = dataset.fragments()[0].id; + enable_zone_write_seeds(&mut dataset, seed_rows_per_zone).await; + for fragment in 0..BOUNDARY_APPENDED_FRAGMENTS { + let start = BOUNDARY_CREATE_ROWS + fragment * rows_per_fragment; + append_boundary_fragment(&mut dataset, start..start + rows_per_fragment, batch_size).await; + } + let fragments = dataset.fragments().clone(); + assert_eq!( + fragments.len() as i64, + BOUNDARY_APPENDED_FRAGMENTS + 1, + "{context}" + ); + let mut appended: Vec = fragments + .iter() + .map(|f| f.id) + .filter(|id| *id != creating) + .collect(); + appended.sort_unstable(); + for fragment in &fragments[1..] { + assert_eq!( + seed_locator_rows_per_zone(&dataset, fragment, "val").await, + Some(seed_rows_per_zone), + "{context}: fragment {}", + fragment.id + ); + } + + let params = config_seed_index_params(index_rows_per_zone); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1, "{context}: {reports:?}"); + let report = &reports[0]; + let sorted = |ids: &[u64]| { + let mut ids = ids.to_vec(); + ids.sort_unstable(); + ids + }; + let reused = sorted(&report.reused_fragments); + let partial = sorted(&report.partial_fragments); + let scanned = sorted(&report.scanned_fragments); + assert_eq!( + reused.len() + partial.len() + scanned.len(), + fragments.len(), + "{context}: {report:?}" + ); + + // Whether the fully scanned creating fragment counts towards + // `scanned_rows` is not pinned here, so each expectation also accepts the + // seeded total plus its BOUNDARY_CREATE_ROWS (11) rows. + let index_multiple_of_seed = index_rows_per_zone % seed_rows_per_zone == 0; + if index_multiple_of_seed { + // Every seed record lies inside one index zone: no appended fragment + // is scanned. + assert_eq!(reused, appended, "{context}: {report:?}"); + assert!(partial.is_empty(), "{context}: {report:?}"); + assert_eq!(scanned, vec![creating], "{context}: {report:?}"); + assert!( + matches!(report.scanned_rows, 0 | 11), + "{context}: {report:?}" + ); + } else if seed_rows_per_zone < index_rows_per_zone { + // 8-row records over 20-row index zones in a 64-row fragment: the + // records [16,24), [40,48) and [56,64) cross an index zone boundary + // and are scanned, the other five are reused. + assert_eq!( + (seed_rows_per_zone, index_rows_per_zone, rows_per_fragment), + (8, 20, 64), + "{context}: expectation only derived for this shape" + ); + assert!(reused.is_empty(), "{context}: {report:?}"); + assert_eq!(partial, appended, "{context}: {report:?}"); + assert_eq!(scanned, vec![creating], "{context}: {report:?}"); + // Five reused and 24 scanned rows per appended fragment, three + // appended fragments. + assert_eq!(report.reused_records, 15, "{context}: {report:?}"); + assert!( + matches!(report.scanned_rows, 72 | 83), + "{context}: {report:?}" + ); + } else { + // TODO(expectation): every 32-row seed record spans several 8-row + // index zones; whether such fragments are reported partial or + // scanned is not established by the existing tests. + assert!( + !scanned.is_empty() || !partial.is_empty(), + "{context}: the creating fragment is never reused: {report:?}" + ); + } + + // Positions at an index zone boundary inside the first appended fragment, + // and just before and after the first boundary between appended fragments. + let first_appended = BOUNDARY_CREATE_ROWS; + let zone_boundary = first_appended + (index_rows_per_zone as i64).min(rows_per_fragment); + let fragment_boundary = first_appended + rows_per_fragment; + let total_rows = BOUNDARY_CREATE_ROWS + BOUNDARY_APPENDED_FRAGMENTS * rows_per_fragment; + let generated: Vec<(i64, Option)> = + (0..total_rows).map(|p| (p, boundary_value(p))).collect(); + let oracle = |keep: &dyn Fn(Option) -> bool| -> Vec<(i64, Option)> { + generated + .iter() + .filter(|(_, v)| keep(*v)) + .copied() + .collect() + }; + + let zone_value = zone_boundary * 3; + let mut cases: Vec<(String, Vec<(i64, Option)>)> = vec![ + ( + format!("val < {zone_value}"), + oracle(&|v: Option| v.is_some_and(|v| v < zone_value)), + ), + ( + format!("val >= {zone_value}"), + oracle(&|v: Option| v.is_some_and(|v| v >= zone_value)), + ), + ( + "val IS NULL".to_string(), + oracle(&|v: Option| v.is_none()), + ), + ( + "val IS NOT NULL".to_string(), + oracle(&|v: Option| v.is_some()), + ), + ]; + for position in [zone_boundary, fragment_boundary - 1, fragment_boundary] { + let x = position * 3; + cases.push((format!("val = {x}"), oracle(&|v: Option| v == Some(x)))); + } + + for (filter, expected) in cases { + let indexed = boundary_query(&dataset, &filter, true).await; + let unindexed = boundary_query(&dataset, &filter, false).await; + assert_eq!(unindexed, expected, "{context}: unindexed {filter}"); + assert_eq!(indexed, expected, "{context}: indexed {filter}"); + } +} From 7198351e6d6b55fad646cdff7862a364071e5938 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Sun, 22 Nov 2026 23:43:31 -0800 Subject: [PATCH 08/23] test: pin observed reuse counts in the seed boundary matrix A partly reused fragment is reported as both partial and scanned, and scanned rows include the unseeded creating fragment. Corrects the expectation for 8-row records over 20-row index zones. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 65 ++++++++++--------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index dc2e2f109d5..0f7b5e186c4 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3406,12 +3406,11 @@ async fn append_boundary_fragment( .unwrap(); } +/// `(id, val)` pairs, sorted by `id`. +type BoundaryRows = Vec<(i64, Option)>; + /// Sorted `(id, val)` pairs a filter returns. -async fn boundary_query( - dataset: &Dataset, - filter: &str, - use_index: bool, -) -> Vec<(i64, Option)> { +async fn boundary_query(dataset: &Dataset, filter: &str, use_index: bool) -> BoundaryRows { use arrow::array::AsArray; use arrow::datatypes::Int64Type; @@ -3422,7 +3421,7 @@ async fn boundary_query( .project(&["id", "val"]) .unwrap(); let batch = scan.try_into_batch().await.unwrap(); - let mut rows: Vec<(i64, Option)> = batch["id"] + let mut rows: BoundaryRows = batch["id"] .as_primitive::() .values() .iter() @@ -3518,30 +3517,35 @@ async fn test_config_seed_boundary_matrix( let reused = sorted(&report.reused_fragments); let partial = sorted(&report.partial_fragments); let scanned = sorted(&report.scanned_fragments); + // A partly reused fragment is listed as both partial and scanned. assert_eq!( - reused.len() + partial.len() + scanned.len(), + reused.len() + scanned.len(), fragments.len(), "{context}: {report:?}" ); + assert!( + reused.iter().all(|id| !scanned.contains(id)), + "{context}: {report:?}" + ); + assert!( + partial.iter().all(|id| scanned.contains(id)), + "{context}: {report:?}" + ); - // Whether the fully scanned creating fragment counts towards - // `scanned_rows` is not pinned here, so each expectation also accepts the - // seeded total plus its BOUNDARY_CREATE_ROWS (11) rows. - let index_multiple_of_seed = index_rows_per_zone % seed_rows_per_zone == 0; + // `scanned_rows` includes the creating fragment's BOUNDARY_CREATE_ROWS (11) + // rows. + let index_multiple_of_seed = index_rows_per_zone.is_multiple_of(seed_rows_per_zone); if index_multiple_of_seed { // Every seed record lies inside one index zone: no appended fragment // is scanned. assert_eq!(reused, appended, "{context}: {report:?}"); assert!(partial.is_empty(), "{context}: {report:?}"); assert_eq!(scanned, vec![creating], "{context}: {report:?}"); - assert!( - matches!(report.scanned_rows, 0 | 11), - "{context}: {report:?}" - ); + assert_eq!(report.scanned_rows, 11, "{context}: {report:?}"); } else if seed_rows_per_zone < index_rows_per_zone { - // 8-row records over 20-row index zones in a 64-row fragment: the - // records [16,24), [40,48) and [56,64) cross an index zone boundary - // and are scanned, the other five are reused. + // 8-row records over index zones [0,20), [20,40), [40,60), [60,64) + // in a 64-row fragment: the records [16,24) and [56,64) cross an + // index zone boundary and are scanned, the other six are reused. assert_eq!( (seed_rows_per_zone, index_rows_per_zone, rows_per_fragment), (8, 20, 64), @@ -3549,20 +3553,20 @@ async fn test_config_seed_boundary_matrix( ); assert!(reused.is_empty(), "{context}: {report:?}"); assert_eq!(partial, appended, "{context}: {report:?}"); - assert_eq!(scanned, vec![creating], "{context}: {report:?}"); - // Five reused and 24 scanned rows per appended fragment, three - // appended fragments. - assert_eq!(report.reused_records, 15, "{context}: {report:?}"); - assert!( - matches!(report.scanned_rows, 72 | 83), - "{context}: {report:?}" - ); + let mut all_fragments = appended.clone(); + all_fragments.push(creating); + all_fragments.sort_unstable(); + assert_eq!(scanned, all_fragments, "{context}: {report:?}"); + // Six reused records and 16 scanned rows per appended fragment, plus + // the creating fragment's 11 rows. + assert_eq!(report.reused_records, 18, "{context}: {report:?}"); + assert_eq!(report.scanned_rows, 59, "{context}: {report:?}"); } else { // TODO(expectation): every 32-row seed record spans several 8-row // index zones; whether such fragments are reported partial or // scanned is not established by the existing tests. assert!( - !scanned.is_empty() || !partial.is_empty(), + scanned.contains(&creating), "{context}: the creating fragment is never reused: {report:?}" ); } @@ -3573,9 +3577,8 @@ async fn test_config_seed_boundary_matrix( let zone_boundary = first_appended + (index_rows_per_zone as i64).min(rows_per_fragment); let fragment_boundary = first_appended + rows_per_fragment; let total_rows = BOUNDARY_CREATE_ROWS + BOUNDARY_APPENDED_FRAGMENTS * rows_per_fragment; - let generated: Vec<(i64, Option)> = - (0..total_rows).map(|p| (p, boundary_value(p))).collect(); - let oracle = |keep: &dyn Fn(Option) -> bool| -> Vec<(i64, Option)> { + let generated: BoundaryRows = (0..total_rows).map(|p| (p, boundary_value(p))).collect(); + let oracle = |keep: &dyn Fn(Option) -> bool| -> BoundaryRows { generated .iter() .filter(|(_, v)| keep(*v)) @@ -3584,7 +3587,7 @@ async fn test_config_seed_boundary_matrix( }; let zone_value = zone_boundary * 3; - let mut cases: Vec<(String, Vec<(i64, Option)>)> = vec![ + let mut cases: Vec<(String, BoundaryRows)> = vec![ ( format!("val < {zone_value}"), oracle(&|v: Option| v.is_some_and(|v| v < zone_value)), From 4405ba9654cc3a347da2c8abc566ad91ba0ff9dd Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 00:11:47 -0800 Subject: [PATCH 09/23] test: pin coarse-seed rejection and cover production zone sizes Asserts the exact outcome for a seed coarser than the index and adds 8192 and 1,000,000-row zone sizes over a fragment length neither divides. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 184 ++++++++++++++++-- 1 file changed, 172 insertions(+), 12 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 0f7b5e186c4..d65ba2224b1 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3400,7 +3400,11 @@ async fn append_boundary_fragment( .map(Ok::), boundary_schema(), ), - None, + Some(WriteParams { + mode: WriteMode::Append, + max_rows_per_file: (positions.end - positions.start) as usize, + ..Default::default() + }), ) .await .unwrap(); @@ -3562,21 +3566,49 @@ async fn test_config_seed_boundary_matrix( assert_eq!(report.reused_records, 18, "{context}: {report:?}"); assert_eq!(report.scanned_rows, 59, "{context}: {report:?}"); } else { - // TODO(expectation): every 32-row seed record spans several 8-row - // index zones; whether such fragments are reported partial or - // scanned is not established by the existing tests. - assert!( - scanned.contains(&creating), - "{context}: the creating fragment is never reused: {report:?}" + // In this fixture every 32-row record crosses 8-row index zones and + // none fits, so each appended seed is rejected before any reuse is + // recorded and its fragment is scanned in full. + assert_eq!( + (seed_rows_per_zone, index_rows_per_zone, rows_per_fragment), + (32, 8, 64), + "{context}: expectation only derived for this shape" ); + assert!(reused.is_empty(), "{context}: {report:?}"); + assert!(partial.is_empty(), "{context}: {report:?}"); + let mut all_fragments = appended.clone(); + all_fragments.push(creating); + all_fragments.sort_unstable(); + assert_eq!(scanned, all_fragments, "{context}: {report:?}"); + assert_eq!(report.reused_records, 0, "{context}: {report:?}"); + // The creating fragment's 11 rows plus three fully scanned 64-row + // fragments. + assert_eq!(report.scanned_rows, 203, "{context}: {report:?}"); } // Positions at an index zone boundary inside the first appended fragment, // and just before and after the first boundary between appended fragments. let first_appended = BOUNDARY_CREATE_ROWS; - let zone_boundary = first_appended + (index_rows_per_zone as i64).min(rows_per_fragment); - let fragment_boundary = first_appended + rows_per_fragment; - let total_rows = BOUNDARY_CREATE_ROWS + BOUNDARY_APPENDED_FRAGMENTS * rows_per_fragment; + assert_boundary_predicates( + &dataset, + BOUNDARY_CREATE_ROWS + BOUNDARY_APPENDED_FRAGMENTS * rows_per_fragment, + first_appended + (index_rows_per_zone as i64).min(rows_per_fragment), + first_appended + rows_per_fragment, + &context, + ) + .await; +} + +/// Range, null and equality predicates around `zone_boundary` and +/// `fragment_boundary` return the rows the generator yields for positions +/// `0..total_rows`, with and without the scalar index. +async fn assert_boundary_predicates( + dataset: &Dataset, + total_rows: i64, + zone_boundary: i64, + fragment_boundary: i64, + context: &str, +) { let generated: BoundaryRows = (0..total_rows).map(|p| (p, boundary_value(p))).collect(); let oracle = |keep: &dyn Fn(Option) -> bool| -> BoundaryRows { generated @@ -3611,9 +3643,137 @@ async fn test_config_seed_boundary_matrix( } for (filter, expected) in cases { - let indexed = boundary_query(&dataset, &filter, true).await; - let unindexed = boundary_query(&dataset, &filter, false).await; + let indexed = boundary_query(dataset, &filter, true).await; + let unindexed = boundary_query(dataset, &filter, false).await; assert_eq!(unindexed, expected, "{context}: unindexed {filter}"); assert_eq!(indexed, expected, "{context}: indexed {filter}"); } } + +/// Configured seeds at production zone sizes serve a ZoneMap index over one +/// appended fragment whose length no zone size divides. Seed records are +/// `seed_rows_per_zone` rows from the fragment start with a short final +/// record; with seed records no larger than index zones, a record is reused +/// when it lies inside one index zone and scanned when it straddles an index +/// zone boundary. +#[rstest::rstest] +#[case::small_seed_crosses_index_boundary(8192, 1_000_000, 1_050_000, 100_003)] +#[case::equal_sizes_short_final_zone(1_000_000, 1_000_000, 1_050_000, 100_003)] +#[case::equal_small_sizes(8192, 8192, 20_000, 4_099)] +#[tokio::test] +async fn test_config_seed_boundary_real_sizes( + #[case] seed_rows_per_zone: u64, + #[case] index_rows_per_zone: u64, + #[case] rows_per_fragment: i64, + #[case] batch_size: i64, +) { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + let context = format!( + "seed {seed_rows_per_zone}, index {index_rows_per_zone}, \ + fragment {rows_per_fragment}, batch {batch_size}" + ); + let dir = TempStrDir::default(); + let mut dataset = Dataset::write( + RecordBatchIterator::new( + [Ok(boundary_rows(0..BOUNDARY_CREATE_ROWS))], + boundary_schema(), + ), + dir.as_str(), + None, + ) + .await + .unwrap(); + let creating = dataset.fragments()[0].id; + enable_zone_write_seeds(&mut dataset, seed_rows_per_zone).await; + let first_appended = BOUNDARY_CREATE_ROWS; + append_boundary_fragment( + &mut dataset, + first_appended..first_appended + rows_per_fragment, + batch_size, + ) + .await; + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), 2, "{context}"); + let appended = fragments[1].id; + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], "val").await, + Some(seed_rows_per_zone), + "{context}" + ); + + // Expected reuse, computed from the sizes alone. + let seed = seed_rows_per_zone as i64; + let index = index_rows_per_zone as i64; + assert!( + seed <= index, + "{context}: expectation assumes seed <= index" + ); + let records: Vec<(i64, i64)> = (0..rows_per_fragment) + .step_by(seed as usize) + .map(|start| (start, (start + seed).min(rows_per_fragment))) + .collect(); + let crossing: Vec<&(i64, i64)> = records + .iter() + .filter(|(start, end)| start / index != (end - 1) / index) + .collect(); + let expected_reused_records = (records.len() - crossing.len()) as i64; + let expected_scanned_rows = + BOUNDARY_CREATE_ROWS + crossing.iter().map(|(start, end)| end - start).sum::(); + + let params = config_seed_index_params(index_rows_per_zone); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1, "{context}: {reports:?}"); + let report = &reports[0]; + let mut scanned = report.scanned_fragments.clone(); + scanned.sort_unstable(); + if crossing.is_empty() { + assert_eq!( + report.reused_fragments, + vec![appended], + "{context}: {report:?}" + ); + assert!(report.partial_fragments.is_empty(), "{context}: {report:?}"); + assert_eq!(scanned, vec![creating], "{context}: {report:?}"); + } else { + // A partly reused fragment is listed as both partial and scanned. + assert!(report.reused_fragments.is_empty(), "{context}: {report:?}"); + assert_eq!( + report.partial_fragments, + vec![appended], + "{context}: {report:?}" + ); + let mut all_fragments = vec![creating, appended]; + all_fragments.sort_unstable(); + assert_eq!(scanned, all_fragments, "{context}: {report:?}"); + } + assert_eq!( + report.reused_records, + expected_reused_records.try_into().unwrap(), + "{context}: {report:?}" + ); + assert_eq!( + report.scanned_rows, + expected_scanned_rows.try_into().unwrap(), + "{context}: {report:?}" + ); + + // With a single appended fragment the fragment boundary is the one + // between the creating fragment and the appended fragment. + assert_boundary_predicates( + &dataset, + BOUNDARY_CREATE_ROWS + rows_per_fragment, + first_appended + index.min(rows_per_fragment), + first_appended, + &context, + ) + .await; +} From 60f25ad3c9a60bd9977ae0d8d14adbe6c645abff Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 00:31:53 -0800 Subject: [PATCH 10/23] test: type the expected reuse counts in the real-size boundary test Co-Authored-By: Claude --- rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index d65ba2224b1..b62b2701eaf 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3717,7 +3717,7 @@ async fn test_config_seed_boundary_real_sizes( .iter() .filter(|(start, end)| start / index != (end - 1) / index) .collect(); - let expected_reused_records = (records.len() - crossing.len()) as i64; + let expected_reused_records = records.len() - crossing.len(); let expected_scanned_rows = BOUNDARY_CREATE_ROWS + crossing.iter().map(|(start, end)| end - start).sum::(); @@ -3756,13 +3756,11 @@ async fn test_config_seed_boundary_real_sizes( assert_eq!(scanned, all_fragments, "{context}: {report:?}"); } assert_eq!( - report.reused_records, - expected_reused_records.try_into().unwrap(), + report.reused_records, expected_reused_records, "{context}: {report:?}" ); assert_eq!( - report.scanned_rows, - expected_scanned_rows.try_into().unwrap(), + report.scanned_rows, expected_scanned_rows as u64, "{context}: {report:?}" ); From ae859f377873f481d192b78d610dc479cd2aa93c Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 00:56:18 -0800 Subject: [PATCH 11/23] test: compare stored zone statistics with a generator oracle Reads every persisted zone of the index built from configured seeds and checks its span, bounds and null count against values computed from the generator, including the unseeded creating fragment and short final zones. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index b62b2701eaf..36d072d4323 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3597,6 +3597,133 @@ async fn test_config_seed_boundary_matrix( &context, ) .await; + + let mut fragment_ranges = vec![(creating, 0..BOUNDARY_CREATE_ROWS)]; + for (k, fragment) in fragments[1..].iter().enumerate() { + let start = BOUNDARY_CREATE_ROWS + k as i64 * rows_per_fragment; + fragment_ranges.push((fragment.id, start..start + rows_per_fragment)); + } + assert_boundary_zone_statistics(&dataset, index_rows_per_zone, &fragment_ranges, &context) + .await; +} + +/// One stored or expected zone: fragment id, zone start, zone length, null +/// count, min, max, NaN count and negative NaN count. +type BoundaryZone = ( + u64, + u64, + u64, + u32, + Option, + Option, + u32, + Option, +); + +/// Every zone stored by the ZoneMap index on `val`, across all its segments, +/// equals the zone computed from the generator: zones of `index_rows_per_zone` +/// rows restart at each fragment's first row, the last one short. +/// `fragment_ranges` maps each fragment id to its generator positions. +async fn assert_boundary_zone_statistics( + dataset: &Dataset, + index_rows_per_zone: u64, + fragment_ranges: &[(u64, std::ops::Range)], + context: &str, +) { + use arrow::array::AsArray; + use arrow::datatypes::{Int64Type, UInt32Type, UInt64Type}; + use lance_index::scalar::lance_format::LanceIndexStore; + use lance_index::scalar::zonemap::{ZoneMapIndex, ZoneMapIndexVersion}; + + use crate::dataset::index::LanceIndexStoreExt; + + let val = field_id(dataset, "val"); + let indices = dataset.load_indices().await.unwrap(); + let segments: Vec<_> = indices + .iter() + .filter(|index| index.fields == vec![val]) + .collect(); + assert!(!segments.is_empty(), "{context}: no index on val"); + + let mut batches = Vec::new(); + let mut stored: Vec = Vec::new(); + for segment in segments { + let store = LanceIndexStore::from_dataset_for_existing(dataset, segment) + .await + .unwrap(); + let version = ZoneMapIndexVersion::from_metadata(segment.index_version as u32).unwrap(); + let batch = ZoneMapIndex::load_zone_statistics(&store, version) + .await + .unwrap(); + let min = batch["min"].as_primitive::(); + let max = batch["max"].as_primitive::(); + let null_count = batch["null_count"].as_primitive::(); + let nan_count = batch["nan_count"].as_primitive::(); + let negative_nan_count = batch["negative_nan_count"].as_primitive::(); + let fragment_id = batch["fragment_id"].as_primitive::(); + let zone_start = batch["zone_start"].as_primitive::(); + let zone_length = batch["zone_length"].as_primitive::(); + for row in 0..batch.num_rows() { + stored.push(( + fragment_id.value(row), + zone_start.value(row), + zone_length.value(row), + null_count.value(row), + min.is_valid(row).then(|| min.value(row)), + max.is_valid(row).then(|| max.value(row)), + nan_count.value(row), + negative_nan_count + .is_valid(row) + .then(|| negative_nan_count.value(row)), + )); + } + batches.push(batch); + } + stored.sort_unstable_by_key(|zone| (zone.0, zone.1)); + + let zone_rows = index_rows_per_zone as i64; + let mut expected: Vec = Vec::new(); + for (fragment_id, positions) in fragment_ranges { + let mut start = positions.start; + while start < positions.end { + let end = (start + zone_rows).min(positions.end); + let values: Vec> = (start..end).map(boundary_value).collect(); + let non_null = values.iter().flatten(); + expected.push(( + *fragment_id, + (start - positions.start) as u64, + (end - start) as u64, + values.iter().filter(|v| v.is_none()).count() as u32, + non_null.clone().min().copied(), + non_null.max().copied(), + 0, + Some(0), + )); + start = end; + } + } + expected.sort_unstable_by_key(|zone| (zone.0, zone.1)); + + assert_eq!( + stored.len(), + expected.len(), + "{context}: zone count, stored {batches:?}" + ); + for (stored, expected) in stored.iter().zip(&expected) { + // `zone_start` is accepted as a fragment-local offset or as the row + // address of the zone's first row. + let row_address = (expected.0 << 32) | expected.1; + assert!( + stored.1 == expected.1 || stored.1 == row_address, + "{context}: zone start of {expected:?}, stored {stored:?} in {batches:?}" + ); + let mut normalized = *stored; + normalized.1 = expected.1; + assert_eq!( + normalized, *expected, + "{context}: zone {expected:?}, stored {stored:?} in {batches:?}" + ); + } } /// Range, null and equality predicates around `zone_boundary` and @@ -3774,4 +3901,15 @@ async fn test_config_seed_boundary_real_sizes( &context, ) .await; + + assert_boundary_zone_statistics( + &dataset, + index_rows_per_zone, + &[ + (creating, 0..BOUNDARY_CREATE_ROWS), + (appended, first_appended..first_appended + rows_per_fragment), + ], + &context, + ) + .await; } From 35bd435ffd767b65e1a5256a984a49d9b0935966 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 01:21:19 -0800 Subject: [PATCH 12/23] test: require fragment-local zone starts in the stored statistics oracle Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 83 +++++++++---------- 1 file changed, 38 insertions(+), 45 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 36d072d4323..0a342948b3c 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3607,22 +3607,24 @@ async fn test_config_seed_boundary_matrix( .await; } -/// One stored or expected zone: fragment id, zone start, zone length, null -/// count, min, max, NaN count and negative NaN count. -type BoundaryZone = ( - u64, - u64, - u64, - u32, - Option, - Option, - u32, - Option, -); +/// One stored or expected zone of the ZoneMap index on `val`. +#[derive(Debug, Clone, PartialEq)] +struct BoundaryZone { + fragment_id: u64, + /// Offset of the zone's first row within its fragment. + zone_start: u64, + zone_length: u64, + null_count: u32, + min: Option, + max: Option, + nan_count: u32, + negative_nan_count: Option, +} /// Every zone stored by the ZoneMap index on `val`, across all its segments, /// equals the zone computed from the generator: zones of `index_rows_per_zone` -/// rows restart at each fragment's first row, the last one short. +/// rows restart at each fragment's first row, the last one short, and +/// `zone_start` is the offset within the fragment. /// `fragment_ranges` maps each fragment id to its generator positions. async fn assert_boundary_zone_statistics( dataset: &Dataset, @@ -3664,22 +3666,22 @@ async fn assert_boundary_zone_statistics( let zone_start = batch["zone_start"].as_primitive::(); let zone_length = batch["zone_length"].as_primitive::(); for row in 0..batch.num_rows() { - stored.push(( - fragment_id.value(row), - zone_start.value(row), - zone_length.value(row), - null_count.value(row), - min.is_valid(row).then(|| min.value(row)), - max.is_valid(row).then(|| max.value(row)), - nan_count.value(row), - negative_nan_count + stored.push(BoundaryZone { + fragment_id: fragment_id.value(row), + zone_start: zone_start.value(row), + zone_length: zone_length.value(row), + null_count: null_count.value(row), + min: min.is_valid(row).then(|| min.value(row)), + max: max.is_valid(row).then(|| max.value(row)), + nan_count: nan_count.value(row), + negative_nan_count: negative_nan_count .is_valid(row) .then(|| negative_nan_count.value(row)), - )); + }); } batches.push(batch); } - stored.sort_unstable_by_key(|zone| (zone.0, zone.1)); + stored.sort_unstable_by_key(|zone| (zone.fragment_id, zone.zone_start)); let zone_rows = index_rows_per_zone as i64; let mut expected: Vec = Vec::new(); @@ -3689,20 +3691,20 @@ async fn assert_boundary_zone_statistics( let end = (start + zone_rows).min(positions.end); let values: Vec> = (start..end).map(boundary_value).collect(); let non_null = values.iter().flatten(); - expected.push(( - *fragment_id, - (start - positions.start) as u64, - (end - start) as u64, - values.iter().filter(|v| v.is_none()).count() as u32, - non_null.clone().min().copied(), - non_null.max().copied(), - 0, - Some(0), - )); + expected.push(BoundaryZone { + fragment_id: *fragment_id, + zone_start: (start - positions.start) as u64, + zone_length: (end - start) as u64, + null_count: values.iter().filter(|v| v.is_none()).count() as u32, + min: non_null.clone().min().copied(), + max: non_null.max().copied(), + nan_count: 0, + negative_nan_count: Some(0), + }); start = end; } } - expected.sort_unstable_by_key(|zone| (zone.0, zone.1)); + expected.sort_unstable_by_key(|zone| (zone.fragment_id, zone.zone_start)); assert_eq!( stored.len(), @@ -3710,17 +3712,8 @@ async fn assert_boundary_zone_statistics( "{context}: zone count, stored {batches:?}" ); for (stored, expected) in stored.iter().zip(&expected) { - // `zone_start` is accepted as a fragment-local offset or as the row - // address of the zone's first row. - let row_address = (expected.0 << 32) | expected.1; - assert!( - stored.1 == expected.1 || stored.1 == row_address, - "{context}: zone start of {expected:?}, stored {stored:?} in {batches:?}" - ); - let mut normalized = *stored; - normalized.1 = expected.1; assert_eq!( - normalized, *expected, + stored, expected, "{context}: zone {expected:?}, stored {stored:?} in {batches:?}" ); } From bda2e551c0ea6e114aac24b26daa2504912e773d Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 07:18:16 -0800 Subject: [PATCH 13/23] test: cover seed boundaries per type with and without a null bitmap index Checks reuse, stored zone statistics and query results for integer, float, string, timestamp, boolean and decimal columns where reused and scanned zones mix. Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 222 ++++++++++++++++++ 1 file changed, 222 insertions(+) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 0a342948b3c..7fbda354375 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3906,3 +3906,225 @@ async fn test_config_seed_boundary_real_sizes( ) .await; } + +/// One stored or expected zone of the ZoneMap index on `col`; `min` and `max` +/// are one-element arrays of the column's type. +#[derive(Debug, PartialEq)] +struct TypedZone { + fragment_id: u64, + zone_start: u64, + zone_length: u64, + null_count: u32, + nan_count: u32, + min: ArrayRef, + max: ArrayRef, +} + +/// The boundary shape where reused and scanned seed records mix (seed zones +/// of 8 rows, index zones of 20, 64-row fragments written in 13-row batches), +/// for each type family and both null-bitmap settings of the index. Stored +/// zone statistics equal those computed from the generated arrays, and +/// indexed filters match a scan. +#[rstest::rstest] +#[case::int32(DataType::Int32, INT_FILTERS)] +#[case::float64(DataType::Float64, FLOAT_FILTERS)] +#[case::utf8(DataType::Utf8, STRING_FILTERS)] +#[case::timestamp_ms( + DataType::Timestamp(TimeUnit::Millisecond, None), + &["col >= TIMESTAMP '2023-11-14 22:13:50'"] +)] +#[case::boolean(DataType::Boolean, &["col = true"])] +#[case::decimal128(DataType::Decimal128(38, 4), &["col >= 30"])] +#[tokio::test] +async fn test_config_seed_boundary_per_type( + #[case] data_type: DataType, + #[case] filters: &'static [&'static str], + #[values(false, true)] index_store_null_bitmap: bool, +) { + use arrow::array::{AsArray, BooleanArray, new_null_array}; + use arrow::datatypes::{Float64Type, UInt32Type, UInt64Type}; + use lance_index::scalar::lance_format::LanceIndexStore; + use lance_index::scalar::zonemap::{ZoneMapIndex, ZoneMapIndexVersion}; + + use crate::dataset::index::LanceIndexStoreExt; + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + const SEED_ROWS_PER_ZONE: u64 = 8; + const INDEX_ROWS_PER_ZONE: usize = 20; + const CREATE_ROWS: i64 = 11; + const APPENDED_FRAGMENTS: i64 = 2; + const FRAGMENT_ROWS: i64 = 64; + const BATCH_ROWS: i64 = 13; + + let context = format!("{data_type}, index store_null_bitmap {index_store_null_bitmap}"); + let dir = TempStrDir::default(); + let schema = typed_schema(&data_type); + let mut dataset = Dataset::write( + RecordBatchIterator::new([Ok(typed_rows(&data_type, 0..CREATE_ROWS))], schema.clone()), + dir.as_str(), + None, + ) + .await + .unwrap(); + let creating = dataset.fragments()[0].id; + enable_zone_write_seeds(&mut dataset, SEED_ROWS_PER_ZONE).await; + let mut fragment_ranges = vec![(creating, 0..CREATE_ROWS)]; + for k in 0..APPENDED_FRAGMENTS { + let start = CREATE_ROWS + k * FRAGMENT_ROWS; + let end = start + FRAGMENT_ROWS; + let batches: Vec = (start..end) + .step_by(BATCH_ROWS as usize) + .map(|b| typed_rows(&data_type, b..(b + BATCH_ROWS).min(end))) + .collect(); + dataset + .append( + RecordBatchIterator::new( + batches + .into_iter() + .map(Ok::), + schema.clone(), + ), + Some(WriteParams { + mode: WriteMode::Append, + max_rows_per_file: FRAGMENT_ROWS as usize, + ..Default::default() + }), + ) + .await + .unwrap(); + fragment_ranges.push((dataset.fragments().last().unwrap().id, start..end)); + } + assert_eq!( + dataset.fragments().len(), + fragment_ranges.len(), + "{context}" + ); + let mut appended: Vec = fragment_ranges[1..].iter().map(|(id, _)| *id).collect(); + appended.sort_unstable(); + let mut all_fragments = appended.clone(); + all_fragments.push(creating); + all_fragments.sort_unstable(); + + let params = + ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(&serde_json::json!({ + "rows_per_zone": INDEX_ROWS_PER_ZONE, + "use_seeds": true, + "store_null_bitmap": index_store_null_bitmap, + })); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["col"], IndexType::ZoneMap, None, ¶ms, false) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1, "{context}: {reports:?}"); + let report = &reports[0]; + let sorted = |ids: &[u64]| { + let mut ids = ids.to_vec(); + ids.sort_unstable(); + ids + }; + // Per 64-row fragment, the 8-row records [16,24) and [56,64) cross an + // index zone boundary and are scanned; the other six are reused. + assert!(report.reused_fragments.is_empty(), "{context}: {report:?}"); + assert_eq!( + sorted(&report.partial_fragments), + appended, + "{context}: {report:?}" + ); + assert_eq!( + sorted(&report.scanned_fragments), + all_fragments, + "{context}: {report:?}" + ); + assert_eq!(report.reused_records, 12, "{context}: {report:?}"); + assert_eq!(report.scanned_rows, 11 + 2 * 16, "{context}: {report:?}"); + + let col = field_id(&dataset, "col"); + let indices = dataset.load_indices().await.unwrap(); + let mut batches = Vec::new(); + let mut stored: Vec = Vec::new(); + for segment in indices.iter().filter(|index| index.fields == vec![col]) { + let store = LanceIndexStore::from_dataset_for_existing(&dataset, segment) + .await + .unwrap(); + let version = ZoneMapIndexVersion::from_metadata(segment.index_version as u32).unwrap(); + let batch = ZoneMapIndex::load_zone_statistics(&store, version) + .await + .unwrap(); + let null_count = batch["null_count"].as_primitive::(); + let nan_count = batch["nan_count"].as_primitive::(); + let fragment_id = batch["fragment_id"].as_primitive::(); + let zone_start = batch["zone_start"].as_primitive::(); + let zone_length = batch["zone_length"].as_primitive::(); + for row in 0..batch.num_rows() { + stored.push(TypedZone { + fragment_id: fragment_id.value(row), + zone_start: zone_start.value(row), + zone_length: zone_length.value(row), + null_count: null_count.value(row), + nan_count: nan_count.value(row), + min: batch["min"].slice(row, 1), + max: batch["max"].slice(row, 1), + }); + } + batches.push(batch); + } + assert!(!batches.is_empty(), "{context}: no index on col"); + stored.sort_unstable_by_key(|zone| (zone.fragment_id, zone.zone_start)); + + // Min and max exclude nulls and NaN; the rest is ordered by Arrow's sort, + // which orders floats totally. + let mut expected: Vec = Vec::new(); + for (fragment_id, positions) in &fragment_ranges { + let column = typed_column(&data_type, positions.clone()); + let mut offset = 0; + while offset < column.len() { + let length = INDEX_ROWS_PER_ZONE.min(column.len() - offset); + let zone = column.slice(offset, length); + let floats = zone.as_primitive_opt::(); + let is_nan = + |row: usize| floats.is_some_and(|f| f.is_valid(row) && f.value(row).is_nan()); + let keep: Vec = (0..length) + .map(|row| zone.is_valid(row) && !is_nan(row)) + .collect(); + let values = arrow::compute::filter(zone.as_ref(), &BooleanArray::from(keep)).unwrap(); + let (min, max) = if values.is_empty() { + (new_null_array(&data_type, 1), new_null_array(&data_type, 1)) + } else { + let order = arrow::compute::sort_to_indices(values.as_ref(), None, None).unwrap(); + let ordered = arrow::compute::take(values.as_ref(), &order, None).unwrap(); + (ordered.slice(0, 1), ordered.slice(ordered.len() - 1, 1)) + }; + expected.push(TypedZone { + fragment_id: *fragment_id, + zone_start: offset as u64, + zone_length: length as u64, + null_count: zone.null_count() as u32, + nan_count: (0..length).filter(|row| is_nan(*row)).count() as u32, + min, + max, + }); + offset += length; + } + } + + assert_eq!( + stored.len(), + expected.len(), + "{context}: zone count, stored {batches:?}" + ); + for (stored, expected) in stored.iter().zip(&expected) { + assert_eq!( + stored, expected, + "{context}: zone {expected:?}, stored {stored:?} in {batches:?}" + ); + } + + let mut all_filters: Vec<&str> = filters.to_vec(); + all_filters.extend(["col IS NULL", "col IS NOT NULL"]); + assert_indexed_ids_match_scan(&dataset, &all_filters, &context).await; +} From cec085360aba2f649671aef891b8e3a39d67c04e Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 07:42:20 -0800 Subject: [PATCH 14/23] test: compare typed zone bounds through array equality Co-Authored-By: Claude --- .../src/dataset/tests/dataset_zone_map_seeds.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 7fbda354375..30c59a9cc30 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3909,7 +3909,7 @@ async fn test_config_seed_boundary_real_sizes( /// One stored or expected zone of the ZoneMap index on `col`; `min` and `max` /// are one-element arrays of the column's type. -#[derive(Debug, PartialEq)] +#[derive(Debug)] struct TypedZone { fragment_id: u64, zone_start: u64, @@ -3920,6 +3920,18 @@ struct TypedZone { max: ArrayRef, } +impl PartialEq for TypedZone { + fn eq(&self, other: &Self) -> bool { + self.fragment_id == other.fragment_id + && self.zone_start == other.zone_start + && self.zone_length == other.zone_length + && self.null_count == other.null_count + && self.nan_count == other.nan_count + && self.min.as_ref() == other.min.as_ref() + && self.max.as_ref() == other.max.as_ref() + } +} + /// The boundary shape where reused and scanned seed records mix (seed zones /// of 8 rows, index zones of 20, 64-row fragments written in 13-row batches), /// for each type family and both null-bitmap settings of the index. Stored From 759eebad7ab4733159c5b7d91d6eb5b27bc60c0c Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 08:06:45 -0800 Subject: [PATCH 15/23] test: extend the per-type seed boundary test to every round-trip type Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 30c59a9cc30..e11fcd32813 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3938,14 +3938,29 @@ impl PartialEq for TypedZone { /// zone statistics equal those computed from the generated arrays, and /// indexed filters match a scan. #[rstest::rstest] +#[case::boolean(DataType::Boolean, &["col = true"])] +#[case::int8(DataType::Int8, INT_FILTERS)] #[case::int32(DataType::Int32, INT_FILTERS)] +#[case::int64(DataType::Int64, INT_FILTERS)] +#[case::uint16(DataType::UInt16, INT_FILTERS)] +#[case::uint64(DataType::UInt64, INT_FILTERS)] +#[case::float32(DataType::Float32, FLOAT_FILTERS)] #[case::float64(DataType::Float64, FLOAT_FILTERS)] -#[case::utf8(DataType::Utf8, STRING_FILTERS)] +#[case::date32(DataType::Date32, &["col >= DATE '2022-02-07'"])] #[case::timestamp_ms( DataType::Timestamp(TimeUnit::Millisecond, None), &["col >= TIMESTAMP '2023-11-14 22:13:50'"] )] -#[case::boolean(DataType::Boolean, &["col = true"])] +#[case::timestamp_ns_utc(DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())), &[])] +#[case::duration_us(DataType::Duration(TimeUnit::Microsecond), &[])] +#[case::time32_s( + DataType::Time32(TimeUnit::Second), + &["col >= arrow_cast(1800, 'Time32(Second)')"] +)] +#[case::utf8(DataType::Utf8, STRING_FILTERS)] +#[case::large_utf8(DataType::LargeUtf8, STRING_FILTERS)] +#[case::binary(DataType::Binary, &["col >= X'000000000000001E'"])] +#[case::large_binary(DataType::LargeBinary, &["col >= X'000000000000001E'"])] #[case::decimal128(DataType::Decimal128(38, 4), &["col >= 30"])] #[tokio::test] async fn test_config_seed_boundary_per_type( @@ -3954,7 +3969,7 @@ async fn test_config_seed_boundary_per_type( #[values(false, true)] index_store_null_bitmap: bool, ) { use arrow::array::{AsArray, BooleanArray, new_null_array}; - use arrow::datatypes::{Float64Type, UInt32Type, UInt64Type}; + use arrow::datatypes::{Float32Type, Float64Type, UInt32Type, UInt64Type}; use lance_index::scalar::lance_format::LanceIndexStore; use lance_index::scalar::zonemap::{ZoneMapIndex, ZoneMapIndexVersion}; @@ -4097,9 +4112,12 @@ async fn test_config_seed_boundary_per_type( while offset < column.len() { let length = INDEX_ROWS_PER_ZONE.min(column.len() - offset); let zone = column.slice(offset, length); - let floats = zone.as_primitive_opt::(); - let is_nan = - |row: usize| floats.is_some_and(|f| f.is_valid(row) && f.value(row).is_nan()); + let doubles = zone.as_primitive_opt::(); + let singles = zone.as_primitive_opt::(); + let is_nan = |row: usize| { + doubles.is_some_and(|f| f.is_valid(row) && f.value(row).is_nan()) + || singles.is_some_and(|f| f.is_valid(row) && f.value(row).is_nan()) + }; let keep: Vec = (0..length) .map(|row| zone.is_valid(row) && !is_nan(row)) .collect(); From 0b403f4f540ade2d7aab0f8eae635379e4834008 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 23 Nov 2026 08:48:00 -0800 Subject: [PATCH 16/23] test: cover the remaining configured-seed types in the boundary oracle Co-Authored-By: Claude --- .../dataset/tests/dataset_zone_map_seeds.rs | 66 ++++++++++++++++++- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index e11fcd32813..a66b49e93ed 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3126,9 +3126,12 @@ fn typed_float(i: i64) -> Option { fn typed_column(data_type: &DataType, ids: std::ops::Range) -> ArrayRef { use arrow_array::{ - BooleanArray, Date32Array, Decimal128Array, DurationMicrosecondArray, Float32Array, - Float64Array, Int8Array, LargeBinaryArray, LargeStringArray, Time32SecondArray, - TimestampMillisecondArray, TimestampNanosecondArray, UInt16Array, UInt64Array, + BooleanArray, Date32Array, Date64Array, Decimal128Array, DurationMicrosecondArray, + DurationMillisecondArray, DurationNanosecondArray, DurationSecondArray, Float32Array, + Float64Array, Int8Array, Int16Array, LargeBinaryArray, LargeStringArray, + Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray, Time64NanosecondArray, + TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray, + TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array, UInt64Array, }; let values = ids.clone().map(typed_value); @@ -3182,6 +3185,49 @@ fn typed_column(data_type: &DataType, ids: std::ops::Range) -> ArrayRef { .with_precision_and_scale(*precision, *scale) .unwrap(), ), + DataType::Int16 => Arc::new(Int16Array::from_iter(values.map(|v| v.map(|v| v as i16)))), + DataType::UInt8 => Arc::new(UInt8Array::from_iter(values.map(|v| v.map(|v| v as u8)))), + DataType::UInt32 => Arc::new(UInt32Array::from_iter(values.map(|v| v.map(|v| v as u32)))), + // Halves of `typed_value` are exact in Float16; no NaN is generated. + DataType::Float16 => arrow::compute::cast( + &Float32Array::from_iter(values.map(|v| v.map(|v| v as f32 / 2.0))), + data_type, + ) + .unwrap(), + DataType::Date64 => Arc::new(Date64Array::from_iter( + values.map(|v| v.map(|v| (19_000 + v) * 86_400_000)), + )), + DataType::Time32(TimeUnit::Millisecond) => Arc::new(Time32MillisecondArray::from_iter( + values.map(|v| v.map(|v| (v * 60_000) as i32)), + )), + DataType::Time64(TimeUnit::Microsecond) => Arc::new(Time64MicrosecondArray::from_iter( + values.map(|v| v.map(|v| v * 60_000_000)), + )), + DataType::Time64(TimeUnit::Nanosecond) => Arc::new(Time64NanosecondArray::from_iter( + values.map(|v| v.map(|v| v * 60_000_000_000)), + )), + DataType::Timestamp(TimeUnit::Second, None) => Arc::new(TimestampSecondArray::from_iter( + values.map(|v| v.map(|v| 1_700_000_000 + v)), + )), + DataType::Timestamp(TimeUnit::Microsecond, None) => { + Arc::new(TimestampMicrosecondArray::from_iter( + values.map(|v| v.map(|v| 1_700_000_000_000_000 + v * 1_000_000)), + )) + } + DataType::Duration(TimeUnit::Second) => Arc::new(DurationSecondArray::from_iter(values)), + DataType::Duration(TimeUnit::Millisecond) => Arc::new(DurationMillisecondArray::from_iter( + values.map(|v| v.map(|v| v * 1_000)), + )), + DataType::Duration(TimeUnit::Nanosecond) => Arc::new(DurationNanosecondArray::from_iter( + values.map(|v| v.map(|v| v * 1_000)), + )), + DataType::Decimal256(_, scale) => arrow::compute::cast( + &Decimal128Array::from_iter(values.map(|v| v.map(|v| v as i128 * 10_000))) + .with_precision_and_scale(38, *scale) + .unwrap(), + data_type, + ) + .unwrap(), other => panic!("no generator for {other}"), } } @@ -3962,6 +4008,20 @@ impl PartialEq for TypedZone { #[case::binary(DataType::Binary, &["col >= X'000000000000001E'"])] #[case::large_binary(DataType::LargeBinary, &["col >= X'000000000000001E'"])] #[case::decimal128(DataType::Decimal128(38, 4), &["col >= 30"])] +#[case::int16(DataType::Int16, &[])] +#[case::uint8(DataType::UInt8, &[])] +#[case::uint32(DataType::UInt32, &[])] +#[case::float16(DataType::Float16, &[])] +#[case::date64(DataType::Date64, &[])] +#[case::time32_ms(DataType::Time32(TimeUnit::Millisecond), &[])] +#[case::time64_us(DataType::Time64(TimeUnit::Microsecond), &[])] +#[case::time64_ns(DataType::Time64(TimeUnit::Nanosecond), &[])] +#[case::timestamp_s(DataType::Timestamp(TimeUnit::Second, None), &[])] +#[case::timestamp_us(DataType::Timestamp(TimeUnit::Microsecond, None), &[])] +#[case::duration_s(DataType::Duration(TimeUnit::Second), &[])] +#[case::duration_ms(DataType::Duration(TimeUnit::Millisecond), &[])] +#[case::duration_ns(DataType::Duration(TimeUnit::Nanosecond), &[])] +#[case::decimal256(DataType::Decimal256(50, 4), &[])] #[tokio::test] async fn test_config_seed_boundary_per_type( #[case] data_type: DataType, From 3fa69928088f10fc3d3ef4428593e4b568215ef9 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 30 Nov 2026 14:09:27 -0800 Subject: [PATCH 17/23] refactor: read the configured seed zone size from the manifest in binary copy Co-Authored-By: Claude --- .../src/optimize/binary_copy.rs | 18 +-- rust/lance-table-runtime/src/write/seeds.rs | 11 +- rust/lance-table/src/feature_flags.rs | 125 +++++++++++++++++ rust/lance/src/dataset/write/seeds.rs | 132 +----------------- 4 files changed, 139 insertions(+), 147 deletions(-) diff --git a/rust/lance-table-runtime/src/optimize/binary_copy.rs b/rust/lance-table-runtime/src/optimize/binary_copy.rs index 2960ab52c61..72f056d564e 100644 --- a/rust/lance-table-runtime/src/optimize/binary_copy.rs +++ b/rust/lance-table-runtime/src/optimize/binary_copy.rs @@ -175,16 +175,16 @@ pub async fn rewrite_files_binary_copy( // Seeds of the inputs feeding the current output file, in copy order. let mut seed_acc = OutputSeedAccumulator::default(); let carry_v1_seeds = lance_table::feature_flags::write_v1_zone_write_seeds(&dataset.manifest); - let (index_rows_per_zone, unindexed_rows_per_zone) = match seed_hook { - Some(hook) => ( - hook.index_rows_per_zone(dataset).await?, - hook.unindexed_rows_per_zone(dataset), - ), - None => ( - Default::default(), - lance_table::format::index_seed::ROWS_PER_ZONE_DEFAULT, - ), + let index_rows_per_zone = match seed_hook { + Some(hook) => hook.index_rows_per_zone(dataset).await?, + None => Default::default(), }; + let unindexed_rows_per_zone = + lance_table::feature_flags::ZoneWriteSeedsConfig::from_config(&dataset.manifest.config) + .map_or( + lance_table::format::index_seed::ROWS_PER_ZONE_DEFAULT, + |config| config.rows_per_zone, + ); // Visit each fragment and all of its data files (a fragment may contain multiple files) for frag in fragments.iter() { diff --git a/rust/lance-table-runtime/src/write/seeds.rs b/rust/lance-table-runtime/src/write/seeds.rs index 844522c4188..8a73eb44c29 100644 --- a/rust/lance-table-runtime/src/write/seeds.rs +++ b/rust/lance-table-runtime/src/write/seeds.rs @@ -7,7 +7,7 @@ use std::collections::HashMap; use lance_core::{Result, datatypes::Schema}; use lance_file::version::ConcreteFileVersion; -use lance_table::format::index_seed::{IndexSeedWriter, ROWS_PER_ZONE_DEFAULT}; +use lance_table::format::index_seed::IndexSeedWriter; use crate::Table; @@ -29,17 +29,10 @@ pub trait WriteSeedHook: Send + Sync { ) -> Result>>; /// Current ZoneMap zone sizes by top-level field ID for carrying seeds - /// through binary copy. Unspecified fields use - /// [`Self::unindexed_rows_per_zone`]. + /// through binary copy. Unspecified fields use the format default. async fn index_rows_per_zone(&self, _table: &Table) -> Result> { Ok(HashMap::new()) } - - /// Zone size declared for carried seeds of fields that - /// [`Self::index_rows_per_zone`] does not list. - fn unindexed_rows_per_zone(&self, _table: &Table) -> u64 { - ROWS_PER_ZONE_DEFAULT - } } /// Collects write seeds for the columns of one data file. diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index b1ad60b69ff..f0882baa3eb 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -3,6 +3,9 @@ //! Feature flags +use std::collections::HashMap; + +use crate::format::index_seed::ROWS_PER_ZONE_DEFAULT; use crate::format::{IndexMetadata, Manifest}; use lance_core::{Error, Result, datatypes::Schema}; @@ -387,6 +390,69 @@ pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { Ok(()) } +/// The dataset-level zone write seed setting, parsed from the dataset config. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ZoneWriteSeedsConfig { + /// Rows per seed zone for columns without a seeded ZoneMap index. + pub rows_per_zone: u64, + /// Whether those seeds record null positions. + pub store_null_bitmap: bool, +} + +impl ZoneWriteSeedsConfig { + /// The setting in `config`, or `None` when it is disabled. + /// + /// Values are validated when they are set + /// ([`validate_zone_write_seeds_config`]), so this read is lenient: an + /// unparsable `enabled` disables the setting, an invalid `rows_per_zone` + /// falls back to [`ROWS_PER_ZONE_DEFAULT`] and an unparsable + /// `store_null_bitmap` records null positions, each with a warning. That + /// only matters for a manifest written by a build that did not validate + /// them. + pub fn from_config(config: &HashMap) -> Option { + let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; + match enabled.parse::() { + Ok(true) => {} + Ok(false) => return None, + Err(err) => { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_ENABLED_KEY}={enabled:?} ({err}); zone write \ + seeds stay disabled" + ); + return None; + } + } + let rows_per_zone = match config.get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) { + None => ROWS_PER_ZONE_DEFAULT, + Some(value) => match value.parse::() { + Ok(rows) if rows > 0 && rows <= u64::from(u32::MAX) => rows, + _ => { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected an \ + integer between 1 and {}; using {ROWS_PER_ZONE_DEFAULT}", + u32::MAX + ); + ROWS_PER_ZONE_DEFAULT + } + }, + }; + let store_null_bitmap = match config.get(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY) { + None => true, + Some(value) => value.parse::().unwrap_or_else(|err| { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?} ({err}); zone \ + write seeds record null positions" + ); + true + }), + }; + Some(Self { + rows_per_zone, + store_null_bitmap, + }) + } +} + /// Validate a change to [`ZONE_WRITE_SEEDS_VERSION_KEY`]. /// /// Accepts absent, `"0"`, or `"1"`. Call before publishing a commit that @@ -1248,6 +1314,65 @@ mod tests { assert!(message.contains(&format!("{value:?}")), "{message}"); } + #[rstest::rstest] + #[case::absent(&[], None)] + #[case::disabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")], None)] + #[case::size_without_enabled(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], None)] + #[case::unparsable_enabled( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], + None + )] + #[case::default_size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")], Some((ROWS_PER_ZONE_DEFAULT, true)))] + #[case::explicit_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], + Some((16, true)) + )] + #[case::zero_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::negative_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::unparsable_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::too_large_size( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::no_null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false")], + Some((ROWS_PER_ZONE_DEFAULT, false)) + )] + #[case::unparsable_null_bitmap( + &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")], + Some((ROWS_PER_ZONE_DEFAULT, true)) + )] + #[case::null_bitmap_without_enabled(&[(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], None)] + fn test_zone_write_seeds_config_from_config( + #[case] entries: &[(&str, &str)], + #[case] expected: Option<(u64, bool)>, + ) { + let config: HashMap = entries + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(); + assert_eq!( + ZoneWriteSeedsConfig::from_config(&config), + expected.map(|(rows_per_zone, store_null_bitmap)| ZoneWriteSeedsConfig { + rows_per_zone, + store_null_bitmap, + }) + ); + } + #[test] fn test_zone_write_seeds_require_both_feature_bits() { for (reader, writer) in [(true, false), (false, true)] { diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 72ebb15af36..231f86dc78e 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -15,7 +15,7 @@ //! or `"false"` disables this. //! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those //! columns, an integer in `1..=u32::MAX`. Absent, it is -//! [`ROWS_PER_ZONE_DEFAULT`]. +//! [`ROWS_PER_ZONE_DEFAULT`](lance_table::format::index_seed::ROWS_PER_ZONE_DEFAULT). //! - `lance.zone_write_seeds.store_null_bitmap`: whether those seeds record //! null positions, so they can serve a ZoneMap index with //! `store_null_bitmap = true` (the index default). Absent or `"true"`, @@ -46,11 +46,11 @@ use lance_core::Result; use lance_core::datatypes::{Field, Schema}; use lance_file::version::ConcreteFileVersion; use lance_index::pbold; -use lance_index::scalar::zonemap::{ROWS_PER_ZONE_DEFAULT, ZoneMapSeedVersion, ZoneMapSeedWriter}; +use lance_index::scalar::zonemap::{ZoneMapSeedVersion, ZoneMapSeedWriter}; use lance_table::feature_flags::write_v1_zone_write_seeds; pub use lance_table::feature_flags::{ ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, - ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, ZoneWriteSeedsConfig, }; use lance_table::format::IndexMetadata; use lance_table::format::index_seed::IndexSeedWriter; @@ -66,68 +66,6 @@ use lance_table_runtime::{Table, WriteSeedHook}; /// reported once per process and at debug level afterwards. static SEED_CONFLICT_WARNED: std::sync::Once = std::sync::Once::new(); -/// The dataset-level zone write seed setting, parsed from the dataset config. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ZoneWriteSeedsConfig { - /// Rows per seed zone for columns without a seeded ZoneMap index. - pub rows_per_zone: u64, - /// Whether those seeds record null positions. - pub store_null_bitmap: bool, -} - -impl ZoneWriteSeedsConfig { - /// The setting in `config`, or `None` when it is disabled. - /// - /// Values are validated when they are set - /// (`validate_zone_write_seeds_config`), so this read is lenient: an - /// unparsable `enabled` disables the setting, an invalid `rows_per_zone` - /// falls back to [`ROWS_PER_ZONE_DEFAULT`] and an unparsable - /// `store_null_bitmap` records null positions, each with a warning. That only matters for a manifest written by a build that did - /// not validate them. - pub fn from_config(config: &HashMap) -> Option { - let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; - match enabled.parse::() { - Ok(true) => {} - Ok(false) => return None, - Err(err) => { - log::warn!( - "ignoring {ZONE_WRITE_SEEDS_ENABLED_KEY}={enabled:?} ({err}); zone write \ - seeds stay disabled" - ); - return None; - } - } - let rows_per_zone = match config.get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) { - None => ROWS_PER_ZONE_DEFAULT, - Some(value) => match value.parse::() { - Ok(rows) if rows > 0 && rows <= u64::from(u32::MAX) => rows, - _ => { - log::warn!( - "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected an \ - integer between 1 and {}; using {ROWS_PER_ZONE_DEFAULT}", - u32::MAX - ); - ROWS_PER_ZONE_DEFAULT - } - }, - }; - let store_null_bitmap = match config.get(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY) { - None => true, - Some(value) => value.parse::().unwrap_or_else(|err| { - log::warn!( - "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?} ({err}); zone \ - write seeds record null positions" - ); - true - }), - }; - Some(Self { - rows_per_zone, - store_null_bitmap, - }) - } -} - /// Selects seed writers using Lance's scalar index registry. pub struct LanceWriteSeedHook { session: Arc, @@ -194,11 +132,6 @@ impl WriteSeedHook for LanceWriteSeedHook { } Ok(rows_per_zone) } - - fn unindexed_rows_per_zone(&self, table: &Table) -> u64 { - ZoneWriteSeedsConfig::from_config(&table.manifest().config) - .map_or(ROWS_PER_ZONE_DEFAULT, |config| config.rows_per_zone) - } } pub async fn collect_write_seeds( @@ -453,65 +386,6 @@ mod tests { } } - #[rstest::rstest] - #[case::absent(&[], None)] - #[case::disabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")], None)] - #[case::size_without_enabled(&[(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], None)] - #[case::unparsable_enabled( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "yes"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], - None - )] - #[case::default_size(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true")], Some((ROWS_PER_ZONE_DEFAULT, true)))] - #[case::explicit_size( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16")], - Some((16, true)) - )] - #[case::zero_size( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::negative_size( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::unparsable_size( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::too_large_size( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::null_bitmap( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::no_null_bitmap( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false")], - Some((ROWS_PER_ZONE_DEFAULT, false)) - )] - #[case::unparsable_null_bitmap( - &[(ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")], - Some((ROWS_PER_ZONE_DEFAULT, true)) - )] - #[case::null_bitmap_without_enabled(&[(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true")], None)] - fn test_zone_write_seeds_config_from_config( - #[case] entries: &[(&str, &str)], - #[case] expected: Option<(u64, bool)>, - ) { - let config: HashMap = entries - .iter() - .map(|(key, value)| (key.to_string(), value.to_string())) - .collect(); - assert_eq!( - ZoneWriteSeedsConfig::from_config(&config), - expected.map(|(rows_per_zone, store_null_bitmap)| ZoneWriteSeedsConfig { - rows_per_zone, - store_null_bitmap, - }) - ); - } - #[rstest::rstest] #[case::boolean(DataType::Boolean, true)] #[case::int64(DataType::Int64, true)] From 45aa04ea58bd4e9e30aacbadc133857f714935ad Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 30 Nov 2026 15:10:46 -0800 Subject: [PATCH 18/23] fix: let unknown keys under the zone write seeds prefix pass validation The validator walks the whole manifest config, so rejecting keys it does not know would let a key written by a newer release block every later change under the prefix. Validate only known keys, as the other config validators do. Co-Authored-By: Claude --- rust/lance-table/src/feature_flags.rs | 36 ++++++++++++++----- .../src/transaction/action/config_update.rs | 12 +++++-- .../dataset/tests/dataset_zone_map_seeds.rs | 30 +++++++++++++++- rust/lance/src/dataset/write/seeds.rs | 4 +-- 4 files changed, 68 insertions(+), 14 deletions(-) diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index f0882baa3eb..34ecb59337d 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -353,8 +353,10 @@ pub const ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY: &str = "lance.zone_write_seeds /// and `lance.zone_write_seeds.rows_per_zone` an integer in `1..=u32::MAX`: /// per-zone null and NaN counts are 32-bit, as are the row offsets a zone /// spans within a fragment. [`ZONE_WRITE_SEEDS_VERSION_KEY`] is checked by -/// [`validate_zone_write_seeds_version_config`]. No other key may use the -/// prefix. Call before publishing a change to these keys. +/// [`validate_zone_write_seeds_version_config`]. Keys under the prefix that +/// this build does not know are left alone, so settings added by later +/// releases do not block changes here. Call before publishing a change to +/// these keys. pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { for (key, value) in manifest.config.iter() { if !key.starts_with(ZONE_WRITE_SEEDS_CONFIG_PREFIX) { @@ -380,11 +382,7 @@ pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { } } ZONE_WRITE_SEEDS_VERSION_KEY => validate_zone_write_seeds_version_config(manifest)?, - _ => { - return Err(Error::invalid_input(format!( - "Unknown zone write seeds configuration key: {key}={value:?}" - ))); - } + _ => {} } } Ok(()) @@ -1277,6 +1275,11 @@ mod tests { #[case::no_null_bitmap(&[(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false")])] #[case::unrelated_key(&[("lance.zone_write_seedsx", "1"), ("other.key", "x")])] #[case::version_0(&[(ZONE_WRITE_SEEDS_VERSION_KEY, "0")])] + #[case::unknown_key(&[("lance.zone_write_seeds.rows_per_zonee", "8")])] + #[case::unknown_key_with_enabled_change(&[ + ("lance.zone_write_seeds.future_setting", "anything"), + (ZONE_WRITE_SEEDS_ENABLED_KEY, "false"), + ])] #[case::all_keys_with_version(&[ (ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "16"), @@ -1301,7 +1304,6 @@ mod tests { #[case::negative_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "-4")] #[case::garbage_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "many")] #[case::too_large_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")] - #[case::unknown_key("lance.zone_write_seeds.rows_per_zonee", "8")] #[case::version_2(ZONE_WRITE_SEEDS_VERSION_KEY, "2")] #[case::version_bool(ZONE_WRITE_SEEDS_VERSION_KEY, "true")] fn test_zone_write_seeds_config_rejects_invalid_values(#[case] key: &str, #[case] value: &str) { @@ -1314,6 +1316,24 @@ mod tests { assert!(message.contains(&format!("{value:?}")), "{message}"); } + #[test] + fn test_zone_write_seeds_config_rejects_invalid_value_beside_unknown_key() { + let mut manifest = empty_manifest(); + manifest.config.insert( + "lance.zone_write_seeds.future_setting".to_string(), + "anything".to_string(), + ); + manifest + .config + .insert(ZONE_WRITE_SEEDS_ENABLED_KEY.to_string(), "yes".to_string()); + let error = validate_zone_write_seeds_config(&manifest).unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. }), "{error}"); + assert!( + error.to_string().contains(ZONE_WRITE_SEEDS_ENABLED_KEY), + "{error}" + ); + } + #[rstest::rstest] #[case::absent(&[], None)] #[case::disabled(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")], None)] diff --git a/rust/lance-table/src/transaction/action/config_update.rs b/rust/lance-table/src/transaction/action/config_update.rs index e87109aff57..f8c48eb44bc 100644 --- a/rust/lance-table/src/transaction/action/config_update.rs +++ b/rust/lance-table/src/transaction/action/config_update.rs @@ -766,7 +766,7 @@ mod tests { assert_ne!(with_version.reader_feature_flags & FLAG_ZONE_WRITE_SEEDS, 0); assert_ne!(with_version.writer_feature_flags & FLAG_ZONE_WRITE_SEEDS, 0); - let error = apply( + let with_unknown_key = apply( &backed_manifest(), vec![set_config(&[ (ZONE_WRITE_SEEDS_ENABLED_KEY, Some("true")), @@ -774,8 +774,14 @@ mod tests { ("lance.zone_write_seeds.unknown", Some("1")), ])], ) - .unwrap_err(); - assert!(matches!(error, Error::InvalidInput { .. }), "{error:?}"); + .unwrap(); + assert_eq!( + with_unknown_key + .config + .get("lance.zone_write_seeds.unknown") + .map(String::as_str), + Some("1") + ); } #[test] diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index f7bb289812c..8a93557c5a4 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -3178,6 +3178,35 @@ async fn test_binary_copy_declares_configured_rows_per_zone(#[case] v1: bool) { } } +/// A key under the zone write seeds prefix that this build does not know is +/// stored as is, and later changes to known keys still commit beside it. +#[tokio::test] +async fn test_config_keeps_unknown_zone_write_seeds_key() { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + enable_zone_write_seeds(&mut dataset, ROWS_PER_ZONE).await; + + let unknown_key = "lance.zone_write_seeds.unknown"; + dataset.update_config([(unknown_key, "1")]).await.unwrap(); + dataset + .update_config([(ZONE_WRITE_SEEDS_ENABLED_KEY, "false")]) + .await + .unwrap(); + + let reopened = Dataset::open(dir.as_str()).await.unwrap(); + assert_eq!( + reopened.config().get(unknown_key).map(String::as_str), + Some("1") + ); + assert_eq!( + reopened + .config() + .get(ZONE_WRITE_SEEDS_ENABLED_KEY) + .map(String::as_str), + Some("false") + ); +} + /// Setting an invalid zone write seed value is rejected by its commit and /// leaves the config as it was; unrelated config changes still commit. #[rstest::rstest] @@ -3185,7 +3214,6 @@ async fn test_binary_copy_declares_configured_rows_per_zone(#[case] v1: bool) { #[case::rows_per_zone(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "0")] #[case::store_null_bitmap(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "yes")] #[case::version(ZONE_WRITE_SEEDS_VERSION_KEY, "2")] -#[case::unknown_key("lance.zone_write_seeds.unknown", "1")] #[tokio::test] async fn test_config_rejects_invalid_zone_write_seeds_value( #[case] key: &'static str, diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 231f86dc78e..5a285cf5f3c 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -22,8 +22,8 @@ //! they do; `"false"` records none, and the seeds then only serve indexes //! that store no null bitmap. //! -//! Setting any of these keys to an invalid value, or any other key under -//! `lance.zone_write_seeds.`, is rejected by the commit that sets it. +//! Setting any of these keys to an invalid value is rejected by the commit +//! that sets it. Other keys under `lance.zone_write_seeds.` are not validated. //! //! These keys only choose which columns are seeded. The seed format follows //! `lance.zone_write_seeds.version` exactly as for index-requested seeds: From 77852797b6a54f267464b693aceba7dfd1735012 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Mon, 30 Nov 2026 20:16:31 -0800 Subject: [PATCH 19/23] docs: list zone write seed keys in the table config spec Document lance.zone_write_seeds.enabled, rows_per_zone, store_null_bitmap and version in the table config spec, with what other implementations must do with them. Make the binary-copy zone size selection a pure function with unit tests, and share the value parsing between config validation and ZoneWriteSeedsConfig::from_config. Co-Authored-By: Claude --- .../format/index/scalar/zone_write_seeds.md | 11 +++ docs/src/format/table/table_config.md | 14 +++ rust/lance-table/src/feature_flags.rs | 86 +++++++++++++------ rust/lance/src/dataset/write/seeds.rs | 52 ++++++++--- 4 files changed, 127 insertions(+), 36 deletions(-) diff --git a/docs/src/format/index/scalar/zone_write_seeds.md b/docs/src/format/index/scalar/zone_write_seeds.md index c5232a682ad..a8531e014e2 100644 --- a/docs/src/format/index/scalar/zone_write_seeds.md +++ b/docs/src/format/index/scalar/zone_write_seeds.md @@ -9,6 +9,17 @@ fragment or index segment pruning, or build an index without rereading the colum This proposal defines version 1 seeds. It does not change the ZoneMap index format or enable version 1 writes; implementation follows separately. +## Table configuration + +Columns with a seeded ZoneMap index (`use_seeds=true`) get the seeds that index +requests. Other columns are seeded only when the table sets +`lance.zone_write_seeds.enabled`, with zone size and null-position collection +controlled by `lance.zone_write_seeds.rows_per_zone` and +`lance.zone_write_seeds.store_null_bitmap`. These keys only choose which +columns are seeded; the seed version follows `lance.zone_write_seeds.version`. +See [Table Config](../../table/table_config.md) for types, defaults, and +supported column types. + ## Arrow Rust ordering Zone statistics follow [Arrow Rust ordering](https://arrow.apache.org/rust/arrow_ord/sort/fn.sort.html). diff --git a/docs/src/format/table/table_config.md b/docs/src/format/table/table_config.md index 1f541b45140..cf7f364893d 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -49,7 +49,21 @@ full set of metadata maps. | `lance.compaction.max_source_rows` | Non-negative integer | Maximum number of live source rows (physical rows minus soft-deleted rows) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_source_bytes` | Non-negative integer | Maximum number of source bytes (data files and [data overlay files](data_overlay_file.md), excluding blob v2 payloads) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_overlays_per_fragment` | Non-negative integer or `none` | Maximum number of [data overlay files](data_overlay_file.md) a fragment may carry before it is fully compacted (overlays and deletions materialized into the base data). Defaults to `10`. Set to `0` to compact every fragment with any overlay, or `none` to disable the trigger. | +| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and variable-length binary; nested, vector, dictionary, fixed-size binary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. Defaults to `false`. | +| `lance.zone_write_seeds.rows_per_zone` | Integer (1 to 4,294,967,295) | Rows per seed zone for the columns seeded because of `lance.zone_write_seeds.enabled`. Defaults to `8192`. | +| `lance.zone_write_seeds.store_null_bitmap` | Boolean (`true`/`false`) | Whether the seeds collected because of `lance.zone_write_seeds.enabled` record null positions, so they can serve a ZoneMap index that stores a null bitmap. With `false`, those seeds only serve indexes that store no null bitmap. Defaults to `true`. | +| `lance.zone_write_seeds.version` | `0` or `1` | [Zone write seed](../index/scalar/zone_write_seeds.md) format version. A commit that itself writes `1` sets `FLAG_ZONE_WRITE_SEEDS` in both feature flag words; an inherited `1` does not. Once set, the flag stays set and writers emit version 1 seeds unless this key is explicitly `0`. Without the flag, writers emit version 0 seeds. Unset by default. | Unrecognized `lance.compaction.*` keys are ignored with a warning; unrecognized keys under other `lance.*` prefixes should likewise be ignored by conforming readers rather than treated as errors. + +Zone write seeds are optional metadata, so an implementation that does not +write seeds only needs to preserve the `lance.zone_write_seeds.*` keys. +`enabled`, `rows_per_zone`, and `store_null_bitmap` only affect which seeds a +writer collects; they never change what readers must understand and never set +a feature flag. The seed format a writer emits and +[`FLAG_ZONE_WRITE_SEEDS`](versioning.md#current-feature-flags) are governed by +`lance.zone_write_seeds.version` alone. Setting a known key to an invalid +value is rejected by the commit that sets it; unknown keys under the +`lance.zone_write_seeds.` prefix are preserved and not rejected. diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index 34ecb59337d..2d44bad53b8 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -364,17 +364,14 @@ pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { } match key.as_str() { ZONE_WRITE_SEEDS_ENABLED_KEY | ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY => { - if value != "true" && value != "false" { + if parse_zone_write_seeds_bool(value).is_none() { return Err(Error::invalid_input(format!( "{key} must be \"true\" or \"false\", got {value:?}" ))); } } ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY => { - let valid = value - .parse::() - .is_ok_and(|rows| rows > 0 && rows <= u64::from(u32::MAX)); - if !valid { + if parse_zone_write_seeds_rows_per_zone(value).is_none() { return Err(Error::invalid_input(format!( "{key} must be an integer between 1 and {}, got {value:?}", u32::MAX @@ -388,6 +385,20 @@ pub fn validate_zone_write_seeds_config(manifest: &Manifest) -> Result<()> { Ok(()) } +/// A zone write seed boolean value: exactly `"true"` or `"false"`. +fn parse_zone_write_seeds_bool(value: &str) -> Option { + value.parse::().ok() +} + +/// A zone write seed `rows_per_zone` value: an integer in `1..=u32::MAX`, +/// since per-zone counts and in-fragment row offsets are 32-bit. +fn parse_zone_write_seeds_rows_per_zone(value: &str) -> Option { + value + .parse::() + .ok() + .filter(|rows| (1..=u64::from(u32::MAX)).contains(rows)) +} + /// The dataset-level zone write seed setting, parsed from the dataset config. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ZoneWriteSeedsConfig { @@ -409,37 +420,34 @@ impl ZoneWriteSeedsConfig { /// them. pub fn from_config(config: &HashMap) -> Option { let enabled = config.get(ZONE_WRITE_SEEDS_ENABLED_KEY)?; - match enabled.parse::() { - Ok(true) => {} - Ok(false) => return None, - Err(err) => { + match parse_zone_write_seeds_bool(enabled) { + Some(true) => {} + Some(false) => return None, + None => { log::warn!( - "ignoring {ZONE_WRITE_SEEDS_ENABLED_KEY}={enabled:?} ({err}); zone write \ - seeds stay disabled" + "ignoring {ZONE_WRITE_SEEDS_ENABLED_KEY}={enabled:?}: expected \"true\" or \ + \"false\"; zone write seeds stay disabled" ); return None; } } let rows_per_zone = match config.get(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY) { None => ROWS_PER_ZONE_DEFAULT, - Some(value) => match value.parse::() { - Ok(rows) if rows > 0 && rows <= u64::from(u32::MAX) => rows, - _ => { - log::warn!( - "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected an \ - integer between 1 and {}; using {ROWS_PER_ZONE_DEFAULT}", - u32::MAX - ); - ROWS_PER_ZONE_DEFAULT - } - }, + Some(value) => parse_zone_write_seeds_rows_per_zone(value).unwrap_or_else(|| { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY}={value:?}: expected an \ + integer between 1 and {}; using {ROWS_PER_ZONE_DEFAULT}", + u32::MAX + ); + ROWS_PER_ZONE_DEFAULT + }), }; let store_null_bitmap = match config.get(ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY) { None => true, - Some(value) => value.parse::().unwrap_or_else(|err| { + Some(value) => parse_zone_write_seeds_bool(value).unwrap_or_else(|| { log::warn!( - "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?} ({err}); zone \ - write seeds record null positions" + "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?}: expected \ + \"true\" or \"false\"; zone write seeds record null positions" ); true }), @@ -980,6 +988,34 @@ mod tests { use super::*; use crate::format::{BasePath, DeletionFile, DeletionFileType, Fragment}; + #[rstest::rstest] + #[case::true_("true", Some(true))] + #[case::false_("false", Some(false))] + #[case::uppercase("TRUE", None)] + #[case::capitalized("False", None)] + #[case::number("1", None)] + #[case::padded(" true", None)] + #[case::empty("", None)] + fn test_parse_zone_write_seeds_bool(#[case] value: &str, #[case] expected: Option) { + assert_eq!(parse_zone_write_seeds_bool(value), expected); + } + + #[rstest::rstest] + #[case::one("1", Some(1))] + #[case::typical("8192", Some(8192))] + #[case::max("4294967295", Some(u64::from(u32::MAX)))] + #[case::zero("0", None)] + #[case::above_max("4294967296", None)] + #[case::negative("-1", None)] + #[case::not_a_number("abc", None)] + #[case::empty("", None)] + fn test_parse_zone_write_seeds_rows_per_zone( + #[case] value: &str, + #[case] expected: Option, + ) { + assert_eq!(parse_zone_write_seeds_rows_per_zone(value), expected); + } + #[rstest::rstest] #[case::missing(None, "requires a cleanup policy")] #[case::age_only( diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 5a285cf5f3c..67e9d6e241d 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -98,7 +98,7 @@ impl WriteSeedHook for LanceWriteSeedHook { async fn index_rows_per_zone(&self, table: &Table) -> Result> { let dataset = Dataset::from_committed_table(table.clone(), self.session.clone()); - let mut rows_per_zone = HashMap::new(); + let mut zone_maps: HashMap)>> = HashMap::new(); for index in load_all_indices(&dataset) .await? .iter() @@ -118,22 +118,39 @@ impl WriteSeedHook for LanceWriteSeedHook { let Ok(details) = fetch_index_details(&dataset, &field.name, index).await else { continue; }; - // Only seeded indices decide a column's seed zone size; several - // share the finest, as the write path chooses it. - if let Ok(zone_map) = details.to_msg::() - && zone_map.use_seeds.unwrap_or(false) - && let Some(configured) = zone_map.rows_per_zone - { - rows_per_zone + if let Ok(zone_map) = details.to_msg::() { + zone_maps .entry(field_id) - .and_modify(|rows: &mut u64| *rows = (*rows).min(configured)) - .or_insert(configured); + .or_default() + .push((zone_map.use_seeds.unwrap_or(false), zone_map.rows_per_zone)); } } - Ok(rows_per_zone) + Ok(zone_maps + .into_iter() + .filter_map(|(field_id, indexes)| { + seeded_rows_per_zone(indexes).map(|rows_per_zone| (field_id, rows_per_zone)) + }) + .collect()) } } +/// The seed zone size of one column, given each of its ZoneMap indexes as +/// `(use_seeds, rows_per_zone)`. +/// +/// Only seeded indexes decide a column's seed zone size: an unseeded index +/// never reads seeds, so its zone size must not shape them. Several seeded +/// indexes share one seed of the finest size, which serves every coarser +/// index through whole-record reuse, as the write path chooses it. An index +/// without `rows_per_zone` contributes nothing. `None` means no seeded index +/// decides the size, so the configured size applies. +fn seeded_rows_per_zone(indexes: impl IntoIterator)>) -> Option { + indexes + .into_iter() + .filter(|(use_seeds, _)| *use_seeds) + .filter_map(|(_, rows_per_zone)| rows_per_zone) + .min() +} + pub async fn collect_write_seeds( version: ConcreteFileVersion, dataset: &Dataset, @@ -428,6 +445,19 @@ mod tests { assert_eq!(config_seed_supports(&field), expected); } + #[rstest::rstest] + #[case::no_indexes(vec![], None)] + #[case::only_unseeded(vec![(false, Some(8))], None)] + #[case::two_seeded(vec![(true, Some(8)), (true, Some(16))], Some(8))] + #[case::seeded_and_unseeded_finer(vec![(true, Some(16)), (false, Some(8))], Some(16))] + #[case::seeded_without_size(vec![(true, None)], None)] + fn test_seeded_rows_per_zone( + #[case] indexes: Vec<(bool, Option)>, + #[case] expected: Option, + ) { + assert_eq!(seeded_rows_per_zone(indexes), expected); + } + #[test] fn test_config_seed_skips_blob_columns() { let blob_v2 = Field::try_from(&crate::blob::blob_field("blob", true)).unwrap(); From 7ec156bb407cf02cecbf2f3d38a9c0f36d0b168a Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Wed, 2 Dec 2026 11:55:40 -0800 Subject: [PATCH 20/23] feat: seed fixed-size binary columns from the table config Zone statistics now compute min/max bounds for fixed-size binary values, so a seed for such a column can be reused by an index build. Co-Authored-By: Claude --- docs/src/format/table/table_config.md | 2 +- rust/lance/src/dataset/write/seeds.rs | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/src/format/table/table_config.md b/docs/src/format/table/table_config.md index cf7f364893d..0d6c374f900 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -49,7 +49,7 @@ full set of metadata maps. | `lance.compaction.max_source_rows` | Non-negative integer | Maximum number of live source rows (physical rows minus soft-deleted rows) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_source_bytes` | Non-negative integer | Maximum number of source bytes (data files and [data overlay files](data_overlay_file.md), excluding blob v2 payloads) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_overlays_per_fragment` | Non-negative integer or `none` | Maximum number of [data overlay files](data_overlay_file.md) a fragment may carry before it is fully compacted (overlays and deletions materialized into the base data). Defaults to `10`. Set to `0` to compact every fragment with any overlay, or `none` to disable the trigger. | -| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and variable-length binary; nested, vector, dictionary, fixed-size binary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. Defaults to `false`. | +| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and binary (variable-length or fixed-size); nested, vector, dictionary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. Defaults to `false`. | | `lance.zone_write_seeds.rows_per_zone` | Integer (1 to 4,294,967,295) | Rows per seed zone for the columns seeded because of `lance.zone_write_seeds.enabled`. Defaults to `8192`. | | `lance.zone_write_seeds.store_null_bitmap` | Boolean (`true`/`false`) | Whether the seeds collected because of `lance.zone_write_seeds.enabled` record null positions, so they can serve a ZoneMap index that stores a null bitmap. With `false`, those seeds only serve indexes that store no null bitmap. Defaults to `true`. | | `lance.zone_write_seeds.version` | `0` or `1` | [Zone write seed](../index/scalar/zone_write_seeds.md) format version. A commit that itself writes `1` sets `FLAG_ZONE_WRITE_SEEDS` in both feature flag words; an inherited `1` does not. Once set, the flag stays set and writers emit version 1 seeds unless this key is explicitly `0`. Without the flag, writers emit version 0 seeds. Unset by default. | diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 67e9d6e241d..fb7c50770ac 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -331,10 +331,7 @@ async fn seed_writers_for( /// Whether the dataset config seeds `field`: flat columns of a candidate /// scalar type only. The list is a conservative gate, not a guarantee about /// collection cost. Blob and extension-typed columns are excluded because -/// the written values are not the column's logical values. FixedSizeBinary -/// is excluded at every width: zone statistics compute no min/max bounds for -/// fixed-size binary values, so a seed zone holding non-null values cannot be -/// validated by an index build. +/// the written values are not the column's logical values. fn config_seed_supports(field: &Field) -> bool { if field.is_blob() || field.is_blob_v2() || field.extension_name().is_some() { return false; @@ -363,6 +360,7 @@ fn config_seed_supports(field: &Field) -> bool { | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary + | DataType::FixedSizeBinary(_) | DataType::Decimal128(_, _) | DataType::Decimal256(_, _) ) @@ -417,8 +415,8 @@ mod tests { #[case::duration(DataType::Duration(arrow_schema::TimeUnit::Second), true)] #[case::utf8(DataType::Utf8, true)] #[case::large_binary(DataType::LargeBinary, true)] - #[case::fixed_size_binary_narrow(DataType::FixedSizeBinary(4), false)] - #[case::fixed_size_binary_wide(DataType::FixedSizeBinary(16), false)] + #[case::fixed_size_binary_narrow(DataType::FixedSizeBinary(4), true)] + #[case::fixed_size_binary_wide(DataType::FixedSizeBinary(16), true)] #[case::decimal128(DataType::Decimal128(10, 2), true)] #[case::null(DataType::Null, false)] #[case::fixed_size_list( From fc47019372c0099bec6ab020f8235e6ca26baa42 Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Wed, 2 Dec 2026 12:46:21 -0800 Subject: [PATCH 21/23] docs: state when an index build reads configured zone write seeds An index created without an explicit use_seeds takes the type-based default, which is false for fixed-width types of 8 bytes or less, so those columns need use_seeds=true to reuse configured seeds. Add a test that pins this, use "indices" in the new code and docs, and shrink the two million-row boundary cases to the same geometry at small sizes. Co-Authored-By: Claude --- .../format/index/scalar/zone_write_seeds.md | 5 + docs/src/format/table/table_config.md | 4 +- .../dataset/tests/dataset_zone_map_seeds.rs | 99 +++++++++++++++++-- rust/lance/src/dataset/write/seeds.rs | 26 ++--- 4 files changed, 112 insertions(+), 22 deletions(-) diff --git a/docs/src/format/index/scalar/zone_write_seeds.md b/docs/src/format/index/scalar/zone_write_seeds.md index a8531e014e2..71d3dcd632e 100644 --- a/docs/src/format/index/scalar/zone_write_seeds.md +++ b/docs/src/format/index/scalar/zone_write_seeds.md @@ -17,6 +17,11 @@ requests. Other columns are seeded only when the table sets controlled by `lance.zone_write_seeds.rows_per_zone` and `lance.zone_write_seeds.store_null_bitmap`. These keys only choose which columns are seeded; the seed version follows `lance.zone_write_seeds.version`. +An index build reads these seeds only when the index uses seeds. An index created +without an explicit `use_seeds` takes the default for the column's type: `false` +for fixed-width types of 8 bytes or less, so reusing the configured seeds for those +columns requires creating the index with `use_seeds=true`, and `true` for +variable-length and wider types. See [Table Config](../../table/table_config.md) for types, defaults, and supported column types. diff --git a/docs/src/format/table/table_config.md b/docs/src/format/table/table_config.md index 0d6c374f900..b4e8c1cbde1 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -49,9 +49,9 @@ full set of metadata maps. | `lance.compaction.max_source_rows` | Non-negative integer | Maximum number of live source rows (physical rows minus soft-deleted rows) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_source_bytes` | Non-negative integer | Maximum number of source bytes (data files and [data overlay files](data_overlay_file.md), excluding blob v2 payloads) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_overlays_per_fragment` | Non-negative integer or `none` | Maximum number of [data overlay files](data_overlay_file.md) a fragment may carry before it is fully compacted (overlays and deletions materialized into the base data). Defaults to `10`. Set to `0` to compact every fragment with any overlay, or `none` to disable the trigger. | -| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and binary (variable-length or fixed-size); nested, vector, dictionary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. Defaults to `false`. | +| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and binary (variable-length or fixed-size); nested, vector, dictionary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. An index build reads these seeds only when the index uses seeds; an index created without an explicit `use_seeds` takes the default for the column's type, which is `false` for fixed-width types of 8 bytes or less (so those columns need `use_seeds=true` to reuse the seeds) and `true` for variable-length and wider types. Defaults to `false`. | | `lance.zone_write_seeds.rows_per_zone` | Integer (1 to 4,294,967,295) | Rows per seed zone for the columns seeded because of `lance.zone_write_seeds.enabled`. Defaults to `8192`. | -| `lance.zone_write_seeds.store_null_bitmap` | Boolean (`true`/`false`) | Whether the seeds collected because of `lance.zone_write_seeds.enabled` record null positions, so they can serve a ZoneMap index that stores a null bitmap. With `false`, those seeds only serve indexes that store no null bitmap. Defaults to `true`. | +| `lance.zone_write_seeds.store_null_bitmap` | Boolean (`true`/`false`) | Whether the seeds collected because of `lance.zone_write_seeds.enabled` record null positions, so they can serve a ZoneMap index that stores a null bitmap. With `false`, those seeds only serve indices that store no null bitmap. Defaults to `true`. | | `lance.zone_write_seeds.version` | `0` or `1` | [Zone write seed](../index/scalar/zone_write_seeds.md) format version. A commit that itself writes `1` sets `FLAG_ZONE_WRITE_SEEDS` in both feature flag words; an inherited `1` does not. Once set, the flag stays set and writers emit version 1 seeds unless this key is explicitly `0`. Without the flag, writers emit version 0 seeds. Unset by default. | diff --git a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs index 8a93557c5a4..3833c4be8dd 100644 --- a/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs +++ b/rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs @@ -4064,15 +4064,15 @@ async fn assert_boundary_predicates( } } -/// Configured seeds at production zone sizes serve a ZoneMap index over one -/// appended fragment whose length no zone size divides. Seed records are -/// `seed_rows_per_zone` rows from the fragment start with a short final -/// record; with seed records no larger than index zones, a record is reused -/// when it lies inside one index zone and scanned when it straddles an index -/// zone boundary. +/// Configured seeds serve a ZoneMap index over one appended fragment whose +/// length no zone size divides, written in batches no zone size aligns with. +/// Seed records are `seed_rows_per_zone` rows from the fragment start with a +/// short final record; with seed records no larger than index zones, a record +/// is reused when it lies inside one index zone and scanned when it straddles +/// an index zone boundary. #[rstest::rstest] -#[case::small_seed_crosses_index_boundary(8192, 1_000_000, 1_050_000, 100_003)] -#[case::equal_sizes_short_final_zone(1_000_000, 1_000_000, 1_050_000, 100_003)] +#[case::small_seed_crosses_index_boundary(8, 1_004, 1_050, 101)] +#[case::equal_sizes_short_final_zone(1_000, 1_000, 1_050, 101)] #[case::equal_small_sizes(8192, 8192, 20_000, 4_099)] #[tokio::test] async fn test_config_seed_boundary_real_sizes( @@ -4201,6 +4201,89 @@ async fn test_config_seed_boundary_real_sizes( .await; } +/// Pins the type-based `use_seeds` default: an Int64 ZoneMap index created +/// without `use_seeds` reads no configured seeds, one with `use_seeds=true` +/// reuses them. A change to that default shows up here. +#[tokio::test] +async fn test_config_seed_reuse_needs_use_seeds_for_narrow_types() { + use crate::index::scalar::zonemap::{SEED_REUSE_REPORTS, SeedReuseReport}; + + const SEED_ROWS_PER_ZONE: u64 = 8; + const INDEX_ROWS_PER_ZONE: u64 = 32; + const APPENDED_ROWS: i64 = 64; + + let dir = TempStrDir::default(); + let mut dataset = Dataset::write( + RecordBatchIterator::new( + [Ok(boundary_rows(0..BOUNDARY_CREATE_ROWS))], + boundary_schema(), + ), + dir.as_str(), + None, + ) + .await + .unwrap(); + enable_zone_write_seeds(&mut dataset, SEED_ROWS_PER_ZONE).await; + append_boundary_fragment( + &mut dataset, + BOUNDARY_CREATE_ROWS..BOUNDARY_CREATE_ROWS + APPENDED_ROWS, + APPENDED_ROWS, + ) + .await; + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), 2); + let appended = fragments[1].id; + assert_eq!( + seed_locator_rows_per_zone(&dataset, &fragments[1], "val").await, + Some(SEED_ROWS_PER_ZONE) + ); + + async fn build(dataset: &mut Dataset, params: serde_json::Value) -> SeedReuseReport { + let params = ScalarIndexParams::for_builtin(BuiltinIndexType::ZoneMap).with_params(¶ms); + let reports = SEED_REUSE_REPORTS + .scope(std::sync::Mutex::new(Vec::new()), async { + dataset + .create_index(&["val"], IndexType::ZoneMap, None, ¶ms, true) + .await + .unwrap(); + SEED_REUSE_REPORTS.with(|reports| reports.lock().unwrap().clone()) + }) + .await; + assert_eq!(reports.len(), 1, "{reports:?}"); + reports.into_iter().next().unwrap() + } + + let default = build( + &mut dataset, + serde_json::json!({ "rows_per_zone": INDEX_ROWS_PER_ZONE }), + ) + .await; + assert_eq!(default.reused_records, 0, "{default:?}"); + assert!(default.reused_fragments.is_empty(), "{default:?}"); + assert_eq!(default.total_seed_bytes, 0, "{default:?}"); + assert_eq!( + default.scanned_rows, + (BOUNDARY_CREATE_ROWS + APPENDED_ROWS) as u64, + "{default:?}" + ); + + let seeded = build( + &mut dataset, + serde_json::json!({ "rows_per_zone": INDEX_ROWS_PER_ZONE, "use_seeds": true }), + ) + .await; + assert_eq!(seeded.reused_fragments, vec![appended], "{seeded:?}"); + assert_eq!( + seeded.reused_records, + (APPENDED_ROWS as u64 / SEED_ROWS_PER_ZONE) as usize, + "{seeded:?}" + ); + assert_eq!( + seeded.scanned_rows, BOUNDARY_CREATE_ROWS as u64, + "{seeded:?}" + ); +} + /// One stored or expected zone of the ZoneMap index on `col`; `min` and `max` /// are one-element arrays of the column's type. #[derive(Debug)] diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index fb7c50770ac..624bc4da210 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -12,14 +12,16 @@ //! ZoneMap index covers, so a ZoneMap index created later can be built //! from seeds instead of scanning. Nested, vector, dictionary, //! extension and blob columns are never seeded by the config. Absent -//! or `"false"` disables this. +//! or `"false"` disables this. An index build reads these seeds only when +//! the index uses seeds; without an explicit `use_seeds`, that defaults to +//! `false` for fixed-width types of 8 bytes or less and `true` otherwise. //! - `lance.zone_write_seeds.rows_per_zone`: rows per seed zone for those //! columns, an integer in `1..=u32::MAX`. Absent, it is //! [`ROWS_PER_ZONE_DEFAULT`](lance_table::format::index_seed::ROWS_PER_ZONE_DEFAULT). //! - `lance.zone_write_seeds.store_null_bitmap`: whether those seeds record //! null positions, so they can serve a ZoneMap index with //! `store_null_bitmap = true` (the index default). Absent or `"true"`, -//! they do; `"false"` records none, and the seeds then only serve indexes +//! they do; `"false"` records none, and the seeds then only serve indices //! that store no null bitmap. //! //! Setting any of these keys to an invalid value is rejected by the commit @@ -127,24 +129,24 @@ impl WriteSeedHook for LanceWriteSeedHook { } Ok(zone_maps .into_iter() - .filter_map(|(field_id, indexes)| { - seeded_rows_per_zone(indexes).map(|rows_per_zone| (field_id, rows_per_zone)) + .filter_map(|(field_id, indices)| { + seeded_rows_per_zone(indices).map(|rows_per_zone| (field_id, rows_per_zone)) }) .collect()) } } -/// The seed zone size of one column, given each of its ZoneMap indexes as +/// The seed zone size of one column, given each of its ZoneMap indices as /// `(use_seeds, rows_per_zone)`. /// -/// Only seeded indexes decide a column's seed zone size: an unseeded index +/// Only seeded indices decide a column's seed zone size: an unseeded index /// never reads seeds, so its zone size must not shape them. Several seeded -/// indexes share one seed of the finest size, which serves every coarser +/// indices share one seed of the finest size, which serves every coarser /// index through whole-record reuse, as the write path chooses it. An index /// without `rows_per_zone` contributes nothing. `None` means no seeded index /// decides the size, so the configured size applies. -fn seeded_rows_per_zone(indexes: impl IntoIterator)>) -> Option { - indexes +fn seeded_rows_per_zone(indices: impl IntoIterator)>) -> Option { + indices .into_iter() .filter(|(use_seeds, _)| *use_seeds) .filter_map(|(_, rows_per_zone)| rows_per_zone) @@ -444,16 +446,16 @@ mod tests { } #[rstest::rstest] - #[case::no_indexes(vec![], None)] + #[case::no_indices(vec![], None)] #[case::only_unseeded(vec![(false, Some(8))], None)] #[case::two_seeded(vec![(true, Some(8)), (true, Some(16))], Some(8))] #[case::seeded_and_unseeded_finer(vec![(true, Some(16)), (false, Some(8))], Some(16))] #[case::seeded_without_size(vec![(true, None)], None)] fn test_seeded_rows_per_zone( - #[case] indexes: Vec<(bool, Option)>, + #[case] indices: Vec<(bool, Option)>, #[case] expected: Option, ) { - assert_eq!(seeded_rows_per_zone(indexes), expected); + assert_eq!(seeded_rows_per_zone(indices), expected); } #[test] From 668137655bb007ad739bacf601189859ff95212a Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Wed, 2 Dec 2026 13:40:37 -0800 Subject: [PATCH 22/23] fix: validate zone write seed settings on the same condition in both commit paths Both paths now validate every setting under the prefix when a commit changes any of them, so rewriting an inherited value unchanged is not blocked by a value that was already invalid. Also correct the spec on which feature flags the keys set and list the writes that collect no seed. Co-Authored-By: Claude --- .../format/index/scalar/zone_write_seeds.md | 15 +++- docs/src/format/table/table_config.md | 6 +- rust/lance-table/src/feature_flags.rs | 17 +++- .../src/transaction/action/apply.rs | 15 +--- .../src/transaction/action/config_update.rs | 27 +++++++ .../src/transaction/manifest_build.rs | 78 +++++++++++++------ 6 files changed, 115 insertions(+), 43 deletions(-) diff --git a/docs/src/format/index/scalar/zone_write_seeds.md b/docs/src/format/index/scalar/zone_write_seeds.md index 71d3dcd632e..cd0c258784b 100644 --- a/docs/src/format/index/scalar/zone_write_seeds.md +++ b/docs/src/format/index/scalar/zone_write_seeds.md @@ -6,8 +6,10 @@ divided into zones, normally 8,192 rows each, with one statistics record per zon The table layer can use these statistics for zone pruning, aggregate them for fragment or index segment pruning, or build an index without rereading the column. -This proposal defines version 1 seeds. It does not change the ZoneMap index format -or enable version 1 writes; implementation follows separately. +This proposal defines version 1 seeds. It does not change the ZoneMap index format. +Writers emit version 1 seeds once a table opts in through +`lance.zone_write_seeds.version` (see +[Reader and writer compatibility](#reader-and-writer-compatibility)). ## Table configuration @@ -17,6 +19,9 @@ requests. Other columns are seeded only when the table sets controlled by `lance.zone_write_seeds.rows_per_zone` and `lance.zone_write_seeds.store_null_bitmap`. These keys only choose which columns are seeded; the seed version follows `lance.zone_write_seeds.version`. +No seed is collected by the write that creates the dataset, by an overwrite, +for data files in the legacy file format, or for a column whose seed another +index type provides. An index build reads these seeds only when the index uses seeds. An index created without an explicit `use_seeds` takes the default for the column's type: `false` for fixed-width types of 8 bytes or less, so reusing the configured seeds for those @@ -117,4 +122,8 @@ Activation is explicit, not triggered by opening a table. Both bits remain set in derived snapshots, including clone and restore, even after dropping an index. Historical snapshots are unchanged; version 0 and version 1 seeds may coexist. -The bit remains reserved and unsupported until runtime support is implemented. +A commit that explicitly writes `lance.zone_write_seeds.version = 1` sets +`FLAG_ZONE_WRITE_SEEDS` in both `reader_feature_flags` and +`writer_feature_flags`; an inherited `1` does not. Once set, the flag stays set +and writers emit version 1 seeds unless the key is explicitly `0`. Without the +flag, writers emit version 0 seeds. diff --git a/docs/src/format/table/table_config.md b/docs/src/format/table/table_config.md index b4e8c1cbde1..d4fe7e46ad6 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -62,7 +62,11 @@ Zone write seeds are optional metadata, so an implementation that does not write seeds only needs to preserve the `lance.zone_write_seeds.*` keys. `enabled`, `rows_per_zone`, and `store_null_bitmap` only affect which seeds a writer collects; they never change what readers must understand and never set -a feature flag. The seed format a writer emits and +`FLAG_ZONE_WRITE_SEEDS`. Like any table configuration, they are covered by the +[`FLAG_TABLE_CONFIG`](versioning.md#current-feature-flags) writer flag that a +non-empty table config sets. No seed is collected by the write that creates +the dataset, by an overwrite, for data files in the legacy file format, or for +a column whose seed another index type provides. The seed format a writer emits and [`FLAG_ZONE_WRITE_SEEDS`](versioning.md#current-feature-flags) are governed by `lance.zone_write_seeds.version` alone. Setting a known key to an invalid value is rejected by the commit that sets it; unknown keys under the diff --git a/rust/lance-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index 9e4ccbf5b95..70cfb51fd62 100644 --- a/rust/lance-table/src/feature_flags.rs +++ b/rust/lance-table/src/feature_flags.rs @@ -3,7 +3,7 @@ //! Feature flags -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use crate::format::index_seed::ROWS_PER_ZONE_DEFAULT; use crate::format::{IndexMetadata, Manifest}; @@ -364,6 +364,21 @@ pub const ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY: &str = "lance.zone_write_seeds.row /// absent means `"true"`). pub const ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY: &str = "lance.zone_write_seeds.store_null_bitmap"; +/// The settings in `config` whose keys start with `prefix`. A commit validates +/// every setting under a prefix whenever it changes any of them; a commit that +/// leaves them as they were (including rewriting an inherited value unchanged) +/// is not blocked by a value that was already invalid. +pub(crate) fn settings_with_prefix<'a>( + config: &'a HashMap, + prefix: &str, +) -> BTreeMap<&'a str, &'a str> { + config + .iter() + .filter(|(key, _)| key.starts_with(prefix)) + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect() +} + /// Validate a change to the zone write seed configuration. /// /// `lance.zone_write_seeds.enabled` and diff --git a/rust/lance-table/src/transaction/action/apply.rs b/rust/lance-table/src/transaction/action/apply.rs index 96918e25c74..a71bad2a62b 100644 --- a/rust/lance-table/src/transaction/action/apply.rs +++ b/rust/lance-table/src/transaction/action/apply.rs @@ -27,7 +27,7 @@ use super::{CompositeOperation, FieldId, FieldRef, Ref}; use crate::feature_flags::{ FLAG_MANAGED_BLOBS, ZONE_WRITE_SEEDS_CONFIG_PREFIX, apply_index_object_metadata_flag, apply_zone_write_seeds_version_config, inherit_sticky_feature_flags, managed_blobs_enabled, - validate_auto_cleanup_config, validate_written_auto_cleanup_interval, + settings_with_prefix, validate_auto_cleanup_config, validate_written_auto_cleanup_interval, validate_zone_write_seeds_config, }; use crate::format::overlay::staleness::field_affects_index; @@ -48,7 +48,7 @@ use crate::transaction::{FragReuseUpdate, LogicalIndexSegments, ReadVersionState use lance_core::datatypes::{Field, Schema}; use lance_core::{Error, Result, is_system_column}; use roaring::RoaringTreemap; -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use uuid::Uuid; @@ -1460,17 +1460,6 @@ fn check_schema(schema: &Schema) -> Result<()> { const AUTO_CLEANUP_CONFIG_PREFIX: &str = "lance.auto_cleanup."; -fn settings_with_prefix<'a>( - config: &'a HashMap, - prefix: &str, -) -> BTreeMap<&'a str, &'a str> { - config - .iter() - .filter(|(key, _)| key.starts_with(prefix)) - .map(|(key, value)| (key.as_str(), value.as_str())) - .collect() -} - /// Refuse an index action naming the fragment reuse history. The history is /// not an index on the action path -- its own actions append to and trim it, /// merged onto the current history at every attempt -- so an index action diff --git a/rust/lance-table/src/transaction/action/config_update.rs b/rust/lance-table/src/transaction/action/config_update.rs index 5310c8ca689..43003f03672 100644 --- a/rust/lance-table/src/transaction/action/config_update.rs +++ b/rust/lance-table/src/transaction/action/config_update.rs @@ -682,6 +682,33 @@ mod tests { apply(&manifest, vec![set_config(&[("unrelated", Some("1"))])]).unwrap(); } + #[test] + fn test_zone_write_seeds_settings_rewritten_unchanged_do_not_block_the_commit() { + let mut manifest = backed_manifest(); + manifest + .config + .insert(ZONE_WRITE_SEEDS_ENABLED_KEY.into(), "yes".into()); + + apply( + &manifest, + vec![set_config(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, Some("yes"))])], + ) + .unwrap(); + + let error = apply( + &manifest, + vec![set_config(&[( + ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + Some("8"), + )])], + ) + .unwrap_err(); + assert!( + error.to_string().contains(ZONE_WRITE_SEEDS_ENABLED_KEY), + "unexpected error: {error}" + ); + } + #[test] fn test_config_update_validates_explicit_auto_cleanup_interval() { let mut manifest = backed_manifest(); diff --git a/rust/lance-table/src/transaction/manifest_build.rs b/rust/lance-table/src/transaction/manifest_build.rs index 9043a01fa3f..c4a524b652f 100644 --- a/rust/lance-table/src/transaction/manifest_build.rs +++ b/rust/lance-table/src/transaction/manifest_build.rs @@ -16,9 +16,9 @@ use crate::feature_flags::{ FLAG_STABLE_ROW_IDS, ZONE_WRITE_SEEDS_CONFIG_PREFIX, ZONE_WRITE_SEEDS_VERSION_KEY, apply_feature_flags, apply_index_object_metadata_flag, apply_row_addr_index_feature_flag, apply_zone_write_seeds_version_config, ensure_can_read_manifest, ensure_can_write_manifest, - inherit_sticky_feature_flags, managed_blobs_enabled, validate_auto_cleanup_config, - validate_non_reusable_field_id_flags, validate_written_auto_cleanup_interval, - validate_zone_write_seeds_config, + inherit_sticky_feature_flags, managed_blobs_enabled, settings_with_prefix, + validate_auto_cleanup_config, validate_non_reusable_field_id_flags, + validate_written_auto_cleanup_interval, validate_zone_write_seeds_config, }; use crate::format::clustering::{ChangedReferences, validate_clustering_of}; @@ -146,27 +146,6 @@ fn changes_auto_cleanup_config(operation: &Operation) -> bool { } } -fn changes_zone_write_seeds_config(operation: &Operation) -> bool { - let is_zone_write_seeds_key = |key: &str| key.starts_with(ZONE_WRITE_SEEDS_CONFIG_PREFIX); - match operation { - Operation::Overwrite { - config_upsert_values: Some(values), - .. - } => values.keys().any(|key| is_zone_write_seeds_key(key)), - Operation::UpdateConfig { - config_updates: Some(update), - .. - } => { - update.replace - || update - .update_entries - .iter() - .any(|entry| is_zone_write_seeds_key(&entry.key)) - } - _ => false, - } -} - fn writes_zone_write_seeds_version_config(operation: &Operation) -> bool { match operation { Operation::Overwrite { @@ -2157,7 +2136,12 @@ impl Transaction { if changes_auto_cleanup_config(&self.operation) { validate_auto_cleanup_config(&manifest)?; } - if changes_zone_write_seeds_config(&self.operation) { + let previous_zone_write_seeds = current_manifest + .map(|m| settings_with_prefix(&m.config, ZONE_WRITE_SEEDS_CONFIG_PREFIX)) + .unwrap_or_default(); + if previous_zone_write_seeds + != settings_with_prefix(&manifest.config, ZONE_WRITE_SEEDS_CONFIG_PREFIX) + { validate_zone_write_seeds_config(&manifest)?; } validate_written_auto_cleanup_interval(&manifest, auto_cleanup_interval_written)?; @@ -4373,6 +4357,50 @@ mod tests { .unwrap(); } + #[test] + fn zone_write_seeds_settings_rewritten_unchanged_do_not_block_the_commit() { + let mut manifest = sample_manifest(); + manifest.config.insert( + crate::feature_flags::ZONE_WRITE_SEEDS_ENABLED_KEY.into(), + "yes".into(), + ); + let make_update = |key: &str, value: &str| { + Transaction::new( + manifest.version, + Operation::UpdateConfig { + config_updates: Some(crate::transaction::UpdateMap { + update_entries: vec![crate::transaction::update_map::UpdateMapEntry { + key: key.into(), + value: Some(value.into()), + }], + replace: false, + }), + table_metadata_updates: None, + schema_metadata_updates: None, + field_metadata_updates: HashMap::new(), + }, + None, + ) + }; + + make_update(crate::feature_flags::ZONE_WRITE_SEEDS_ENABLED_KEY, "yes") + .build_manifest(Some(&manifest), vec![], "txn", &default_build_config()) + .unwrap(); + + let error = make_update( + crate::feature_flags::ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + "8", + ) + .build_manifest(Some(&manifest), vec![], "txn", &default_build_config()) + .unwrap_err(); + assert!( + error + .to_string() + .contains(crate::feature_flags::ZONE_WRITE_SEEDS_ENABLED_KEY), + "{error}" + ); + } + #[test] fn zone_write_seeds_enabled_config_does_not_activate_flag() { let manifest = sample_manifest(); From a61778b7f194320f31d9b046eadeb5869846193b Mon Sep 17 00:00:00 2001 From: Lu Qiu Date: Wed, 2 Dec 2026 16:01:39 -0800 Subject: [PATCH 23/23] docs: leave seeded column types to the writer and state config rules as requirements Drop the type list from the lance.zone_write_seeds.enabled row, phrase the paragraph under the table as rules for implementations, and move the cases where no seed is collected to the zone write seed page as writer latitude. Also re-export ZONE_WRITE_SEEDS_VERSION_KEY next to the other three keys. --- .../format/index/scalar/zone_write_seeds.md | 10 ++++---- docs/src/format/table/table_config.md | 25 +++++++++---------- rust/lance/src/dataset/write.rs | 1 + 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/src/format/index/scalar/zone_write_seeds.md b/docs/src/format/index/scalar/zone_write_seeds.md index cd0c258784b..d1832735f5a 100644 --- a/docs/src/format/index/scalar/zone_write_seeds.md +++ b/docs/src/format/index/scalar/zone_write_seeds.md @@ -19,16 +19,16 @@ requests. Other columns are seeded only when the table sets controlled by `lance.zone_write_seeds.rows_per_zone` and `lance.zone_write_seeds.store_null_bitmap`. These keys only choose which columns are seeded; the seed version follows `lance.zone_write_seeds.version`. -No seed is collected by the write that creates the dataset, by an overwrite, -for data files in the legacy file format, or for a column whose seed another -index type provides. +Which column types are seeded is up to the writer. A writer may also skip +configured seeds in the write that creates the dataset, in an overwrite, for data +files in the legacy file format, or for a column whose seed another index type +provides. An index build reads these seeds only when the index uses seeds. An index created without an explicit `use_seeds` takes the default for the column's type: `false` for fixed-width types of 8 bytes or less, so reusing the configured seeds for those columns requires creating the index with `use_seeds=true`, and `true` for variable-length and wider types. -See [Table Config](../../table/table_config.md) for types, defaults, and -supported column types. +See [Table Config](../../table/table_config.md) for types and defaults. ## Arrow Rust ordering diff --git a/docs/src/format/table/table_config.md b/docs/src/format/table/table_config.md index d4fe7e46ad6..014de1c29af 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -49,7 +49,7 @@ full set of metadata maps. | `lance.compaction.max_source_rows` | Non-negative integer | Maximum number of live source rows (physical rows minus soft-deleted rows) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_source_bytes` | Non-negative integer | Maximum number of source bytes (data files and [data overlay files](data_overlay_file.md), excluding blob v2 payloads) to compact in a single run. Defaults to unlimited. | | `lance.compaction.max_overlays_per_fragment` | Non-negative integer or `none` | Maximum number of [data overlay files](data_overlay_file.md) a fragment may carry before it is fully compacted (overlays and deletions materialized into the base data). Defaults to `10`. Set to `0` to compact every fragment with any overlay, or `none` to disable the trigger. | -| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writes collect a [zone write seed](../index/scalar/zone_write_seeds.md) for every top-level column of a supported scalar type that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Supported types are boolean, integer, floating-point, date, time, timestamp, duration, decimal, string, and binary (variable-length or fixed-size); nested, vector, dictionary, extension-typed, and blob columns are never seeded by this key. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. An index build reads these seeds only when the index uses seeds; an index created without an explicit `use_seeds` takes the default for the column's type, which is `false` for fixed-width types of 8 bytes or less (so those columns need `use_seeds=true` to reuse the seeds) and `true` for variable-length and wider types. Defaults to `false`. | +| `lance.zone_write_seeds.enabled` | Boolean (`true`/`false`) | If `true`, writers should collect a [zone write seed](../index/scalar/zone_write_seeds.md) for top-level scalar columns that no seeded index already covers, so a ZoneMap index created later can be built from seeds instead of rescanning. Which column types get seeds is up to the writer. Columns covered by a ZoneMap index with `use_seeds=true` keep that index's settings. An index build reads these seeds only when the index uses seeds. Defaults to `false`. | | `lance.zone_write_seeds.rows_per_zone` | Integer (1 to 4,294,967,295) | Rows per seed zone for the columns seeded because of `lance.zone_write_seeds.enabled`. Defaults to `8192`. | | `lance.zone_write_seeds.store_null_bitmap` | Boolean (`true`/`false`) | Whether the seeds collected because of `lance.zone_write_seeds.enabled` record null positions, so they can serve a ZoneMap index that stores a null bitmap. With `false`, those seeds only serve indices that store no null bitmap. Defaults to `true`. | | `lance.zone_write_seeds.version` | `0` or `1` | [Zone write seed](../index/scalar/zone_write_seeds.md) format version. A commit that itself writes `1` sets `FLAG_ZONE_WRITE_SEEDS` in both feature flag words; an inherited `1` does not. Once set, the flag stays set and writers emit version 1 seeds unless this key is explicitly `0`. Without the flag, writers emit version 0 seeds. Unset by default. | @@ -58,16 +58,15 @@ full set of metadata maps. Unrecognized `lance.compaction.*` keys are ignored with a warning; unrecognized keys under other `lance.*` prefixes should likewise be ignored by conforming readers rather than treated as errors. -Zone write seeds are optional metadata, so an implementation that does not -write seeds only needs to preserve the `lance.zone_write_seeds.*` keys. -`enabled`, `rows_per_zone`, and `store_null_bitmap` only affect which seeds a -writer collects; they never change what readers must understand and never set -`FLAG_ZONE_WRITE_SEEDS`. Like any table configuration, they are covered by the +Zone write seeds are optional metadata. An implementation that does not write +seeds must preserve every `lance.zone_write_seeds.*` key. `enabled`, +`rows_per_zone`, and `store_null_bitmap` only choose which seeds a writer +collects: they must not change what readers need to understand, and must not +set [`FLAG_ZONE_WRITE_SEEDS`](versioning.md#current-feature-flags). Like any +table configuration, they are covered by the [`FLAG_TABLE_CONFIG`](versioning.md#current-feature-flags) writer flag that a -non-empty table config sets. No seed is collected by the write that creates -the dataset, by an overwrite, for data files in the legacy file format, or for -a column whose seed another index type provides. The seed format a writer emits and -[`FLAG_ZONE_WRITE_SEEDS`](versioning.md#current-feature-flags) are governed by -`lance.zone_write_seeds.version` alone. Setting a known key to an invalid -value is rejected by the commit that sets it; unknown keys under the -`lance.zone_write_seeds.` prefix are preserved and not rejected. +non-empty table config sets. The seed version a writer emits, and whether +`FLAG_ZONE_WRITE_SEEDS` is set, must depend only on +`lance.zone_write_seeds.version`. A commit that sets one of these keys to an +invalid value must be rejected. Unknown keys under the +`lance.zone_write_seeds.` prefix must be preserved, not rejected. diff --git a/rust/lance/src/dataset/write.rs b/rust/lance/src/dataset/write.rs index 75b96c5e23f..61f81bc8964 100644 --- a/rust/lance/src/dataset/write.rs +++ b/rust/lance/src/dataset/write.rs @@ -43,6 +43,7 @@ pub use super::progress::{WriteProgressFn, WriteStats}; pub use commit::{CommitBuilder, DEFAULT_COMMIT_TIMEOUT}; pub use delete::{DeleteBuilder, DeleteResult, UncommittedDelete}; pub use insert::InsertBuilder; +pub use lance_table::feature_flags::ZONE_WRITE_SEEDS_VERSION_KEY; pub use lance_table_runtime::write::{ AutoCleanupParams, ExternalBlobMode, GenericWriter, PRIMARY_BASE_ID, TargetBaseInfo, WriteMode, };