Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
* OptimizeOptions#getMaxRowsPerSegment()} every index is one task: the single-process optimize over
* all of its segments and all of its unindexed fragments, with the caller's options, and a merge
* that passes the result through. With a bound set, an index whose kind can merge segments (vector,
* BTree, Bitmap, BloomFilter, NGram, RTree, Inverted, LabelList) is split: tasks build one
* BTree, Bitmap, BloomFilter, NGram, RTree, Inverted, LabelList, ZoneMap) is split: tasks build one
* uncommitted segment each over a group of fragments, and merges combine the task results of their
* group with the committed segments they absorb into one segment. Other indices stay one task, and
* an index a split build cannot handle is skipped with a warning unless {@link
Expand All @@ -56,6 +56,11 @@
* <p>LabelList segments must match the identifier domain written by the dataset. Incompatible
* groups use one unsplit task.
*
* <p>ZoneMap reuses compatible v1 segments and distributes rebuilds of v0 or incompatible segments.
* If a selected live segment has a separate base path or a pending legacy remap, the plan only
* indexes new fragments. With tagged fragment reuse, bounded optimize skips ZoneMap unless
* explicitly named, which fails instead. Fragments are indivisible.
*
* <p>An ordinary commit publishes every merged segment in one transaction anchored at the plan's
* read version, so conflict detection covers everything committed since the plan was made. Results
* may be partial: whatever they do not cover stays unindexed for the next optimize.
Expand Down
420 changes: 260 additions & 160 deletions rust/lance-index/src/scalar/zonemap.rs

Large diffs are not rendered by default.

208 changes: 178 additions & 30 deletions rust/lance-index/src/scalar/zonemap/tests.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

Expand Down Expand Up @@ -50,7 +50,7 @@
lance_format::LanceIndexStore,
zonemap::{
HarvestedZoneSeed, ReusedZones, SEED_NULL_BITMAP_META_KEY, SEED_VERSION_META_KEY,
SeedOutcome, ZONEMAP_FILENAME, ZONEMAP_SIZE_META_KEY, ZoneMapIndex,
SeedOutcome, ZONEMAP_FILENAME, ZONEMAP_SIZE_META_KEY, ZoneMapIndex, ZoneMapIndexBuilder,
ZoneMapIndexBuilderParams, ZoneMapProcessor, ZoneMapSeedVersion, ZoneMapSeedWriter,
ZoneMapSegmentBase, build_zonemap_segment, merge_seeds_for_binary_copy,
merge_zonemap_indices, parse_seed_for_binary_copy, place_records, remap_zone,
Expand Down Expand Up @@ -6938,15 +6938,18 @@
/// An update whose scan covers a partial fragment's uncovered interval
/// and a whole fragment: zones are cut at the configured boundaries,
/// seed and scan fold into one zone, positions stay exact.
#[rstest::rstest]
#[case::update(false)]
#[case::merge(true)]
#[tokio::test]
async fn test_build_segment_update_folds_seeds_and_scan_into_target_zones() {
async fn test_build_segment_update_folds_seeds_and_scan_into_target_zones(#[case] is_merge: bool) {
let tmpdir = TempObjDir::default();
let store = local_store(&tmpdir);
// Fragment 0 from a scan, with a bitmap, target zones of 4.
// Fragment 0 is retained; fragment 1 is replaced by the new seed/scan data.
build_segment_from_batches(
store.as_ref(),
ZoneMapIndexBuilderParams::new(4),
vec![vec![None, Some(1)]],
vec![vec![None, Some(1)], vec![None, Some(-1)]],
)
.await;
let existing = ZoneMapIndex::load(
Expand Down Expand Up @@ -6997,16 +7000,36 @@
let physical_rows = HashMap::from([(1u64, 6u64), (2, 2)]);
let dest = TempObjDir::default();
let dest_store = local_store(&dest);
let created = build_zonemap_segment(
ZoneMapSegmentBase::Update(&existing),
&DataType::Int32,
reused,
Some(scanned),
&physical_rows,
&[1, 2],
dest_store.as_ref(),
)
.await
let created = if is_merge {
let builder = ZoneMapIndexBuilder::from_segments(
&[(existing.as_ref(), &RoaringBitmap::from_iter([0, 1]))],
&RoaringBitmap::from_iter([1, 2]),
)
.unwrap();
let scanned = super::train_zonemap_scan(
&DataType::Int32,
4,
builder.keeps_null_positions(),
physical_rows,
scanned,
)
.await
.unwrap();
builder
.write_segment(reused, scanned, dest_store.as_ref())
.await
} else {
build_zonemap_segment(
ZoneMapSegmentBase::Update(&existing),
&DataType::Int32,
reused,
Some(scanned),
&physical_rows,
&[1, 2],
dest_store.as_ref(),
)
.await
}
.unwrap();
let details = created
.index_details
Expand Down Expand Up @@ -7052,26 +7075,151 @@
assert!(nulls.contains((2 << 32) | 1));
assert_eq!(nulls.len(), Some(5));

// Reusing seeds without positions for an index that keeps them is a
// caller error, not a silent downgrade.
let seed = seed_of(3, 4, int_values(2, 0));
let mut no_positions = ReusedZones::new(false);
no_positions
.reuse(&harvested(seed, 2), 4, &DataType::Int32, true)
.unwrap();
let err = build_zonemap_segment(
ZoneMapSegmentBase::Update(&existing),
if !is_merge {
// Reusing seeds without positions for an index that keeps them is a
// caller error, not a silent downgrade.
let seed = seed_of(3, 4, int_values(2, 0));
let mut no_positions = ReusedZones::new(false);
no_positions
.reuse(&harvested(seed, 2), 4, &DataType::Int32, true)
.unwrap();
let err = build_zonemap_segment(
ZoneMapSegmentBase::Update(&existing),
&DataType::Int32,
no_positions,
None,
&HashMap::new(),
&[3],
local_store(&TempObjDir::default()).as_ref(),
)
.await
.err()
.expect("reuse without positions must be rejected");
assert!(err.to_string().contains("without null positions"), "{err}");
}
}

#[tokio::test]
async fn test_merge_restores_exact_null_positions_after_refreshing_source_without_bitmap() {
let mut a = train_and_load::<Int32Type>(vec![vec![Some(-1), None]]).await;
// This format supports exact NULLs, but their positions are absent in A.
Arc::get_mut(&mut a).unwrap().null_rows = None;
assert!(a.store_null_bitmap());
let b = train_and_load::<Int32Type>(vec![vec![], vec![None, Some(3)]]).await;

let batch = record_batch!(
(VALUE_COLUMN_NAME, Int32, [None, Some(2)]),
(ROW_ADDR, UInt64, [0u64, 1])
)
.unwrap();
let scan = Box::pin(RecordBatchStreamAdapter::new(
batch.schema(),
stream::iter([Ok(batch)]),
));
let dest = TempObjDir::default();
let store = local_store(&dest);
let builder = ZoneMapIndexBuilder::from_segments(
&[
(&a, &RoaringBitmap::from_iter([0])),
(&b, &RoaringBitmap::from_iter([1])),
],
&RoaringBitmap::from_iter([0]),
)
.unwrap();
let scanned = super::train_zonemap_scan(
&DataType::Int32,
no_positions,
2,
builder.keeps_null_positions(),
HashMap::from([(0, 2)]),
scan,
)
.await
.unwrap();
builder
.write_segment(ReusedZones::default(), scanned, store.as_ref())
.await
.unwrap();

let merged = ZoneMapIndex::load(
store,
None,
&HashMap::new(),
&[3],
local_store(&TempObjDir::default()).as_ref(),
&LanceCache::no_cache(),
false,
ZoneMapIndexVersion::V1,
)
.await
.err()
.expect("reuse without positions must be rejected");
assert!(err.to_string().contains("without null positions"), "{err}");
.unwrap();
let result = merged
.search(&SargableQuery::IsNull(), &NoOpMetricsCollector)
.await
.unwrap();
assert_eq!(
result,
SearchResult::exact(RowAddrTreeMap::from_iter([0u64, 1 << 32]))
);
}

#[tokio::test]
async fn test_merge_rejects_scanned_zones_without_null_positions() {
let dir = TempObjDir::default();
let store = local_store(&dir);
build_segment_from_batches(
store.as_ref(),
ZoneMapIndexBuilderParams::new(4),
vec![vec![None, Some(1)]],
)
.await;
let existing = ZoneMapIndex::load(
store,
None,
&LanceCache::no_cache(),
true,
ZoneMapIndexVersion::V1,
)
.await
.unwrap();
assert!(existing.has_null_bitmap());

let mut scanned = super::ScannedZones::default();
for (fragment, track_nulls) in [(1, false), (2, true)] {
let batch = arrow_array::record_batch!(
(VALUE_COLUMN_NAME, Int32, [None, Some(1)]),
(ROW_ADDR, UInt64, [fragment << 32, (fragment << 32) | 1])
)
.unwrap();
let stream = Box::pin(RecordBatchStreamAdapter::new(
batch.schema(),
stream::iter([Ok(batch)]),
));
scanned.merge(
super::train_zonemap_scan(
&DataType::Int32,
4,
track_nulls,
HashMap::from([(fragment, 2)]),
stream,
)
.await
.unwrap(),
);
}

let dest = TempObjDir::default();
let builder = ZoneMapIndexBuilder::from_segments(
&[(existing.as_ref(), &RoaringBitmap::from_iter([0]))],
&RoaringBitmap::from_iter([1, 2]),
)
.unwrap();
let error = builder
.write_segment(ReusedZones::new(true), scanned, local_store(&dest).as_ref())
.await
.err()
.expect("scanning without null positions must be rejected");
assert!(matches!(error, Error::InvalidInput { .. }), "{error}");
assert!(
error.to_string().contains("scanned without null positions"),
"{error}"
);
}

/// The low-level plugin entry reuses only seeds whose every record fits
Expand Down
16 changes: 12 additions & 4 deletions rust/lance/src/dataset/tests/dataset_zone_map_seed_reuse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1158,7 +1158,7 @@ async fn test_two_zone_maps_on_one_column_share_the_finer_seed() {
}
}

/// A rebuild over a subset (two segments merged) goes through the
/// A rebuild over a subset (two incompatible segments) goes through the
/// metadata-aware builder: a scanned fragment keeps its configured
/// boundaries up to its deleted tail, a fully seed-covered deleted fragment
/// keeps its physical zones, fragments outside the request get no zones,
Expand All @@ -1175,8 +1175,8 @@ async fn test_rebuild_keeps_boundaries_past_a_deleted_tail() {
.await
.unwrap();
// Three segments: fragment 0 (replace), fragment 1 (append mode), then
// fragment 2 appended and indexed in append mode; merging the trailing
// two is a rebuild over {1, 2} with fragment 0 outside the request.
// fragment 2 indexed with a different zone size. The incompatible trailing
// two require a rebuild over {1, 2}, with fragment 0 outside the request.
create_index(
&mut dataset,
"val",
Expand All @@ -1189,8 +1189,16 @@ async fn test_rebuild_keeps_boundaries_past_a_deleted_tail() {
.await
.unwrap();
append(&mut dataset, 2 * N..3 * N).await;
let params = zone_map_params(2000, true, true);
let segment = CreateIndexBuilder::new(&mut dataset, &["val"], IndexType::ZoneMap, &params)
.name(index_name("val"))
.replace(true)
.fragments(vec![2])
.execute_uncommitted()
.await
.unwrap();
dataset
.optimize_indices(&OptimizeOptions::new().num_indices_to_merge(Some(0)))
.commit_existing_index_segments(&index_name("val"), "val", vec![segment])
.await
.unwrap();
assert_eq!(index_metadata(&dataset, "val").await.len(), 3);
Expand Down
42 changes: 42 additions & 0 deletions rust/lance/src/dataset/tests/dataset_zone_map_seeds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use std::sync::Arc;

use arrow::compute::concat_batches;
use arrow_array::cast::AsArray;
use arrow_array::types::Int32Type;
use arrow_array::{
Array, ArrayRef, BinaryArray, BinaryViewArray, Int32Array, RecordBatch, RecordBatchIterator,
StringArray, StringViewArray, StructArray,
Expand Down Expand Up @@ -861,6 +863,46 @@ async fn test_merge_insert_partial_fragment_rewrite_seeds_new_file() {
assert_seed_matches_data(&dataset, &[1, 2], "val").await;
}

#[tokio::test]
async fn test_zone_map_refresh_after_rewrite_and_deferred_compaction() {
let dataset = dataset_with_val_index("memory://", true).await;
// Row 17 was null in indexed fragment 1. Rewrite it before compacting
// that fragment together with the unindexed append.
let mut dataset = merge_insert_val(dataset, 17..18).await;
let metrics = compact_files(
&mut dataset,
CompactionOptions {
defer_index_remap: true,
..Default::default()
},
None,
)
.await
.unwrap();
assert_eq!(metrics.fragments_removed, 2);
assert!(dataset.get_fragment(1).is_none());

dataset
.optimize_indices(&OptimizeOptions::default())
.await
.unwrap();

for use_index in [false, true] {
let mut scan = dataset.scan();
scan.use_scalar_index(use_index)
.project(&["id"])
.unwrap()
.filter("val IS NULL")
.unwrap();
let plan = scan.explain_plan(false).await.unwrap();
assert_eq!(plan.contains("ScalarIndexQuery"), use_index, "{plan}");
let batch = scan.try_into_batch().await.unwrap();
let mut ids = batch["id"].as_primitive::<Int32Type>().values().to_vec();
ids.sort_unstable();
assert_eq!(ids, [3, 10, 24], "use_scalar_index={use_index}");
}
}

/// `FileFragment::write_columns`, used by computed and function column
/// refreshes, stages a replacement column file that carries a seed, even
/// when the column already moved out of the fragment's first file.
Expand Down
Loading
Loading