Repository navigation
perf(index): merge Bitmap index segments instead of rescanning the dataset - #62
Conversation
`merge_scalar_indices` listed only `IndexType::BTree` in
`has_segment_merge_primitive`, so a Bitmap index with more than one selected
segment fell through to `rebuild_scalar_segment` -- a full rescan and retrain
over every covered fragment. Bitmap declares
`TrainingCriteria::new(TrainingOrdering::Values)`, so that rescan is wrapped
in a blocking spilling `SortExec` against `FairSpillPool(LANCE_MEM_POOL_SIZE)`.
On a production boolean column that meant sorting ~955M rows through a 32 GiB
DataFusion pool to produce a ~1 MB index: 12-17s failures on an 8 GiB pool,
or 38+ minutes wedged on a zero-byte spill file on a 32 GiB one.
Wire Bitmap into the same N:1 segment-merge path BTree uses, as a k-way
sorted merge-join over the source segments' postings. Each segment
contributes its keys from the in-memory `index_map` and its bitmaps one key
at a time through `load_bitmap`. Both choices are load-bearing:
- `index_map` is a `BTreeMap`, so key order does not depend on the on-disk
row order. Bitmap lookup files are not reliably key-sorted -- `remap` and
the `merge_bitmap_indices` HashMap union wrote them from a `HashMap`, and
even `streaming_build_and_write` appends an old-only null row last -- so a
merge that read the files sequentially and assumed sorted input would
silently drop postings.
- `load_bitmap` is the accessor that applies fragment-reuse remapping.
Reading the lookup file's raw bytes would bypass it and emit row
addresses pointing at fragments compaction has already retired, which
under `defer_index_remap: true` is silent data loss.
Peak memory is one posting per segment for the current key plus the union
being emitted -- the bound `merge_shards` gives -- rather than the whole
merged index in heap the DataFusion pool cannot see, which is what the
deleted `merge_bitmap_indices` HashMap union held.
Per-segment `OldIndexDataFilter`s are applied to each source posting, so
compaction-retired fragments and stable-row-id rewrites are dropped exactly
as on the BTree path, and a filter that keeps nothing skips the segment's
reads entirely.
`Dataset::merge_existing_index_segments` now routes bitmap groups through the
same primitive, which also gives it the per-segment filtering it lacked.
Co-Authored-By: Claude Opus 5 <[email protected]>
…nsolidation Close three coverage gaps in the Bitmap segment-merge path: - a k-way merge whose NEW data stream contains nulls, exercising the finish_run null branch that folds every old segment's null_map in exactly once (with a per-segment filter applied to one null posting); - Boolean key columns, the motivating production column type (all previous tests used Utf8 keys); - a genuinely wide consolidation: 26 delta segments merged into one segment by a single optimize_indices call (previous e2e merged 3). Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Directly merging segments created before deferred compaction can silently discard their remapped rows.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds streaming N:1 Bitmap segment merging to avoid costly dataset rescans.
Changes:
- Implements k-way posting merges with per-segment filtering and remapping.
- Routes Bitmap optimization through the merge primitive.
- Adds broad merge, null, Boolean, compaction, and update tests.
File summaries
| File | Description |
|---|---|
rust/lance/src/index/scalar/btree.rs |
Shares the empty merge stream helper. |
rust/lance/src/index/scalar/bitmap.rs |
Integrates Bitmap segment merging. |
rust/lance/src/index/append.rs |
Routes Bitmap optimization and adds integration tests. |
rust/lance-index/src/scalar/bitmap.rs |
Implements streaming k-way merging and unit tests. |
rust/lance-index/src/scalar/label_list.rs |
Updates merge documentation. |
Review details
- Files reviewed: 5/5 changed files
- Comments generated: 1
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| let segment_refs: Vec<&IndexMetadata> = segments.iter().collect(); | ||
| let (fragment_bitmap, old_data_filters) = | ||
| crate::index::append::build_per_segment_filters(dataset, &segment_refs).await?; |
There was a problem hiding this comment.
this doesn't seem to hold. There is no correctness concern here, only small perf concern, and this is not the fix.
There was a problem hiding this comment.
This is an actual bug, reproduced as tests in #75. Not reachable through optimize_indices (which we call). In the public API merge_existing_index_segments (which our rerun repos don't call) the filter deciding which old rows survive is a list of pre-compaction fragment ids, but the rows it checks have already been remapped to post-compaction ids — nothing matches, so all of them are dropped. Pre-existing for BTree.
|
ACTION NEEDED The PR title and description are used as the merge commit message. Please update your PR title and description to match the specification. For details on the error please inspect the "PR Title Check" action. |
There was a problem hiding this comment.
Verdict
No correctness defect found in the K-way merge itself. Heap invariants, the PartialEq-vs-Ord divergence between take_smallest's membership test and the BTreeMap lookup it drives, null-run handling, degenerate inputs (0/1 segments, key-less segments, empty new data), and the irrelevance of output key order to every reader all hold. Randomized differential testing against a brute-force oracle (K=1–6, fragments shared across segments, all three filter shapes including keep-nothing, nulls, values split across batches) matched exactly, and test_bitmap_merge_matches_brute_force_union holds that contract at 200 fixed seeds in ~0.9s. Mutation testing shows the tests are sensitive: dropping take_smallest's cross-segment union, dropping the shared-key old row set in finish_run, neutering filter_keeps_nothing, applying one segment's filter to another, or making retain_valid a no-op are each caught.
The deferred-remap filter defect is excluded here: it is a pre-existing build_per_segment_filters issue that also affects BTree, with a repro in #75.
Confirmed
1. The stated memory bound is not the bound the code has. BitmapBatchWriter accumulates every key and serialized row set, flushing only when the buffer would exceed ~2.15 GB:
// rust/lance-index/src/scalar/bitmap.rs:65
const MAX_BITMAP_ARRAY_LENGTH: usize = i32::MAX as usize - 1024 * 1024; // leave headroom
// :1085
struct BitmapBatchWriter {
file: Box<dyn super::IndexWriter>,
keys: Vec<ScalarValue>,
serialized: Vec<Vec<u8>>,
bytes: usize,
num_bitmaps: usize,
}
// :1106
async fn emit(&mut self, key: ScalarValue, bitmap: &RowAddrTreeMap) -> Result<()> {
let mut buf = Vec::new();
bitmap.serialize_into(&mut buf).unwrap();
let size = buf.len();
if self.bytes + size > MAX_BITMAP_ARRAY_LENGTH { // ~2.15 GB
self.flush().await?;
}
self.keys.push(key);
self.serialized.push(buf);
...flush then allocates a builder of the full size while serialized is still live, briefly doubling it:
// :1129
let total_size: usize = self.serialized.iter().map(|b| b.len()).sum();
let mut binary_builder = BinaryBuilder::with_capacity(self.serialized.len(), total_size);
for b in self.serialized.drain(..) {
binary_builder.append_value(&b);
}So any merged index under ~2.15 GB is held whole in memory. Separately, all K index_maps stay resident for the entire merge, and OldSegments::new materializes a pointer per key per segment on top:
// :643
struct OldSegments<'a> {
segments: Vec<OldSegment<'a>>,
keys: Vec<Vec<&'a OrderableScalarValue>>, // K x cardinality, held for the whole merge
..."Peak memory is one posting per segment for the current key plus the union being emitted" therefore describes the read side only. The change is still a real improvement — it removes the deleted merge_bitmap_indices' fully deserialized HashMap — but the description should match the implementation. Lowering the flush threshold (e.g. 32 MB) would make the claim true; multi-batch output files already read back correctly, since load streams keys and load_bitmap indexes by global row offset.
2. Filtered-empty row sets are written and then persist forever. take_smallest returns Some(empty) for a key whose every row the segment's filter removed, and both emit sites are unconditional:
// :1681
// Emit any remaining old-only entries.
while let Some((key, bitmap)) = old.take_smallest().await? {
writer.emit(key, &bitmap).await?; // no is_empty() guard
}
// :1686
if !emitted_null && let Some(null_bitmap) = old.take_null_bitmap().await? {
let null_key = new_null_array(&value_type, 1);
let null_key = ScalarValue::try_from_array(null_key.as_ref(), 0)?;
writer.emit(null_key, &null_bitmap).await?; // same
}On reload, load populates index_map from the keys column alone, so an emptied key is indistinguishable from a live one and nothing prunes it; successive merges accumulate dead keys without bound. That falls on bitmap's one hard scaling constraint — the resident key directory — so a column whose values stop occurring after compaction or updates grows its directory while its content shrinks.
This is new behaviour on the consolidation path: merge_bitmap_indices applied no filter and so could never produce an empty row set. It also desynchronizes the two row counts, since statistics() derives from the loaded maps while the file metadata counts emit calls:
// :851
fn statistics(&self) -> Result<serde_json::Value> {
let stats = BitmapStatistics {
num_bitmaps: self.index_map.len() + if !self.null_map.is_empty() { 1 } else { 0 },
};Guarding both emits with if !bitmap.is_empty() closes it.
3. Out-of-order new_data silently drops row sets instead of erroring. The run detector compares only against the immediately preceding key:
// :1643
match ¤t_key {
Some(cur) if *cur == key => {
current_bitmap.insert(row_id);
}
_ => {
// Value changed — flush the previous run.So a key that reappears after another key opens a second run, finish_run emits it twice, and load's index_map.insert keeps only the last file offset — the earlier row set is dropped with no error and no diagnostic. Unreachable today: scan_training_data applies a global order_by(asc_nulls_first), and the other producer is the empty stream from empty_value_row_id_stream. This is a missing guard on an undocumented precondition rather than a live bug; a debug_assert! on non-decreasing keys at the run boundary would pin it.
Plausible
4. A legacy segment without fragment coverage now fails the optimize. The two coverage helpers disagree on None:
// rust/lance/src/index/append.rs:151 — tolerates a coverage-less segment
if let Some(eff) = segment.effective_fragment_bitmap(&dataset.fragment_bitmap) {
effective |= eff;
}
// :223 — rejects it
if segment.fragment_bitmap.is_none() {
return Err(Error::invalid_input(format!(
"CreateIndex: segment {} is missing fragment coverage",
segment.uuid
)));
}A Bitmap index with ≥2 selected segments, one pre-dating fragment bitmaps, previously reached rebuild_scalar_segment via split_segment_coverage and succeeded; routing through build_per_segment_filters now errors. Requires a mixed legacy/modern delta chain. BTree already behaves this way.
5. The seed shortcut ignores all but the first selected segment. Will not do in this PR — unreachable. reference_index is selected_old_indices.first(), yet the function returns frag_bitmap covering every selected segment and removes all of them:
// rust/lance/src/index/append.rs:536
let maybe_created = if plugin.might_use_seeds(&index_details) {
if let Some(seeds) = try_harvest_seeds(dataset.as_ref(), unindexed, column_name).await? {
plugin
.update_from_seeds(seeds, reference_index.clone(), &index_details, &new_store)
.await? // <- only the first selected segment's index
} else {
None
}
} else {
None
};With ≥2 selected segments that commits a segment claiming coverage it does not index. Not currently reachable: might_use_seeds is false by default and only ZoneMap overrides it, and ZoneMap is not in has_segment_merge_primitive. Adding IndexType::Bitmap to that gate means a future bitmap seed writer would make it reachable. Refusing seeds when selected_old_indices.len() > 1 removes the hazard.
Test coverage
- The PR's stated motivation — streaming memory — has no test.
test_optimize_bitmap_wide_consolidationuses 26 × 12 rows over 3 distinct values, far too small to detect a regression in peak memory. - No nullable column appears in any of the four e2e tests (
Field::new("cat", DataType::Utf8, false)inid_cat_schema), so no null-related e2e mutation can be caught. The repo's testing rules require NULL edge cases in index tests. commit_bitmap_segment_per_fragmentalways builds one fragment per segment (.fragments(vec![frag_id])), so a partialFragmentsfilter — segment covers{0,1}, only frag 0 retired — is never exercised end to end.test_bitmap_merge_k_segments_with_new_nullsoverclaims. Its doc says the null run folds in "every old segment'snull_map", but seg1's null is removed by the allow-list and seg2 has none, so exactly one segment ever contributes; a "first segment's nulls only" mutation is not caught by this test. Giving seg2 a surviving null would pin the claim.test_optimize_bitmap_multi_segment_merge_consolidatesandtest_optimize_bitmap_wide_consolidationshare ~90% of their body and differ only in segment count, rows per fragment, and whether an unindexed tail exists — one#[rstest]with two cases.test_optimize_bitmap_drops_stale_rows_across_segments_after_updateasserts no segment count, so ifselect_segments_to_mergechanged it would silently degrade to the untouched single-segmentupdatepath while keeping its name. It currently selects K=2;assert_eq!(dataset.load_indices_by_name("cat_idx").await.unwrap().len(), 1)after the optimize pins it.- The
merge_existing_index_segmentsbitmap path has no test. - Doc nit: the comment on
test_optimize_bitmap_multi_segment_merge_consolidatesreads "A 200-way merge over three Bitmap segments" — 200 isnum_indices_to_merge, not a segment count.
Efficiency
BitmapHeapItem.keyis an owned clone pushed on everyadvance, thoughkeysalready holds&'a OrderableScalarValuefor the merge's lifetime — K×cardinalityScalarValueclones (each aStringmalloc for Utf8 keys) for nothing:
// :730
fn advance(&mut self, shard_idx: usize) {
self.pos[shard_idx] += 1;
if let Some(key) = self.keys[shard_idx].get(self.pos[shard_idx]) {
self.heap.push(Reverse(BitmapHeapItem {
key: (*key).clone(), // borrowed already; the clone is avoidable
shard_idx,
}));
}
}take_null_bitmapclones each segment's fullnull_mapeven when that segment's filter isNone:
// :711
let nulls = retain_valid((*segment.index.null_map).clone(), segment.filter);*acc |= &*segment.index.null_map in the None arm is exact and allocation-free.
load_filteredreads throughload_bitmap, which is correct — it is what applies the fragment-reuse remap — but that path also populates the shared index cache and clones to do so, thenload_filteredclones again to filter:
// :517 (inside load_bitmap)
self.index_cache
.insert_with_key(&cache_key, Arc::new(bitmap.clone()))
.await;
// :720
let bitmap = segment.index.load_bitmap(key, None).await?;
Ok(retain_valid(bitmap.as_ref().clone(), segment.filter))For a wide consolidation that pushes the entire old side through a cache where all of it is dead the moment the merge commits, evicting live entries. A cache-bypassing read for the merge path would avoid both the churn and one of the copies.
-
Will not do in this PR — applies to K-way segment merges generally. One
read_range(row_offset..row_offset + 1)per (segment, key), sequentially awaited, on the one path that reads every key of every segment. Each such call builds a decode plan whose initialization is proportional to the pages in the column rather than to the range requested, so the metadata cost is paid per read.whole_file_streamandwith_io_buffer_sizedo not apply here, despiteBTreeIndex::merge_segmentsusing both. They deliver a file in row order, and this merge needs key order: a bitmap lookup file is not reliably key-sorted, which is the premise the merge is built on —remapand the deletedmerge_bitmap_indiceswrote from aHashMap, andstreaming_build_and_writecan still emit an old-only null row last. Walkingindex_mapand reading by row offset is what makes key order independent of file order. BTree can stream because its page data is sorted on disk. So there is no fast path to adopt, and no K-way fan-out of streams whose prefetch budget would need rescoping.What is available is concurrency rather than streaming: the keys are known up front from
index_map, so a bounded number of reads could be in flight per segment instead of one at a time, keeping memory at O(depth × segments). That addresses round-trip latency, which dominates on object storage, without touching the ordering requirement. The read count is unchanged from the deleted code either way, and at the cardinality a bitmap index is meant for the whole term is small — a boolean column is three reads. -
Will not do in this PR — applies to K-way segment merges generally. No segment-merge primitive reports build progress: neither
BitmapIndex::merge_segments,BTreeIndex::merge_segments(btree.rs:1884) norNGramIndexBuilder::merge_segments(ngram.rs:403) takes anIndexBuildProgress, andmerge_scalar_indicespasses one to none of its arms. The rebuild path these replace does report —build_bitmap_shard(bitmap.rs:1746), plusmerge_bitmap_shards,write_bitmap_indexandscan_bitmap_shards— so an optimize that switches from rebuild to merge goes silent. The deletedmerge_bitmap_indicesaccepted a progress argument, but its only caller passednoop_progress(), so nothing was reported there either. Wiring one primitive and not its siblings would be worse than the current uniformity.
Style
unreachable!in library code, againstrust/CLAUDE.md's "neverpanic!()" and "don't silently guard against impossible conditions":
// :1724
if old.peek_key() == Some(&orderable) {
let Some((_, old_bitmap)) = old.take_smallest().await? else {
unreachable!("peeked key must be takeable")
};Dead by construction (a non-empty peek implies a successful pop), as is the inner else { break } in take_smallest.
- The uniform-
value_typecheck returnsError::indexwhere the three adjacent checks in the same block useError::invalid_input, andsegmentsis caller data:
// :573
for segment in segments.iter().skip(1) {
if segment.value_type != first.value_type {
return Err(Error::index(format!( // siblings use invalid_input
"cannot merge bitmap segments with different value types ({:?} vs {:?})",(btree.rs:1908 has the same shape, so fixing one implies both.)
filter_keeps_nothingis now a fourth copy of the same helper (lance-index/src/scalar/btree.rs:2031,lance-index/src/scalar/rtree.rs:478,lance/src/index/scalar/rtree.rs:16, and here):
// :623
fn filter_keeps_nothing(filter: &Option<super::OldIndexDataFilter>) -> bool {
match filter {
Some(super::OldIndexDataFilter::Fragments { to_keep, .. }) => to_keep.is_empty(),
Some(super::OldIndexDataFilter::RowIds(valid)) => valid.is_empty(),
None => false,
}
}All four depend on Fragments staying a pure allow-list — to_remove is read by no consumer of this shape. OldIndexDataFilter in lance-index-core is the natural home.
Checked and clear
- The
field(0)→index_of(VALUE_COLUMN_NAME)change is a strict improvement: every producer names the column, and the loop below already read it by name, so the old positional read was the unsound half. - The new
value_typechecks are load-bearing, not decorative —OrderableScalarValue::cmppanics on mismatched variants. Value types agree across all three derivation sources (dataset schema, persisted segment type, scan schema) for Utf8, LargeUtf8,Dictionary(Int32, Utf8), Decimal128, Timestamp+tz, Date32 and FixedSizeBinary, including thetest_data/v0.20.0/old_btree_bitmap_indices.lancefixture. Segments carrying divergent per-segment dictionaries merge correctly, sinceScalarValue::try_from_arrayresolves the value rather than the code.alter_columnsrefuses to cast an indexed column, so committed segments cannot outlive a type change. - Committed coverage matches committed content on both entry points;
dataset_version = min(selected)errs toward more masking rather than stale-trusted for every consumer traced; label_list cannot be misrouted into either bitmap branch (index_type()isLabelListand thetype_urlpredicates are disjoint). load_unindexed_training_datais still called when there are no unindexed fragments, but it reserves no sort memory: DataFusion registers a zero-size consumer and never reachesreserve_memory_for_mergefor a zero-batch input. The residual cost is plan construction plus acount_all_rows()that only fills a log line.
`BitmapIndex::merge_segments` promises that its output is the union of its filtered inputs, and nothing asserted that directly. The existing tests pin hand-built shapes; this covers the contract itself. 200 fixed seeds, each building 1-4 segments over a 5-value vocabulary and a 4-fragment address space so keys and row addresses collide across segments, every `OldIndexDataFilter` arm including ones that keep nothing, and nulls on either side. `oracle_keeps` reimplements `retain_old_rows` rather than calling it, so the oracle is independent of the code under test. Assertions read `index_map`/`null_map` rather than `search`, comparing what the merge wrote instead of how a query later resolves a row that is both null and non-null. A key whose rows are all filtered out is still materialised with an empty bitmap, so only a key outside the vocabulary counts as fabricated. Runs in ~0.9s. Verified to fail on an ignored per-segment filter, a dropped cross-segment union, and a filter applied from the wrong segment. Co-Authored-By: Claude Opus 5 <[email protected]>
…ap-segment-merge-r10
A bitmap index stores one value's row set as a single `BinaryArray` element, addressed by an `i32` offset, so it cannot reach `MAX_BITMAP_ARRAY_LENGTH` (`i32::MAX` less headroom). `BitmapBatchWriter::emit` checked only the accumulated buffer against that limit, and flushing to make room does nothing when the buffer is already empty, so a single oversized entry passed the check and reached `BinaryBuilder::append_value`, panicking in `next_offset` with "byte array offset overflow". Check each entry before buffering it and return `Error::NotSupported` naming the value and both sizes. A value's row set costs at most one bit per row of the offset space it spans, so the limit is reachable on a large, low-cardinality column: a boolean spread evenly over more than `8 * i32::MAX` rows gives each of its two values a row set over the limit, and the index becomes unbuildable rather than reporting why. Fragment-aligned or run-heavy values compress to `Full` or run containers and stay far below it, so the threshold depends on distribution, not row count alone. This does not raise the limit; writing such a row set needs `LargeBinary` offsets or splitting one value across entries, both format changes. Co-Authored-By: Claude Opus 5 <[email protected]>
An old-data filter can remove every row of a key. `BitmapBatchWriter::emit` wrote it anyway, with a zero-row bitmap, and `BitmapIndex::load` builds `index_map` from the keys column alone, so it came back indistinguishable from a live key. Nothing prunes such an entry, and every later merge re-read and re-emitted it, so a column whose values stop occurring -- retired by compaction, deleted, or updated away -- accumulated one permanent directory entry per value it ever held. The resident key directory is what bounds a bitmap index, so the cost lands on the one scarce resource. Skip the entry instead. `emit` is the single choke point for every write path, and both filter variants drop emptied fragments, so an `is_empty` set really holds no rows. An all-filtered merge now writes a row-less file, which loads correctly because the file schema carries the value type independently. This also realigns `statistics()`, which counts `index_map` plus the null row, with the file's `num_bitmaps` metadata, which counts entries written. Co-Authored-By: Claude Opus 5 <[email protected]>
`streaming_build_and_write` groups rows into runs by comparing each value with the previous one only, so a value that reappears after another value opens a second run for a key already written. `BitmapIndex::load` keys `index_map` by value and keeps the last file offset, so the earlier run's row set was dropped with no error, assertion or log line. Nulls have the same exposure through `null_map`, which takes the last null entry in the file. Check the ordering at each value change, which costs one comparison per distinct value rather than per row, and return `Error::invalid_input` naming both keys. `BitmapIndex::merge_segments` and `BitmapIndexPlugin::train_bitmap_index` take a caller-supplied stream and validated everything about it except the ordering the build depends on. Only the non-null keys have to ascend. Nulls are collected into `null_map` rather than merge-joined by value, so one null run is correct wherever it falls, and both `asc_nulls_first` and `asc_nulls_last` input stay valid; a second null run is what gets rejected. Cover nulls end to end as well. Every `optimize_indices` test used a non-nullable column, so no null reached the scanner's ordering, the per-segment filters or the commit. `test_optimize_bitmap_multi_segment_merge_keeps_nulls` consolidates three segments plus an unindexed tail over a column that is null every fourth row, and checks `IS NULL` and `IS NOT NULL` against the value row sets. `test_bitmap_merge_k_segments_with_new_nulls` now gives a second old segment a surviving null, so it pins the claim in its own doc comment that the null run folds in every segment rather than only the first. Co-Authored-By: Claude Opus 5 <[email protected]>
861002f to
dd2a4da
Compare
The k-way merge-join bounds what the build reads: one row set per segment for the key being unioned, plus that union. It does not bound what the build writes. `BitmapBatchWriter` flushes only when the buffered bytes would cross `MAX_BITMAP_ARRAY_LENGTH`, which is Arrow's `i32` offset ceiling rather than a chosen buffer size, so an index below ~2.15 GB is written as one record batch and is fully resident until `finish`, with `flush` briefly doubling it. Each source segment's `index_map` also stays resident, and dominates on a high-cardinality column. Record the trade a smaller flush target would make, since it is not one-sided: it would bound the output, and multi-batch lookup files are already valid, but batch boundaries force page breaks and `IndexReader::read_range` initializes a decode plan over every page in the column rather than the requested range, so page count costs every single-key read as well as whole-file scans. Unmeasured either way, so the constant is left alone. Co-Authored-By: Claude Opus 5 <[email protected]>
`OldSegments` walks each source segment's resident `index_map`, so the keys it orders outlive the heap, but the heap item owned its key and every push cloned one -- an allocation apiece for string keys, for every key of every segment. Give that merge its own heap item holding `&OrderableScalarValue`. The clone count drops from one per key per segment to one per key emitted, which `take_smallest` still needs because the writer takes an owned key. `merge_shards` keeps `BitmapHeapItem` as it is: it reads keys out of a per-shard batch that is replaced as the cursor advances, so it has nothing to borrow from. Co-Authored-By: Claude Opus 5 <[email protected]>
`load_filtered` read each source row set through `load_bitmap`, which caches what it reads. A merge touches every key of every source segment exactly once, and the commit that follows retires those segments, so every entry it inserted was dead on arrival while evicting entries for indices that still exist. The cache holds up to 6 GiB by default, so a wide consolidation can displace a lot. Each row set was also copied three times: deserialized, cloned for the cache insert, then cloned again by `load_filtered` to get something it could filter in place. Split the read at the cache boundary. `read_bitmap_at` does the read, deserialize and fragment-reuse remap; `load_bitmap` keeps its null, absent-key and cache handling around it, unchanged for the query path and for `load_bitmap_index_state`. `read_bitmap_uncached` gives the merge an owned row set with no cache interaction, which `load_filtered` then filters in place, leaving one copy instead of three. Going through `load_bitmap` was never gratuitous -- it is what applies the fragment-reuse remap, and reading the file directly would resurrect row addresses pointing at retired fragments. `read_bitmap_at` keeps that remap, so only the caching is bypassed. Co-Authored-By: Claude Opus 5 <[email protected]>
86f7c78 to
524a65d
Compare
|
Noting a fragment-reuse remap cost this PR makes more visible, for the FRI remap work rather than for here.
RowAddrTreeMap::from_iter(row_addrs.row_addrs().unwrap().filter_map(|addr| {
let addr_as_u64 = u64::from(addr);
self.remap_row_id(addr_as_u64)
}))So it costs O(rows) lookups and rebuilds the map by individual insert, discarding the input's roaring containers. A single bitmap entry on a low-cardinality column can hold hundreds of millions of rows, and this runs on every index open and every key read once a
Unrelated, same function: |
…bitmap merge `rust/CLAUDE.md` forbids `panic!`/`unreachable!` in library code and asks for impossible conditions to be removed rather than guarded. `finish_run` popped the old side behind an `unreachable!` for a `None` that a preceding `peek_key` had already excluded; a let-chain expresses the same thing without the branch. `take_smallest`'s inner loop had the mirror image, a `break` for a pop that its `while` condition had already proven would succeed; peeking before popping removes it. The mismatched-`value_type` check returned `Error::index` where the three checks beside it use `Error::invalid_input`, and `segments` is caller data. Scoped to code this change introduces. `btree.rs`'s equivalent value-type check and the other copies of `filter_keeps_nothing` are left alone. Co-Authored-By: Claude Opus 5 <[email protected]>
Every other Bitmap merge test goes through `optimize_indices` and builds one segment per fragment, so the distributed-build entry point had no coverage and neither did a segment covering more than one fragment -- which is the only way a per-segment filter is a strict subset of what the segment holds. `test_bitmap_merge_existing_index_segments_multi_fragment` commits two segments over four fragments, two fragments each, deletes one row from each segment's coverage, then merges and opens the result directly. Stable row ids make the filter an exact row-id allow-list, so the deletions reach it instead of being masked at scan time. Verified to fail when the per-segment filter is not applied. `test_optimize_bitmap_drops_stale_rows_across_segments_after_update` now asserts one segment remains. It selects two today, but nothing pinned that, so a change to `select_segments_to_merge` could have quietly moved it onto the single-segment `update` path while it kept its name. Co-Authored-By: Claude Opus 5 <[email protected]>
Brings in #62 (Bitmap segment merge), which routes multi-segment Bitmap consolidation through the merge path this fix covers. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…taset (#9290) ## Problem `merge_scalar_indices` lists only `IndexType::BTree` and `IndexType::NGram` in `has_segment_merge_primitive`, so a Bitmap index with more than one selected segment falls through to `rebuild_scalar_segment`: a full rescan and retrain over every covered fragment. Bitmap trains on `TrainingOrdering::Values`, so that rescan is wrapped in a blocking, spilling `SortExec` against `FairSpillPool(LANCE_MEM_POOL_SIZE)`. On a large low-cardinality column this sorts every row of the column to produce an index of a few megabytes, and fails outright once the pool is exhausted. The k-way merge that `merge_bitmap_indices` already runs over `index_map` keys was not reachable from `optimize_indices`, could not take a new-data stream, and applied a single filter to every source. `Dataset::merge_existing_index_segments` for Bitmap applied no old-data filter at all. ## Change Bitmap joins the N:1 segment-merge path BTree uses. - `OldSegments` presents K source segments as one ascending-key stream of filtered postings: a min-heap over each segment's in-memory `index_map` keys (borrowed, not cloned), with each segment's bitmaps read one key at a time. `build_index_map` takes `Vec<OldSegment>` instead of a single optional old index, so the single-segment `update` path, the LabelList merge (`merge_index_maps`) and the new `BitmapIndex::merge_segments` share one merge-join. `merge_bitmap_indices` is deprecated and forwards to `merge_segments`; `merge_existing_index_segments` now goes through `build_per_segment_filters` and the shared primitive. - Two choices are load-bearing. Keys come from `index_map` (a `BTreeMap`), because bitmap lookup files are not reliably key-sorted on disk (an update appends an old-only null row last, and LabelList files written before spill-based builds are unsorted). Bitmaps are read through the accessor that applies fragment-reuse remapping, because reading raw file bytes would emit row addresses that point at fragments compaction already retired, which under deferred index remapping is silent data loss. - Per-segment `OldIndexDataFilter`s drop compaction-retired fragments and stable-row-id rewrites exactly as on the BTree path; for a segment whose filter keeps nothing, none of its bitmaps are read (its `index_map` is still loaded when the segment is opened). - Merge reads bypass the index cache (`read_bitmap_uncached`): every source entry is read once and the sources are retired by the following commit, so caching them only evicted live entries. The fragment-reuse remap is kept; only the caching is skipped. - Unsorted input is rejected with `Error::invalid_input` in release builds, replacing a `debug_assert!`. A value that reappears after another value reopens a run for a key already written, and `BitmapIndex::load` keeps only the last file offset per key, so the earlier row set vanished silently. The cost is one comparison and two scalar clones per distinct value, not per row. Nulls may lead or trail as a single run. - A key whose bitmap comes out empty is not written, on every path: the check moves to `BitmapBatchWriter::emit`, which also covers `remap_index_map`, which previously wrote such keys deliberately. Absent and present-but-empty are query-equivalent, so nothing observable changes for readers; dropping saves an entry in the resident key directory, a bitmap load and a heap step per emptied key in every later merge, and gives every path one rule instead of two. Peak memory on the old side of a merge is one posting per segment for the current key plus the union being written, on top of each segment's resident `index_map`. On a synthetic 500M-row dataset with 26 delta segments, consolidation through `optimize_indices` went from 36-40 minutes to about 2.5 minutes and stayed flat across 8, 16 and 24 GiB memory pools, where the rescan path failed with memory-pool exhaustion at 8 GiB. ## Public API One addition and one deprecation, `rust/lance-index/src/scalar/bitmap.rs`: | item | change | |---|---| | `BitmapIndex::merge_segments` | new `pub async fn`; the k-way merge this PR adds | | `merge_bitmap_indices` | now `#[deprecated(note = "use BitmapIndex::merge_segments")]` | The deprecated function keeps its signature and behaviour, forwarding to `merge_segments` with no old-data filters and an empty new-data stream. It is not removed. ## Tests - `lance-index`: `test_bitmap_merge_k_segments{,_without_new_data,_with_new_nulls,_boolean_keys}`, `test_bitmap_merge_matches_brute_force_union` (200 seeds against an independent oracle), `test_bitmap_merge_does_not_cache_source_bitmaps`, `test_bitmap_build_rejects_unsorted_input` (rstest), `test_bitmap_merge_drops_emptied_keys`; `test_bitmap_segment_merge_matches_single_build` and `test_bitmap_remap_matches_materialized_path` adapted. - `lance`: `test_optimize_bitmap_multi_segment_merge_consolidates`, `test_optimize_bitmap_wide_consolidation` (26 segments), `test_optimize_bitmap_multi_segment_merge_keeps_nulls`, `test_optimize_bitmap_merge_remaps_deferred_compaction`, `test_optimize_bitmap_drops_stale_rows_across_segments_after_update`, `test_bitmap_merge_existing_index_segments_multi_fragment`. ## Compatibility No on-disk format change and no index version bump: the merged file is a regular `bitmap_page_lookup.lance` that existing readers load as before. Files written by earlier versions merge the same way, because the merge is driven by the loaded `index_map`, not by on-disk row order. `lance_index::scalar::bitmap::merge_bitmap_indices` keeps its signature and is marked `#[deprecated]`; it forwards to `BitmapIndex::merge_segments` with no new data and no filters and keeps its progress stages. `BitmapIndex::merge_segments` is the replacement, with per-segment filters and a new-data stream. --- **Tracking:** Ported from rerun-io#62. --------- Co-authored-by: Zeljko Mihaljcic <[email protected]>
|
Rebase note. Upstream as lance-format/lance#9290 ( A release branch cut from an upstream commit at or after lance-format#9290 already has it: drop this commit rather than carrying it forward. (The fragment-reuse remap cost noted in the comment above is a separate observation and is not addressed by lance-format#9290.) |
Port of #55 (which targets
release-8.0.0) torelease-10.0.0.What
merge_scalar_indiceslisted onlyIndexType::BTree(and, on v10,IndexType::NGram) inhas_segment_merge_primitive, so a Bitmap index with more than one selected segment fellthrough to
rebuild_scalar_segment— a full rescan and retrain over every covered fragment.Bitmap declares
TrainingCriteria::new(TrainingOrdering::Values), so that rescan is wrappedin a blocking spilling
SortExecagainstFairSpillPool(LANCE_MEM_POOL_SIZE), sorting thewhole column to produce an index that is typically ~1 MB.
This change wires Bitmap into the same N:1 segment-merge path BTree uses: a k-way sorted merge-join
over the existing
bitmap_page_lookup.lancesegments' postings, with no dataset scan.Two implementation choices are load-bearing:
index_map(aBTreeMap), not from the on-diskrow order. Bitmap lookup files are not reliably key-sorted —
remapand the oldmerge_bitmap_indicesHashMap union wrote them from aHashMap, and evenstreaming_build_and_writeappends an old-only null row last — so a merge that read thefiles sequentially and assumed sorted input would silently drop postings.
load_bitmap, the accessor that appliesfragment-reuse remapping. Reading the lookup file's raw bytes would bypass it and emit row
addresses pointing at fragments compaction has already retired, which under
defer_index_remap: trueis silent data loss.Peak memory is one posting per segment for the current key plus the union being emitted,
rather than the whole merged index in heap the DataFusion pool cannot see — which is what the
deleted
merge_bitmap_indicesHashMap union held.Per-segment
OldIndexDataFilters are applied to each source posting, so compaction-retiredfragments and stable-row-id rewrites are dropped exactly as on the BTree path, and a filter
that keeps nothing skips the segment's reads entirely.
Dataset::merge_existing_index_segmentsnow routes bitmap groups through the same primitive,which also gives it the per-segment filtering it lacked.
Benchmark evidence, with provenance
Synthetic rig, 500M rows, 26 delta segments, cold cache,
LANCE_FRAG_REUSE_REMAP_MODE=compact: 2,171–2,383s → 49.5s (~43x). Caveat: this numberwas measured with an integer-hasher change also applied, so it is not attributable to this
commit alone.
More important than the speedup, this fixes a real production failure rather than only a
slowdown. On the same rig, stock lance dies at
bitmap.rsExternalSorterMergememory-pool exhaustion at
LANCE_MEM_POOL_SIZE=8 GiB, which is a production value. Patched isflat at ~151s across 8, 16 and 24 GiB.
🤖 Generated with Claude Code