diff --git a/docs/src/format/index/scalar/zone_write_seeds.md b/docs/src/format/index/scalar/zone_write_seeds.md index c5232a682ad..d1832735f5a 100644 --- a/docs/src/format/index/scalar/zone_write_seeds.md +++ b/docs/src/format/index/scalar/zone_write_seeds.md @@ -6,8 +6,29 @@ 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 + +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`. +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 and defaults. ## Arrow Rust ordering @@ -101,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 1f541b45140..014de1c29af 100644 --- a/docs/src/format/table/table_config.md +++ b/docs/src/format/table/table_config.md @@ -49,7 +49,24 @@ 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`, 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. | 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. 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. 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-table-runtime/src/optimize/binary_copy.rs b/rust/lance-table-runtime/src/optimize/binary_copy.rs index 9387e09a82c..72f056d564e 100644 --- a/rust/lance-table-runtime/src/optimize/binary_copy.rs +++ b/rust/lance-table-runtime/src/optimize/binary_copy.rs @@ -179,6 +179,12 @@ pub async fn rewrite_files_binary_copy( 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() { @@ -390,7 +396,7 @@ pub async fn rewrite_files_binary_copy( total_rows_in_current += file_meta.num_rows; if total_rows_in_current >= max_rows_per_file { let output_seeds = if carry_v1_seeds { - seed_acc.finish(&schema, &index_rows_per_zone)? + seed_acc.finish(&schema, &index_rows_per_zone, unindexed_rows_per_zone)? } else { seed_acc.clear(); Vec::new() @@ -428,7 +434,7 @@ pub async fn rewrite_files_binary_copy( init_writer_if_necessary(dataset, version, &mut current_writer, &mut current_filename) .await?; let output_seeds = if carry_v1_seeds { - seed_acc.finish(&schema, &index_rows_per_zone)? + seed_acc.finish(&schema, &index_rows_per_zone, unindexed_rows_per_zone)? } else { seed_acc.clear(); Vec::new() diff --git a/rust/lance-table-runtime/src/optimize/binary_copy/seed_carry.rs b/rust/lance-table-runtime/src/optimize/binary_copy/seed_carry.rs index d1116984223..409b4cea1f9 100644 --- a/rust/lance-table-runtime/src/optimize/binary_copy/seed_carry.rs +++ b/rust/lance-table-runtime/src/optimize/binary_copy/seed_carry.rs @@ -21,8 +21,8 @@ use lance_file::versions::data_file_columns; use lance_io::scheduler::FileScheduler; use lance_table::format::DataFile; use lance_table::format::index_seed::{ - CarriedSeed, MergeableSeed, ROWS_PER_ZONE_DEFAULT, SEED_META_KEY_PREFIX, - merge_seeds_for_binary_copy, parse_seed_for_binary_copy, + CarriedSeed, MergeableSeed, SEED_META_KEY_PREFIX, merge_seeds_for_binary_copy, + parse_seed_for_binary_copy, }; use lance_core::{Result, datatypes::Schema}; @@ -38,10 +38,11 @@ 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(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 validated seeds of one input file, keyed by field id. An input with no @@ -212,8 +213,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. @@ -221,6 +222,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 { @@ -295,7 +297,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-table/src/feature_flags.rs b/rust/lance-table/src/feature_flags.rs index 0382bff66c6..70cfb51fd62 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::{BTreeMap, HashMap}; + +use crate::format::index_seed::ROWS_PER_ZONE_DEFAULT; use crate::format::{IndexMetadata, Manifest}; use lance_core::{Error, Result, datatypes::Schema}; @@ -349,6 +352,146 @@ pub(crate) fn validate_written_auto_cleanup_interval( 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"; +/// 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"; + +/// 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 +/// `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. [`ZONE_WRITE_SEEDS_VERSION_KEY`] is checked by +/// [`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) { + continue; + } + match key.as_str() { + ZONE_WRITE_SEEDS_ENABLED_KEY | ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY => { + 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 => { + 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 + ))); + } + } + ZONE_WRITE_SEEDS_VERSION_KEY => validate_zone_write_seeds_version_config(manifest)?, + _ => {} + } + } + 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 { + /// 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 parse_zone_write_seeds_bool(enabled) { + Some(true) => {} + Some(false) => return None, + None => { + log::warn!( + "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) => 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) => parse_zone_write_seeds_bool(value).unwrap_or_else(|| { + log::warn!( + "ignoring {ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY}={value:?}: expected \ + \"true\" or \"false\"; 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 @@ -878,6 +1021,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( @@ -1162,6 +1333,135 @@ 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::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")])] + #[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"), + (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "false"), + (ZONE_WRITE_SEEDS_VERSION_KEY, "1"), + ])] + 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::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")] + #[case::too_large_size(ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, "4294967296")] + #[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) { + 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_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)] + #[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-table/src/transaction/action/apply.rs b/rust/lance-table/src/transaction/action/apply.rs index b7676b5ad77..a71bad2a62b 100644 --- a/rust/lance-table/src/transaction/action/apply.rs +++ b/rust/lance-table/src/transaction/action/apply.rs @@ -25,9 +25,10 @@ use super::{CompositeOperation, FieldId, FieldRef, Ref}; use crate::feature_flags::{ - FLAG_MANAGED_BLOBS, 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, + 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, + 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; use crate::format::{ @@ -47,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; @@ -447,11 +448,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)?; + } validate_written_auto_cleanup_interval(&manifest, auto_cleanup_interval_written)?; // Both read the final schema and config, so they come after those land. apply_range_segments(&mut manifest, Some(current_manifest))?; @@ -1452,13 +1458,7 @@ fn check_schema(schema: &Schema) -> Result<()> { schema.validate() } -fn auto_cleanup_settings(config: &HashMap) -> BTreeMap<&str, &str> { - config - .iter() - .filter(|(key, _)| key.starts_with("lance.auto_cleanup.")) - .map(|(key, value)| (key.as_str(), value.as_str())) - .collect() -} +const AUTO_CLEANUP_CONFIG_PREFIX: &str = "lance.auto_cleanup."; /// 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, diff --git a/rust/lance-table/src/transaction/action/config_update.rs b/rust/lance-table/src/transaction/action/config_update.rs index 62ab1179cc4..43003f03672 100644 --- a/rust/lance-table/src/transaction/action/config_update.rs +++ b/rust/lance-table/src/transaction/action/config_update.rs @@ -285,7 +285,10 @@ impl TryFrom for ConfigUpdate { #[cfg(test)] mod tests { use super::*; - use crate::feature_flags::{FLAG_ZONE_WRITE_SEEDS, ZONE_WRITE_SEEDS_VERSION_KEY}; + use crate::feature_flags::{ + FLAG_ZONE_WRITE_SEEDS, ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + ZONE_WRITE_SEEDS_VERSION_KEY, + }; use crate::format::Manifest; use crate::transaction::action::test_support::{ added_field, apply, backed_manifest, footprint, one_column_file, unbacked_manifest, @@ -628,6 +631,84 @@ 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_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(); @@ -721,6 +802,48 @@ mod tests { assert!(matches!(error, Error::InvalidInput { .. }), "{error:?}"); } + /// Enabling collection alone never activates the version 1 seed flag; + /// only an explicit version write does, and the prefix validation accepts + /// it alongside the collection settings. + #[test] + fn test_zone_write_seeds_enabled_does_not_activate_the_flag() { + let enabled = apply( + &backed_manifest(), + vec![set_config(&[(ZONE_WRITE_SEEDS_ENABLED_KEY, Some("true"))])], + ) + .unwrap(); + assert!(!enabled.has_zone_write_seeds()); + + let with_version = apply( + &backed_manifest(), + vec![set_config(&[ + (ZONE_WRITE_SEEDS_ENABLED_KEY, Some("true")), + (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, Some("16")), + (ZONE_WRITE_SEEDS_VERSION_KEY, Some("1")), + ])], + ) + .unwrap(); + 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 with_unknown_key = apply( + &backed_manifest(), + vec![set_config(&[ + (ZONE_WRITE_SEEDS_ENABLED_KEY, Some("true")), + (ZONE_WRITE_SEEDS_VERSION_KEY, Some("1")), + ("lance.zone_write_seeds.unknown", Some("1")), + ])], + ) + .unwrap(); + assert_eq!( + with_unknown_key + .config + .get("lance.zone_write_seeds.unknown") + .map(String::as_str), + Some("1") + ); + } + #[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 fe9c0ba50da..c4a524b652f 100644 --- a/rust/lance-table/src/transaction/manifest_build.rs +++ b/rust/lance-table/src/transaction/manifest_build.rs @@ -13,11 +13,12 @@ use crate::feature_flags::{ AUTO_CLEANUP_INTERVAL_KEY, FLAG_COVERED_INDEX_METADATA, FLAG_FRAGMENT_REUSE_INDEX, FLAG_INDEPENDENT_COVERING_FIELDS, FLAG_MANAGED_BLOBS, FLAG_NON_REUSABLE_FIELD_IDS, - FLAG_STABLE_ROW_IDS, ZONE_WRITE_SEEDS_VERSION_KEY, apply_feature_flags, - apply_index_object_metadata_flag, apply_row_addr_index_feature_flag, + 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, + 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}; @@ -2135,6 +2136,14 @@ impl Transaction { if changes_auto_cleanup_config(&self.operation) { validate_auto_cleanup_config(&manifest)?; } + 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)?; apply_range_segments(&mut manifest, current_manifest)?; @@ -4318,6 +4327,108 @@ 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(); + } + + #[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(); + let transaction = Transaction::new( + manifest.version, + Operation::UpdateConfig { + config_updates: Some(crate::transaction::UpdateMap { + update_entries: vec![crate::transaction::update_map::UpdateMapEntry { + key: crate::feature_flags::ZONE_WRITE_SEEDS_ENABLED_KEY.into(), + value: Some("true".into()), + }], + replace: false, + }), + table_metadata_updates: None, + schema_metadata_updates: None, + field_metadata_updates: HashMap::new(), + }, + None, + ); + + let (enabled, _) = transaction + .build_manifest(Some(&manifest), vec![], "txn", &default_build_config()) + .unwrap(); + assert!(!enabled.has_zone_write_seeds()); + assert_eq!(enabled.reader_feature_flags & FLAG_ZONE_WRITE_SEEDS, 0); + assert_eq!(enabled.writer_feature_flags & FLAG_ZONE_WRITE_SEEDS, 0); + } + #[test] fn overwrite_rejects_an_invalid_auto_cleanup_interval_upsert() { let manifest = sample_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 5739a2ee98b..3833c4be8dd 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; @@ -44,6 +46,10 @@ 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, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, +}; use crate::dataset::{ CommitBuilder, DATA_DIR, InsertBuilder, MergeInsertBuilder, MergeInsertWriteMode, UpdateBuilder, WriteDestination, WriteMode, WriteParams, @@ -2705,3 +2711,1843 @@ 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. Enabling +// collection never sets `FLAG_ZONE_WRITE_SEEDS`: the seeds are version 0 +// unless the table opted into version 1 through +// `lance.zone_write_seeds.version`. + +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 seed of `column` in the data file of `fragment` that serves it. +async fn config_seed(dataset: &Dataset, fragment: &Fragment, column: &str) -> Bytes { + let file = serving_file(fragment, field_id(dataset, column)); + seed_in_file(dataset, &file.path, column) + .await + .unwrap_or_else(|| panic!("no seed for column {column}")) +} + +/// Whether a zone map seed records the null positions of its rows. +fn seed_has_null_positions(bytes: &Bytes) -> bool { + let reader = + arrow_ipc::reader::FileReader::try_new(std::io::Cursor::new(bytes.as_ref()), None).unwrap(); + reader + .schema() + .metadata + .contains_key(lance_table::format::index_seed::ZONEMAP_SEED_NULL_BITMAP_META_KEY) +} + +/// The next append after enabling the setting seeds every column at the +/// configured size; earlier files stay unseeded. Enabling alone sets no seed +/// flag and the seeds are version 0; the same update that also writes +/// `version = "1"` sets the flag and the seeds are version 1. +#[rstest::rstest] +#[case::v0(false)] +#[case::v1(true)] +#[tokio::test] +async fn test_config_seeds_columns_without_index(#[case] v1: bool) { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + assert!(!seed_flags_set(&dataset)); + let rows_per_zone = ROWS_PER_ZONE.to_string(); + let mut settings = vec![ + (ZONE_WRITE_SEEDS_ENABLED_KEY, "true"), + (ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, rows_per_zone.as_str()), + (ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, "true"), + ]; + if v1 { + settings.push((ZONE_WRITE_SEEDS_VERSION_KEY, "1")); + } + dataset.update_config(settings).await.unwrap(); + assert_eq!(seed_flags_set(&dataset), v1); + + append_config_rows(&mut dataset, 10..20).await; + assert_eq!(seed_flags_set(&dataset), v1); + 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}" + ); + assert_eq!( + seed_is_v1(&config_seed(&dataset, &fragments[1], column).await), + v1, + "appended file, column {column}" + ); + } + for column in UNSEEDED_CONFIG_COLUMNS { + 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 +} + +/// Configured seeds follow the table's seed version from append to append: +/// version 0 until the table opts into version 1, version 1 afterwards, and +/// version 0 again once the version is pinned back to `"0"`, while the flag +/// stays set. +#[tokio::test] +async fn test_config_seeds_follow_the_seed_version() { + 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!(!seed_flags_set(&dataset)); + + activate_v1_seeds(&mut dataset).await; + assert_seed_flags_set(&dataset); + append_config_rows(&mut dataset, 20..30).await; + + dataset + .update_config([(ZONE_WRITE_SEEDS_VERSION_KEY, "0")]) + .await + .unwrap(); + append_config_rows(&mut dataset, 30..40).await; + assert_seed_flags_set(&dataset); + + let fragments = dataset.fragments().clone(); + assert_eq!(fragments.len(), 4); + for column in CONFIG_COLUMNS { + for (fragment, expected_v1) in fragments[1..].iter().zip([false, true, false]) { + assert_eq!( + seed_is_v1(&config_seed(&dataset, fragment, column).await), + expected_v1, + "fragment {}, column {column}", + fragment.id + ); + } + } +} + +/// 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; + + // 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, + "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}"); + } +} + +/// 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, + #[values(false, true)] v1: bool, +) { + use crate::index::scalar::zonemap::SEED_REUSE_REPORTS; + + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + if v1 { + activate_v1_seeds(&mut dataset).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; + assert_eq!(seed_flags_set(&dataset), v1); + let appended_fragment = dataset.fragments()[1].clone(); + let appended = appended_fragment.id; + // Null positions follow the setting at either seed version. + let seed = config_seed(&dataset, &appended_fragment, "val").await; + assert_eq!(seed_is_v1(&seed), v1); + assert_eq!( + seed_has_null_positions(&seed), + seeds_store_null_bitmap != Some("false") + ); + + 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. +#[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 carries version 1 configured seeds and declares +/// the configured zone size for columns without a seeded index, as the write +/// path does. Version 0 configured seeds are dropped and the compaction sets +/// no seed flag. +#[rstest::rstest] +#[case::v0(false)] +#[case::v1(true)] +#[tokio::test] +async fn test_binary_copy_declares_configured_rows_per_zone(#[case] v1: bool) { + let dir = TempStrDir::default(); + let mut dataset = dataset_with_config_rows(dir.as_str()).await; + if v1 { + activate_v1_seeds(&mut dataset).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); + assert_eq!(seed_flags_set(&dataset), v1); + 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, + v1.then_some(ROWS_PER_ZONE), + "column {column}" + ); + } +} + +/// 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] +#[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")] +#[case::version(ZONE_WRITE_SEEDS_VERSION_KEY, "2")] +#[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 seeds already +/// written stay and no seed flag is set; 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. +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, 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); + 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::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(), + ), + 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}"), + } +} + +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. Runs with version 1 +/// seeds: a version 0 record of a float zone holding NaN is scanned instead. +#[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, &["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), + &["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_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(); + activate_v1_seeds(&mut dataset).await; + 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 version 1 configured seeds were +/// written at 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; + activate_v1_seeds(&mut dataset).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}" + ); + } + + 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"], + "binary copy", + ) + .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(), + ), + Some(WriteParams { + mode: WriteMode::Append, + max_rows_per_file: (positions.end - positions.start) as usize, + ..Default::default() + }), + ) + .await + .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) -> BoundaryRows { + 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: BoundaryRows = 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); + // A partly reused fragment is listed as both partial and scanned. + assert_eq!( + 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:?}" + ); + + // `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_eq!(report.scanned_rows, 11, "{context}: {report:?}"); + } else if seed_rows_per_zone < index_rows_per_zone { + // 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), + "{context}: expectation only derived for this shape" + ); + assert!(reused.is_empty(), "{context}: {report:?}"); + assert_eq!(partial, appended, "{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 { + // 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; + 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; + + 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 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, 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, + 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(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.fragment_id, zone.zone_start)); + + 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(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.fragment_id, zone.zone_start)); + + 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:?}" + ); + } +} + +/// 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 + .iter() + .filter(|(_, v)| keep(*v)) + .copied() + .collect() + }; + + let zone_value = zone_boundary * 3; + let mut cases: Vec<(String, BoundaryRows)> = 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}"); + } +} + +/// 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(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( + #[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(); + 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, + "{context}: {report:?}" + ); + assert_eq!( + report.scanned_rows, expected_scanned_rows as u64, + "{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; + + assert_boundary_zone_statistics( + &dataset, + index_rows_per_zone, + &[ + (creating, 0..BOUNDARY_CREATE_ROWS), + (appended, first_appended..first_appended + rows_per_fragment), + ], + &context, + ) + .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)] +struct TypedZone { + fragment_id: u64, + zone_start: u64, + zone_length: u64, + null_count: u32, + nan_count: u32, + min: ArrayRef, + 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 +/// zone statistics equal those computed from the generated arrays, and +/// indexed filters match a scan. Runs with version 1 seeds, whose float +/// records with NaN stay reusable. +#[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, &["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), + &["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"])] +#[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, + #[case] filters: &'static [&'static str], + #[values(false, true)] index_store_null_bitmap: bool, +) { + use arrow::array::{AsArray, BooleanArray, new_null_array}; + use arrow::datatypes::{Float32Type, 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; + activate_v1_seeds(&mut dataset).await; + 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 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(); + 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; +} diff --git a/rust/lance/src/dataset/write.rs b/rust/lance/src/dataset/write.rs index 8384effb09d..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, }; @@ -50,6 +51,10 @@ pub(crate) use lance_table_runtime::write::{ cleanup_data_fragments, dictionary_budget, promote_legacy_blob_schema, validate_and_resolve_target_bases_with_primary, }; +pub use seeds::{ + ZONE_WRITE_SEEDS_ENABLED_KEY, ZONE_WRITE_SEEDS_ROWS_PER_ZONE_KEY, + ZONE_WRITE_SEEDS_STORE_NULL_BITMAP_KEY, +}; /// Dataset write parameters with a Lance session. pub type WriteParams = lance_table_runtime::write::WriteParamsWithSession; diff --git a/rust/lance/src/dataset/write/seeds.rs b/rust/lance/src/dataset/write/seeds.rs index 38ebe4538de..624bc4da210 100644 --- a/rust/lance/src/dataset/write/seeds.rs +++ b/rust/lance/src/dataset/write/seeds.rs @@ -1,17 +1,59 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The Lance Authors +//! Write seed selection for Lance datasets. +//! +//! Columns with a seeded index get the seeds that index asks for. Columns +//! without one 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 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, +//! extension and blob columns are never seeded by the config. Absent +//! 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 indices +//! that store no null bitmap. +//! +//! 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: +//! enabling collection never sets `FLAG_ZONE_WRITE_SEEDS`, and a table that +//! has not opted into version 1 writes version 0 seeds. +//! +//! A column with a seeded ZoneMap index keeps following that index's +//! `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. + use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use arrow_schema::DataType; use async_trait::async_trait; 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::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, ZoneWriteSeedsConfig, +}; use lance_table::format::IndexMetadata; use lance_table::format::index_seed::IndexSeedWriter; @@ -52,12 +94,13 @@ impl WriteSeedHook for LanceWriteSeedHook { } else { ZoneMapSeedVersion::V0 }; - seed_writers_for(&dataset, &indices, schema, zone_map_seed_version).await + let config = ZoneWriteSeedsConfig::from_config(&table.manifest().config); + seed_writers_for(&dataset, &indices, schema, config, zone_map_seed_version).await } 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() @@ -77,16 +120,39 @@ impl WriteSeedHook for LanceWriteSeedHook { let Ok(details) = fetch_index_details(&dataset, &field.name, index).await else { continue; }; - if let Ok(zone_map) = details.to_msg::() - && let Some(configured) = zone_map.rows_per_zone - { - rows_per_zone.insert(field_id, configured); + if let Ok(zone_map) = details.to_msg::() { + zone_maps + .entry(field_id) + .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, 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 indices as +/// `(use_seeds, rows_per_zone)`. +/// +/// 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 +/// 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(indices: impl IntoIterator)>) -> Option { + indices + .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, @@ -98,7 +164,13 @@ pub async fn collect_write_seeds( } /// The seed writers that the usable indices in `indices` request for the -/// top-level columns of `schema`. +/// top-level columns of `schema`, plus, when `config` is set, a zone map seed +/// of the configured size for every other column of a candidate scalar type. +/// Every zone map seed uses `zone_map_seed_version`. +/// +/// 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`. @@ -106,6 +178,7 @@ async fn seed_writers_for( dataset: &Dataset, indices: &[IndexMetadata], schema: &Schema, + config: Option, zone_map_seed_version: ZoneMapSeedVersion, ) -> Result>> { let mut writers: Vec> = Vec::new(); @@ -173,6 +246,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, config.store_null_bitmap)) + .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; @@ -221,9 +310,64 @@ async fn seed_writers_for( .with_null_positions(positions), )); } + // Configured seeds record null positions unless the config turns them + // off, at either seed version. 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, positions) in config_columns { + match ZoneMapSeedWriter::new(&field.name, rows_per_zone, field.data_type()) { + Ok(writer) => writers.push(Box::new( + writer + .with_version(zone_map_seed_version) + .with_null_positions(positions), + )), + Err(err) => log::debug!( + "column {}: no configured zone write seed ({err})", + field.name + ), + } + } Ok(writers) } +/// 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; + } + 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(_, _) + ) +} + #[cfg(test)] mod tests { use super::*; @@ -259,6 +403,74 @@ mod tests { } } + #[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_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( + 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); + } + + #[rstest::rstest] + #[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] indices: Vec<(bool, Option)>, + #[case] expected: Option, + ) { + assert_eq!(seeded_rows_per_zone(indices), 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() { assert_eq!(PlainSeedWriter.required_feature_flags(), 0);