Repository navigation
perf(index): assemble btree search results once instead of per page - #9462
Merged
Merged
Conversation
Xuanwo
approved these changes
Sep 22, 2026
A btree page holds rows sorted by value, so its row ids are scattered across many fragments. `search_with_options` used to build one `RowAddrTreeMap` per candidate page (one tiny RoaringBitmap per fragment touched by that page) and then union them all, which is O(pages x fragments) allocations and merge work: a 10% range over a large many-fragment dataset paid for tens of thousands of page maps holding millions of tiny bitmaps. Each page now hands back its matched ids as plain sorted `UInt64Array` views of its id column (`PageMatches`: selected ids plus null ids when nulls are tracked), and the final set is built once with the new `RowAddrTreeMap::from_sorted_runs`: ids are bucketed by fragment in a single pass, a bucket is sorted only if the runs feeding it actually interleaved, and exactly one bitmap is built per fragment. Since every row lives on exactly one page, the union of per-page null sets is already the final null set, so no cross-page subtraction is needed. `FlatIndex` no longer materializes the all-ids / null-ids treemaps at load time; `all()`, `all_non_null()`, `all_ignore_nulls()` and the null shortcuts in `search` filter the sorted id column on demand. The cache codec drops the two roaring blobs (version 2) and still reads v1 bodies by skipping them, and `DeepSizeOf` now reflects exactly what a cached page holds. `FlatIndex::search` / `search_prebuilt` keep their signatures on top of the new `*_matches` primitives. Adds a test whose row ids span 200 fragments with every page covering all of them (range, IN, equality, IS NULL, with and without null tracking) and a `btree_range_many_fragments` criterion group (`LANCE_BTREE_BENCH_MANY_FRAG_ROWS` scales the dataset). Co-Authored-By: Claude Fable 5.1 <[email protected]>
The cache codec is still experimental, so an older body layout should fail closed and be treated as a miss instead of carrying a compatibility branch. Remove the v1 read path and its fixture test. Co-Authored-By: Claude Fable 5.1 <[email protected]>
BubbleCal
force-pushed
the
yang/btree-range-result-assembly
branch
from
September 22, 2026 11:26
2a72844 to
1b96ab7
Compare
westonpace
pushed a commit
that referenced
this pull request
Oct 13, 2026
…9761) ## Problem `BTreeIndex::merge_segments` builds every source's stream before consuming any of them: ```rust for (segment, old_data_filter) in segments.iter().zip(old_data_filters) { let stream = segment.data_stream().await?; ... inputs.push(Arc::new(OneShotExec::new(stream))); } ``` `data_stream` reads a segment's index file through `page_stream`, which calls `IndexReader::read_record_batch_stream`. Since #9463, `read_record_batch_stream` reads the whole file under a single decode plan rather than issuing one read per btree page. A single decode plan schedules every one of its reads up front, before the consumer polls the stream at all. The bytes that plan holds in flight are therefore capped by the scheduler's byte budget, not by how far readahead lets the stream run ahead. Each segment owns an `IndexStore`, each `IndexStore` owns a `ScanScheduler`, and each `ScanScheduler` carries a byte budget of its own. Merging N segments therefore holds N full budgets at once. `SchedulerConfig::max_bandwidth` is 32 MiB per I/O thread, so at the cloud default of 64 threads that is 2 GiB per source, none of it visible to the DataFusion memory pool. ## Change - `IndexStore::with_io_buffer_size(bytes)` returns a store whose reads are bounded by `bytes` of outstanding data. `LanceIndexStore` implements it by building a scheduler with the smaller budget over the same object store. Unlike `with_io_priority`, the scheduler cannot be shared: the budget belongs to the scheduler. - `SchedulerConfig::max_bandwidth_bytes(io_parallelism)` exposes the budget `max_bandwidth` would hand a store, so the merge divides the real number rather than a second copy of the formula. - `merge_segments` counts the sources it will actually read (those not skipped by `filter_keeps_nothing`), divides one scan's budget between them, and rescopes each segment's store before building its stream — which is where prefetch starts. The source count and the I/O parallelism both come from those sources alone: `segments[0]` may itself be skipped, and segments under different base paths carry different parallelism. - The per-source share has a floor of one storage page (32 MiB), so a source fetches a whole page at a time rather than trickling. That is a throughput floor, not a liveness one: the scheduler admits a pending request whenever nothing of lower priority is in flight, so a source makes progress at any budget. The aggregate is therefore `max(one scan's budget, num_sources * 32 MiB)`. The division conserves one scan's budget only while `num_sources <= io_parallelism` — 64 sources on cloud storage, but **8 on local**. Past that the floor binds and the total grows with the source count, so a caller wanting a fixed total has to merge in several passes. That is far better than the N full budgets the current code holds, but it is not a constant bound. ## Compatibility `with_io_buffer_size` is **required**, not defaulted, so an out-of-tree `IndexStore` will not compile until it adds one. A defaulted no-op would let a caller ask for a bound, silently not get one, and have no way to tell; `with_io_priority` beside it is required for the same reason. A store that prefetches nothing may still return itself — it just has to say so. Every other `IndexStore` in the tree is a test double over a real store, so each one forwards and the question does not arise for them. No file format change, and no existing signature changes. ## Testing `cargo test -p lance-index -p lance-index-core -p lance-io --lib` passes (2011 / 9 / 323); `cargo clippy --all --tests --benches -- -D warnings` is clean. - **Plumbing** — three trained segments merge with the middle one's filter keeping nothing. A recording `IndexStore` asserts the two read sources are each rescoped exactly once, to half of one scan's budget, and that the skipped source is never rescoped at all. Verified the test fails both ways: removing the rescoping call leaves the recorder empty, and counting the skipped source divides three ways (89478485) instead of two (134217728). - **Arithmetic** — one source gets what a single scan would have had; 2/4/8/16/32/64 sources still total one scan's budget between them; the floor binds from the 9th source at local I/O parallelism; and degenerate inputs yield the floor rather than 0, which the scheduler reads as "no backpressure" rather than "the smallest budget". Verified the test fails when the division is removed: two sources then total 4 GiB where one scan would have held 2 GiB. ## PR history This began as rerun-io#63 on our `release-10.0.0` line, offered upstream as #9289: whole-index btree passes were reading one page per request, and that PR replaced them with a single decode plan per scan. While #9289 was open, `main` arrived at the same place independently — #9463 streams btree pages sequentially through `read_record_batch_stream`, #9310 coalesces page loads into one `read_ranges`, and #9462 assembles search results once rather than per page. Between them they cover what #9289 was for, so it is closed. One piece did not come across. Reading a whole index file under a single decode plan moves the bound on in-flight bytes from readahead to the scheduler's byte budget, and that budget is per store. `merge_segments` opens one store per source and builds every source's stream before consuming any, so it now holds one full budget per source — on `main` today, with no rescoping anywhere. That is the OOM this PR prevents, and it is all this PR does; the streaming work it was originally bundled with is already in `main`. --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
A BTree page holds rows sorted by value, so the 4096 row ids of one page are scattered across many fragments.
FlatIndex::try_neweagerly built aRowAddrTreeMap(oneRoaringBitmapper fragment) for every loaded page, andsearch_with_optionsbuilt another one per page for the query result and then unioned them. For a range query touching many pages this ispages x fragmentstiny bitmaps to allocate, clone and merge: a 10% range over a 100M-row, 1000-fragment dataset spent more than a second in this assembly, and the per-page treemaps made a cached page cost about 5x its Arrow data (whichDeepSizeOfdid not account for).Change
FlatIndexnow holds only the page batch (sorted by row id) and its DataFusion schema. Null / non-null / all ids are computed on demand as filtered views of the id column, andDeepSizeOfis now exactly the Arrow buffers. The cache codec is bumped to v2 (batch only); v1 entries are still read.PageMatches { selected, nulls }pair of sortedUInt64Arrays. The existingsearch/search_prebuilt/all*APIs keep working throughPageMatches::into_row_addr_set.RowAddrTreeMap::from_sorted_runsinlance-select: one pass buckets every run's addresses by fragment, sorts a bucket only if the runs actually interleaved, then builds oneRoaringBitmapper fragment.BTreeIndex::search_with_optionsassembles the TRUE set (and the NULL set when null tracking is on) once from all pages' runs.NullableRowAddrSet::union_allproduced, and "null trumps true" is preserved.Validation
test_search_assembles_rows_across_many_fragments: 200 fragments, page size larger than the fragment count so every page spans every fragment, nulls every 50th row; range / IN / equality / absent-equality / IS NULL, each with and without null tracking, compared against a brute-force expectation.PageMatchesviews and for reading a v1 cache entry;RowAddrTreeMap::from_sorted_runsunit test.cargo test -p lance-select(115 passed),cargo test -p lance-index scalar::btree(48 passed),cargo test -p lance --lib index::scalar(47 passed),cargo test -p lance --lib index::append::tests::test_optimize_btree(7 passed).-D warningsrun only reports pre-existing dead code inlance-io/src/object_store/throttle.rs.Benchmark
100M random Int64 rows in 1000 fragments, BTree with 24,659 pages, c7i.16xlarge, dataset on local disk, index prewarmed, 5 iterations per selectivity, p50, lower is better. Baseline is
mainat 00a8230, this PR is the same commit plus this change, both built and run on the same machine.prewarm_index(1.6 GB of page data)prewarm_indexwall timeSingle-page equality queries are unchanged (0.6 ms hot). The criterion bench
btree_range_many_fragmentsadded inrust/lance-index/benches/btree.rsreproduces the effect at 1M rows (2.5x / 5.2x / 18.6x for the few / many / most cases on a dev laptop).🤖 Generated with Claude Code