Repository navigation
Conversation
Scanning a scalar index end to end went through `IndexReaderStream`, which issues an independent `read_record_batch` per batch. Each of those builds its own decode plan and issues its own small I/O: one read for the page metadata it touches, then one for the page data. Neither coalesces with the neighbouring batch's, so a full scan costs two round trips per batch plus a scheduler build per batch, and the scan is only as far ahead of the consumer as `buffered(n)` lets it be. Adds `IndexReader::whole_file_stream`, which returns a stream over the whole file under a single decode plan or `None`, and a `stream_index_file` helper that prefers it and falls back to the per-batch path for readers without one. The v2 `FileReader` implements it as one `read_stream_projected` over `RangeFull` at the index's own `batch_size`, so btree pages still line up with batches. Taken at the three btree scan sites: `data_stream`, `calculate_included_frags` and `remap`. `IndexReader::read_range_stream` is the same mechanism over a sub-range but at a fixed batch size, which is why this is a separate method. Measured on a 40k-row btree index at batch size 64 (625 batches, no cache, local FS): 1251 read IOPs before, 9 after.
Three follow-ups to the whole-file index scan. 1. `batch_size` is read from the index file's own metadata, so a `u64` that is a multiple of 2^32 truncated to a `rows_per_batch` of 0 in the `as u32` cast: an empty stream that silently retrained an empty index and reported success. Clamp instead. The regression test fails without the clamp. 2. `merge_range_partitioned_lookups` and `merge_pages` build one stream per partition against a *shared* store, and construct all of them before the consumer polls any. A whole-file plan per partition would let partitions the consumer is not draining occupy the scheduler's byte budget, which is credited back only when a batch is polled, and stall the partition being drained. Both keep the demand-paced `buffered(1)` path; only the three single-stream sites use `stream_index_file`. 3. The IOP test used 10,000 rows, below `DEFAULT_INLINE_SCHEDULING_THRESHOLD` (16 Ki), so it exercised inline scheduling rather than the spawned path this change actually affects. Raised to 40,000 rows.
…sources Now that `data_stream()` is a whole-file plan, what it keeps in flight is capped by the store's scheduler budget rather than by readahead. `merge_segments` opens a store per source segment and starts a stream on each, so the merge was sitting on N of those budgets at once (and none of it is visible to the DataFusion memory pool). Adds `IndexStore::with_io_buffer_size` (default no-op) and has `merge_segments` split one scan's budget across the segments it actually reads. The rescope happens before the stream is awaited, because that is where prefetch starts, not at `execute_plan`. Two limits, documented rather than left to be discovered. The 32 MiB floor keeps a whole page in flight per source, so the aggregate is max(one scan's budget, sources * 32 MiB) and not a constant (past `io_parallelism` sources the floor wins and it grows again). And the budget is soft: a request is admitted regardless of remaining bytes when nothing of lower priority is in flight, which is what keeps things moving at any budget. `LanceIndexStore` deliberately does not size its default budget from a process-wide buffer-size variable: its constructor is on the query path too (`open_scalar_index` builds one store per scalar index a scan opens), so a knob set for one workload would silently retune the other. Callers that need a smaller budget ask for it explicitly through `with_io_buffer_size`.
…per scheduler A whole-file plan's outstanding bytes are bounded only by the scheduler budget, and nothing reported that number: `IoQueueState` tracks `bytes_avail` but exposes nothing, so the only available measurement was whole-process RSS, which cannot separate scheduler prefetch from decode buffers from an index merge's own sort. Adds a high-water mark of bytes debited and not yet credited, the current value of the same quantity (which must return to zero once an abandoned read has given its budget back), plus a count of requests admitted over budget on priority: because nothing of lower priority was in flight, or because the request was a later chunk of one already in flight. That last number matters: it is exactly where the budget is soft rather than hard, and until now the only evidence it happens at all was a debug log. Surfaced through `ScanScheduler::backpressure_stats()` alongside the existing `stats()`, and `LanceIndexStore::scheduler()` so a caller can reach it. The lite scheduler reports zeroes; it accounts for reservations with its own RAII type rather than this queue.
… properties Three tests for the memory properties a whole-file index scan has to hold. The budget is respected. A whole-file scan of a 2M-row index (about 23 MiB of incompressible page data) runs at a 1 MiB and a 4 MiB budget and must hold no more than budget + max_iop_size in flight. The slack is deliberate: the budget is soft, because `can_deliver` admits a request over budget when its priority is at or below everything in flight (which guarantees forward progress) or when it is a later chunk of a request already in flight; the slack is the largest single such admission. A fixture guard asserts the file is larger than that bound, and after the first batch the consumer pauses until bytes in flight stop growing and asserts they reached at least half the budget, so the bound cannot hold vacuously and does not depend on I/O outpacing decode. The budget survives an abandoned scan. A whole-file plan has far more outstanding when dropped than a per-batch read did, so a leak in the credit path is proportionally worse here. A scan of a 400k-row index at a 1 MiB budget is dropped after 1, 32 and 256 batches; the scheduler's bytes in flight must return to zero and a subsequent full scan on the same store must complete. The query path cannot reach the whole-file scan. The index is loaded through a store whose readers panic if asked for a whole-file stream, then searched with equality, range and IS NULL. This is a structural assertion, not an inspection: if a search is later routed through a whole-file plan it fails here. A positive control first asserts that a maintenance scan through the same store does trip the guard, proving the guard is consulted at all.
…budget The budget split in `merge_segments` exists for the multi-source case, so it needs a test that runs it with more than one source. This one merges 2, 4 and 8 segments through stores that record the rescoped store each source is handed, then checks: - each source got exactly one store, budgeted at 1/N of a scan (the 32 MiB floor engages at N=8 with the local default of 8 I/O threads) - every rescoped scheduler carried traffic and stayed within its budget plus one split request, with zero priority bypasses - the original stores' schedulers saw no merge traffic at all, so no read path escapes the split - the merged index still contains every row from all N sources The per-source budgets are far larger than the fixture, so this covers the split and the plumbing rather than throttling under it; the single-scan test covers the latter. Also lifts the training-stream construction into `sorted_training_stream`, shared by the index fixture and the merge's new-data input.
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
Three btree operations read an index end to end rather than looking up a single page:
data_stream(value, row_address)pairs, to retrain itcalculate_included_fragsremapAll three went through
IndexReaderStream, which fetches one btree page per call:read_record_batch(n, batch_size)returns pagen, holdingbatch_sizerows of sorted(value, row_address)pairs — 4096 by default.Each
read_record_batchcall builds a decode plan of its own, and each decode plan issues tworequests: one for the column metadata describing the storage pages that cover those rows, then
one for the encoded bytes in those storage pages.
Both requests are small. 4096 rows of a scalar index is a few KB, while the round trip costs
about as much as fetching megabytes. And because each btree page is planned on its own, the
two requests for page
nare never merged with the two requests for pagen + 1, even thoughthe bytes for both pages sit next to each other in the same file — many btree pages share a
storage page. A full pass therefore costs two round trips and one decode plan per btree page,
and the scan runs only as far ahead of the consumer as
buffered(n)allows.Measured on a 40k-row btree index at batch size 64 (625 pages, no cache, local FS):
1251 read IOPs for the per-page scan, 9 for the whole-file plan below.
Public API
Two new trait methods, both with defaults, so existing implementors compile unchanged
(
rust/lance-index-core/src/scalar.rs):IndexReader::whole_file_streamasync fn whole_file_stream(&self, batch_size: u32, batch_readahead: u32) -> Result<Option<Pin<Box<dyn RecordBatchStream>>>>Ok(None); the caller falls back to per-page readsIndexStore::with_io_buffer_sizefn with_io_buffer_size(&self, bytes: u64) -> Arc<dyn IndexStore>Three new public items for observability:
scheduler::BackpressureStats(io_buffer_size,max_bytes_in_flight,bytes_in_flight,priority_bypass_admissions)lance-ioScanScheduler::backpressure_stats() -> BackpressureStatslance-ioLanceIndexStore::scheduler() -> &Arc<ScanScheduler>lance-indexNothing is removed; no existing signature changes.
Change
whole_file_streamreads the whole index file under a single decode plan, so that oneplan schedules every storage page up front and the scheduler can coalesce those reads into a
handful of large requests. The method returns
Nonefor readers that have no such path. Thev2
FileReaderimplementswhole_file_streamas oneread_stream_projectedoverRangeFullat the index's ownbatch_size, so btree page boundaries still line up with thestream's items.
stream_index_filehelper preferswhole_file_streamand falls back to the per-pagepath for readers that return
None. The three whole-index operations above callstream_index_file.read_range_streamis not reused for this.read_range_streamis the same mechanismover a sub-range, but at a fixed batch size of 4096, and a btree page must line up with the
index's own
batch_size, which may differ. Hence a separate method rather than a caller ofread_range_stream.merge_range_partitioned_lookupsandmerge_pagesdeliberately stay on the per-pagebuffered(1)path. Both build one stream per partition against a shared store, andconstruct every stream before the consumer polls any of them. A whole-file plan per partition
would let the undrained partitions hold the store's byte budget and stall the partition being
drained.
batch_sizeis now clamped rather than cast tou32.batch_sizecomes from the indexfile's own metadata, and a
u64multiple of 2^32 truncated to 0, producing an empty streamthat silently retrained an empty index.
Memory
A whole-file plan is scheduled eagerly, so the plan's outstanding bytes are bounded by the
store's scheduler budget (
SchedulerConfig::max_bandwidth, 32 MiB per I/O thread) rather thanby readahead. That budget is per store, and
merge_segmentsopens one store per sourcesegment, so a merge would otherwise hold N budgets at once — none of those bytes visible to the
DataFusion memory pool.
IndexStore::with_io_buffer_size(bytes)(default: return the store unchanged) lets acaller rescope a store's prefetch budget.
merge_segmentssplits one scan's budget across thesegments that merge actually reads, before each stream is awaited, which is where prefetch
starts. A 32 MiB floor keeps one storage page in flight per source, so the aggregate bound is
max(one scan's budget, sources * 32 MiB). Pastio_parallelismsources the floor wins andthe aggregate grows again.
bytes when nothing of lower priority is in flight — which is what guarantees forward progress
at any budget — and when the request is a later chunk of a request already in flight.
LanceIndexStoredoes not size its default budget from a process-wide variable. TheLanceIndexStoreconstructor is on the query path too:open_scalar_indexbuilds one storeper scalar index a scan opens. Callers that need a smaller budget ask for one explicitly.
backpressure_stats()reports peak and current bytes debited-but-not-credited, plus thecount of over-budget admissions, so the bounds claimed above are checkable rather than
argued.
LanceIndexStore::scheduler()exposes the scheduler thatbackpressure_stats()hangs off. The lite scheduler reports zeroes.
Testing
cargo test -p lance-index-core -p lance-index -p lance-io --libpasses (1562 / 2 / 306);cargo clippy --all --tests --benches -- -D warningsis clean. New tests inlance-index:data_streamscan of the 40k-row fixture takes fewer than 64read IOPs (measured 9; the per-page path takes 1251).
batch_size(2^32) still yields every row.merge_io_buffer_sizeconserves one scan's budget across sources until the 32 MiB floorbinds.
4 MiB budget. A fixture guard asserts the index file exceeds budget +
max_iop_size, readfrom the object store so the guard follows
LANCE_MAX_IOP_SIZE. After the first page theconsumer pauses until bytes in flight stop growing, then asserts bytes in flight reached at
least half the budget — backpressure engaged, independent of I/O speed. The scan then drains
and
peak <= budget + max_iop_sizeholds.256 pages; the scheduler's bytes in flight must return to zero, and a following full scan
must complete.
readers panic on
whole_file_stream. A maintenance scan is shown to trip that panic, thenequality, range and IS NULL searches run against the same index.
merge_segmentsof 2, 4 and 8 segments hands each source exactly one rescoped store at1/N of a scan's budget; every rescoped scheduler carries traffic within its own bound with
zero bypasses, the original schedulers see no merge traffic, and the merged index holds every
row. The per-source budgets here (32 MiB and up) far exceed the 40k-row fixture, so this test
covers the split and the plumbing rather than throttling under the split; the budget test
above covers throttling.
Compatibility
No file format change.
whole_file_streamandwith_io_buffer_sizeare trait methods withdefaults, so existing
IndexReaderandIndexStoreimplementations are unaffected and keepthe per-page behaviour.
Tracking: Ported from rerun-io#63.