Skip to content

perf(index): stream btree pages sequentially for update, remap and prewarm - #9463

Merged
BubbleCal merged 1 commit into
mainfrom
yang/btree-sequential-page-stream
Sep 22, 2026
Merged

BubbleCal merged 1 commit into
mainfrom
yang/btree-sequential-page-stream

Conversation

@BubbleCal

Copy link
Copy Markdown
Contributor

Problem

Whenever the BTree index has to read all of its pages (segment merge on optimize_indices, remap, calculate_included_frags, prewarm) it issued one read_record_batch per page. Each call set up its own decode scheduler and its own object-store requests, so a 24k-page index cost about 60k small requests and, on S3, tens of seconds just to stream 1.3 GB that could be read sequentially.

Change

  • IndexReader gains read_record_batch_stream(batch_size, batch_readahead) with the contract "batch n of the stream equals read_record_batch(n, batch_size)". The default implementation falls back to per-batch reads so every existing reader keeps working; CurrentIndexReader implements it as one sequential Range(0..num_rows) read, V1IndexReader streams row groups, and the legacy range-partitioned LazyRangedIndexReader chains its partition files in global page order (each file streamed on its own so a short trailing page stays a page of its own).
  • read_range_stream now takes the batch size and readahead instead of hard-coding 4096 / 2; bitmap and bloomfilter pass the previous values.
  • New BTreeIndex::page_stream yields (page_idx, batch) and is used by data_stream (hence update / merge_segments), remap, calculate_included_frags and prewarm. prewarm keeps one sequential IO stream and decodes pages concurrently on the compute pool, inserting each under the same BTreePageKey. The legacy merge_pages / merge_range_partitioned_lookups paths use the stream directly. IndexReaderStream is removed; the single-page read_page path used by lookups is unchanged.

Validation

  • test_page_stream_matches_read_record_batch: a plain 8-page index with a short last page and a two-partition ranged index (3 + 2 pages, short pages at global index 2 and 4); every streamed page equals read_record_batch(i) and the count matches num_batches; calculate_included_frags and data_stream are checked on the ranged index.
  • test_whole_index_reads_are_sequential: on a 50-page index the per-page path issues 100 requests while prewarm, calculate_included_frags and data_stream issue 3 each, and all 50 pages land in the cache.
  • cargo test -p lance-index scalar::btree (47 passed), scalar::lance_format (28 passed), scalar::bloomfilter scalar::bitmap (36 passed), cargo test -p lance --lib index::append::tests::test_optimize_btree (7 passed), cargo test -p lance --lib index::scalar (47 passed).
  • cargo clippy -p lance-index --tests --no-deps -- -D warnings clean (the workspace 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 in us-east-1, dataset on S3 (us-east-1) and on local disk. Baseline is main at 00a8230, this PR is the same commit plus this change, both built (separate target directories) and run on the same machine; wall time and read request counts, lower is better. The append case appends 1M rows in 10 fragments and runs optimize_indices on the BTree, which merges the old pages with the new data.

Scenario / metric Baseline This PR Benefit
prewarm_index on S3, wall time 27.5 s 1.2 s 24x speedup
prewarm_index on S3, read requests 59,288 773 77x fewer requests
prewarm_index on local disk, wall time 6.1 s 0.5 s 12x speedup
optimize_indices after 1M-row append, S3, wall time 47.9 s 4.8 s 10x speedup
optimize_indices after 1M-row append, S3, read requests 60,432 803 75x fewer requests
optimize_indices after 1M-row append, local disk, wall time 6.0 s 4.4 s 1.4x speedup

Query latency (hot and cold) is unchanged by this PR.

🤖 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 the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 22, 2026
…ewarm

Whole-index passes over a BTree index (update/merge via data_stream,
remap, prewarm, calculate_included_frags and the legacy distributed
merge paths) used to issue one random read per page, each setting up
its own decode scheduler, so IO scheduling passes and small object
store requests scaled with the number of pages.

Add IndexReader::read_record_batch_stream(batch_size, batch_readahead),
whose n-th batch equals read_record_batch(n, batch_size), and give
read_range_stream caller-chosen batch_size/batch_readahead. The v2
reader implements it as one sequential range read of the file, the v1
reader streams its row groups, and LazyRangedIndexReader chains the
partition page files in global page order so a short trailing page in
one partition stays its own page. BTreeIndex::page_stream builds on it
and replaces IndexReaderStream everywhere; read_page (single page
lookups) is unchanged.

On a 50-page index the per-page path issues 100 requests, the streamed
prewarm / calculate_included_frags / data_stream passes issue 3 each.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@BubbleCal
BubbleCal force-pushed the yang/btree-sequential-page-stream branch from f90f34f to ee31956 Compare September 22, 2026 09:50
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label 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 rebase preserves the reviewed stream patch and composes cleanly with #9461: that change caches metadata across opens, while this one removes per-page scheduling within an open reader. Current-format streaming, V1/custom fallbacks, and legacy partition boundaries remain intact on the current head.

Please mark this PR with the breaking-change label.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 22, 2026
@BubbleCal
BubbleCal merged commit 1de931a into main Sep 22, 2026
39 checks passed
@BubbleCal
BubbleCal deleted the yang/btree-sequential-page-stream branch September 22, 2026 11:14
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 K-approved Latest Gatekeeper recommendation permits acceptance. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants