Repository navigation
perf(index): coalesce btree page loads into one read_ranges request - #9310
Merged
westonpace merged 1 commit intoSep 25, 2026
Merged
Conversation
westonpace
added a commit
to westonpace/lance
that referenced
this pull request
Sep 25, 2026
Reading the whole missing page set in one read_record_batches call let peak memory and in-flight I/O scale with the entire predicate: the merged batch stayed alive until the last page was consumed, which is unbounded for the billion-row scale BTreeIndex targets, and a wide range could allocate many GiB or open every range-partitioned file at once. Replace the lazy, whole-query BatchedPageRead with a chunked prefetch step (PAGE_PREFETCH_CHUNK_SIZE = 128 pages) that reads, materializes, and caches one chunk's pages before moving on to the next, dropping each chunk's serialized batches as it goes. This keeps range coalescing within a chunk while capping the working set, at the cost of a few more requests than reading everything at once - the tradeoff the PR description already called out. Also bounds the IndexReader::read_record_batches default impl (used by the legacy V1 reader) to get_num_compute_intensive_cpus() in-flight reads instead of an unbounded try_join_all, restoring the concurrency bound the per-page search loop had before this PR. Addresses gatekeeper review feedback on lance-format#9310. Co-Authored-By: Claude Sonnet 5 <[email protected]>
westonpace
force-pushed
the
perf/btree-coalesce-page-loads
branch
from
September 25, 2026 17:40
ba3281d to
ba783e1
Compare
westonpace
force-pushed
the
perf/btree-coalesce-page-loads
branch
from
September 25, 2026 18:06
ba783e1 to
de00d05
Compare
A btree search loaded each page it needed with its own read, so a range predicate spanning many pages cost one request per page: a filter matching 7M of 10M rows touches 1,710 pages and issues 3,764 reads, with the index lookup dominating the query's latency. Decide the whole page set before loading any of it instead, and hand the pages that are not already cached to IndexReader::read_record_batches in fixed PAGE_PREFETCH_CHUNK_SIZE (128 page) chunks. Each chunk is read, turned into FlatIndex pages, and *searched immediately* with those pages - not via a follow-up cache lookup, since without a warm, big-enough index cache (no cache configured, or a chunk larger than the cache's capacity) a page could already be evicted by the time a later step looked it up, forcing a single-page read per page and making a wide search cost *more* I/O than reading pages one at a time would have. Handing the entire missing set to one read_record_batches call has the same failure mode one level up: peak memory and in-flight I/O would scale with the whole predicate, unbounded for the billion-row scale BTreeIndex targets. Chunking bounds both, at the cost of a few more requests than reading everything at once. A built page is still offered to the index cache for reuse by a concurrent or later query, but no path depends on that succeeding. Adds IndexReader::read_record_batches, whose default implementation reads one batch per page with in-flight reads capped at get_num_compute_intensive_cpus() (restoring the concurrency bound the per-page search loop had before this change), so the legacy V1 index reader is unaffected beyond that cap. The current-format reader overrides it to map batch numbers onto row ranges via read_ranges, and the ranged reader groups pages by the file that holds them so range-partitioned indices coalesce per file rather than falling back to an unbounded per-page read. Adds MetricsCollector::record_batch_reads (one per read_record_batches call) and its unbatched counterpart record_single_page_reads (one per read_record_batch call - the eviction-race fallback in this path, and the always-individual lookups in BTreeIndex::contains_keys), so callers can see how many coalesced vs. individual requests a query actually took, distinct from record_parts_loaded (page count) and without needing the generic io_stats hook. Also adds a large_range case to the basic btree search benchmark, which had no filter selecting more than 8 of its 10M rows. Rebased onto current main, which restructured this file for async fragment reuse remapping (batch_remapper/decode_page) and per-page result assembly (PageMatches) since this branch's previous base; the page-decode step used by the chunked search (build_page) now shares that same remap path. Co-Authored-By: Claude Sonnet 5 <[email protected]>
westonpace
force-pushed
the
perf/btree-coalesce-page-loads
branch
from
September 25, 2026 18:44
de00d05 to
adde860
Compare
Contributor
There was a problem hiding this comment.
✅ Gate recommendation: approve.
The bounded prefetch still searches each chunk while its pages are live, including with no index cache, so it retains coalesced I/O without query-wide page retention. The rebase uses the current row-ID remapping path for batched pages, and the new read counters have focused coverage. I found no remaining merge-relevant issue.
This was referenced Oct 7, 2026
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.
A btree search loaded each page it needed with its own read, so a range predicate spanning many pages cost one request per page: a filter matching 7M of 10M rows touches 1,710 pages and issued 3,764 reads, with the index lookup accounting for 304ms of the query's 306ms.
Decide the whole page set before loading any of it instead, and hand the pages that are not already cached to a single
read_rangescall, which already merges adjacent and nearby ranges into shared requests.Adds
IndexReader::read_record_batches, whose default implementation keeps today's one-request-per-batch behaviour, so the legacy V1 index reader (whose batches are row groups rather than fixed row ranges) is unaffected. The current-format reader overrides it to map batch numbers onto row ranges, and the ranged reader groups pages by the file that holds them so range- partitioned indices coalesce per file rather than falling back to an unbounded per-page read.The batched read stays behind the page cache's loader, so concurrent queries still coalesce against each other, and a page the batch turns out not to cover falls back to a single-page read.
Measured on a 10M row uint64 btree, cold index cache, filter matching 7M rows:
read_iops 3,764 -> 68
read_bytes 50.6MB -> 49.9MB
search_time 304ms -> 207ms
allocations 1,132,917 -> 277,796
parts_loadedis unchanged at 1,710: the same pages are materialized, in far fewer requests. Peak memory rises 186MB -> 257MB on the index-only query, because the merged batch is alive while each page is copied into its own FlatIndex; chunking the read would bound that at the cost of a few more requests.Also adds a
large_rangecase to the basic btree search benchmark, which had no filter selecting more than 8 of its 10M rows.