Skip to content

perf(index): assemble btree search results once instead of per page - #9462

Merged
BubbleCal merged 2 commits into
mainfrom
yang/btree-range-result-assembly
Sep 22, 2026
Merged

BubbleCal merged 2 commits into
mainfrom
yang/btree-range-result-assembly

Conversation

@BubbleCal

Copy link
Copy Markdown
Contributor

Problem

A BTree page holds rows sorted by value, so the 4096 row ids of one page are scattered across many fragments. FlatIndex::try_new eagerly built a RowAddrTreeMap (one RoaringBitmap per fragment) for every loaded page, and search_with_options built another one per page for the query result and then unioned them. For a range query touching many pages this is pages x fragments tiny 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 (which DeepSizeOf did not account for).

Change

  • FlatIndex now 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, and DeepSizeOf is now exactly the Arrow buffers. The cache codec is bumped to v2 (batch only); v1 entries are still read.
  • Per-page search returns a PageMatches { selected, nulls } pair of sorted UInt64Arrays. The existing search / search_prebuilt / all* APIs keep working through PageMatches::into_row_addr_set.
  • New RowAddrTreeMap::from_sorted_runs in lance-select: one pass buckets every run's addresses by fragment, sorts a bucket only if the runs actually interleaved, then builds one RoaringBitmap per fragment. BTreeIndex::search_with_options assembles the TRUE set (and the NULL set when null tracking is on) once from all pages' runs.
  • Semantics are unchanged: every row lives on exactly one page, so the union of per-page null sets equals what NullableRowAddrSet::union_all produced, and "null trumps true" is preserved.

Validation

  • New test 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.
  • New tests for PageMatches views and for reading a v1 cache entry; RowAddrTreeMap::from_sorted_runs unit 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).
  • clippy on lance-index and lance-select is clean; the workspace -D warnings run only reports pre-existing dead code in lance-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 main at 00a8230, this PR is the same commit plus this change, both built and run on the same machine.

Scenario / metric Baseline This PR Benefit
Range query, 1% of rows (1M matches), p50 latency 94 ms 27 ms 3.5x speedup
Range query, 10% of rows (10M matches), p50 latency 1182 ms 247 ms 4.8x speedup
Range query, 50% of rows (50M matches), p50 latency 6070 ms 1174 ms 5.2x speedup
Range query, 0.1% of rows, p50 latency 11.5 ms 4.7 ms 2.4x speedup
Process RSS after prewarm_index (1.6 GB of page data) 8262 MB 1631 MB 5.1x less memory
Local prewarm_index wall time 6.1 s 2.5 s 2.4x speedup

Single-page equality queries are unchanged (0.6 ms hot). The criterion bench btree_range_many_fragments added in rust/lance-index/benches/btree.rs reproduces 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

@github-actions github-actions Bot added A-index Vector index, linalg, tokenizer performance labels Sep 22, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added K-changes Latest Gatekeeper recommendation requests changes. and removed K-changes Latest Gatekeeper recommendation requests changes. labels Sep 22, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Gate recommendation: approve.

The earlier cache-format finding is fixed: the experimental v1 reader and fixture are removed, while malformed legacy bodies still follow the existing cache-miss/reload path. No blocking issue remains.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 22, 2026
BubbleCal and others added 2 commits September 22, 2026 19:15
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
BubbleCal force-pushed the yang/btree-range-result-assembly branch from 2a72844 to 1b96ab7 Compare September 22, 2026 11:26
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 22, 2026
@BubbleCal
BubbleCal merged commit f8fe2db into main Sep 22, 2026
38 checks passed
@BubbleCal
BubbleCal deleted the yang/btree-range-result-assembly branch September 22, 2026 11:56
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-index Vector index, linalg, tokenizer performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants