Repository navigation
perf(scalar): build one decode plan per index scan, not one per batch - #63
Conversation
aa0348b to
d063560
Compare
Scanning a scalar index end to end went through `IndexReaderStream`, which issues an independent `read_record_batch` per 4096-row batch. Each of those builds a fresh `DecodeBatchScheduler`, and `DecodeBatchScheduler::try_new` runs `initialize()` — which for the structural encoding initializes *every page in the column*, with no reference to the rows being requested. So a full scan costs O(batches x pages) metadata reads instead of O(pages). Each read is one small chunk-metadata buffer, and consecutive pages' buffers sit megabytes apart, so the scheduler's coalescer (gap tolerance = block_size, 4 KiB on local FS) cannot merge them: every one becomes its own pread. Adds `IndexReader::whole_file_stream`, which returns a single-decode-plan stream or `None`, and takes it in the btree scan paths. Readers without a fast path keep the old per-batch behaviour via the default. Measured on the new test's fixture (10k rows, 157 batches): 315 read IOPs before, 4 after. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three changes from review feedback. 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. Regression test verified to fail 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 — 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. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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. Also has `LanceIndexStore` honour `LANCE_DEFAULT_IO_BUFFER_SIZE`. Its doc comment asks paths with a computed default to consult it, but index stores never did, so `LANCE_IO_THREADS` was the only way to shrink the budget and that changes concurrency too. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Yesterday's commit had `LanceIndexStore::with_format_version` consult `LANCE_DEFAULT_IO_BUFFER_SIZE`. That constructor is not maintenance-only: `open_scalar_index` builds one per scalar index a scan opens, so this put a knob tuned for one workload in charge of the other. It also went the wrong way in practice. We set that var to Lance's own default (2 GiB) rather than leaving it unset, so instead of letting a deployment shrink the budget it raised every index store from 32 MiB x LANCE_IO_THREADS (256 MiB for us) to 2 GiB, query path included. Back to `max_bandwidth`, with a comment saying why. The merge-site bound stays: `merge_segments` still splits one scan's budget across its sources through `with_io_buffer_size`, which is explicit and scoped to the caller that needs it. If we do want a knob later it should be its own index-store variable, not one the scanner already owns. Side effect: `merge_io_buffer_size` no longer reads the environment, so its test is deterministic regardless of how the shell is configured. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The review objection to this PR is that a whole-file plan's outstanding bytes are bounded only by the scheduler budget, and that nothing reports that number. The second half was true: `IoQueueState` tracks `bytes_avail` but exposes nothing, so every measurement so far has been whole-process RSS, which cannot separate scheduler prefetch from decode buffers from the index merge's own sort. Adds a high-water mark of bytes debited and not yet credited, plus a count of requests admitted through the `priority <= min_in_flight` path despite the budget being exhausted. That second 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. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three tests, one per objection raised in review. The budget is respected. A whole-file scan of a 40k-row index is run at a 1 MiB and a 32 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 whose priority is at or below everything in flight even when the budget is exhausted, and that is what guarantees forward progress. Measured on this fixture: 480 KB in flight against 1 MiB, zero bypass admissions. The budget survives an abandoned scan. A whole-file plan has far more outstanding when dropped than a 4096-row plan did, so a leak in the credit path is proportionally worse here. The scan is dropped after 1, 32 and 256 batches and a subsequent full scan on the same store must complete within 30 s. 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 someone later routes a search through a whole-file plan it fails here. Each test carries its own positive control, because all three would otherwise pass vacuously. The budget test asserts the gauge actually moved; the query-path test first asserts that a maintenance scan through the same store *does* trip the guard, proving the guard is consulted at all. Both controls were checked to fire before being folded in. Not covered: the drop test cannot be shown to fail without reverting the credit-on-drop fix it guards, so treat it as a regression guard rather than a demonstration. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Every earlier measurement ran with a single source, so the budget split in merge_segments had never executed with the multiplier it exists for. This test runs merges of 2, 4 and 8 segments through stores that record the rescoped scheduler 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 locally) - 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 Passes at LANCE_IO_THREADS=8 and 64 (256 MiB and 2 GiB scan budgets). Peaks print under --nocapture so reviewers see numbers, not asserts.
The byte budget that bounds a whole-file index scan is per store, and `open_scalar_index` builds one store per segment, so a caller that fans out over N segments holds N budgets. Nothing could report that: `backpressure_stats` is per scheduler and only tests ever read it, and none of it is visible to the DataFusion memory pool, so the only observable was whole-process RSS. Tag each scheduler with a `SchedulerPurpose` and keep a process-wide sum of bytes debited but not yet credited, so `bytes_in_flight(Index)` answers "how much are index readers holding right now" from one call. Index stores tag themselves; everything else defaults to `Other`. Measured against the per-store sum across a 2-to-24 segment fan-out, the gauge matches byte for byte at every width. Also log at INFO when `calculate_included_frags` recomputes a fragment bitmap: it scans every segment end to end, concurrently, each at a full budget (N x 256 MiB at LANCE_IO_THREADS=8), and it is reached from the commit path, so it is worth knowing when it fires. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
d063560 to
d69baec
Compare
|
Closed the upstream port of this PR's scheduler instrumentation, lance-format/lance#9738, as not needed.
The four test call sites here all read |
…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]>
|
Rebase note. Superseded upstream in two pieces; do not carry this forward. The streaming half — reading a whole index file under one decode plan instead of one read per btree page — arrived on
The merge-budget half did not come across with it and had to be raised separately: reading a whole file under one decode plan moves the bound on in-flight bytes from readahead to the scheduler's byte budget, and that budget is per store, so A release branch cut from an upstream commit at or after lance-format#9761 has both halves and needs none of this commit. One detail differs: the version here sizes the budget from (The scheduler-instrumentation side-branch is covered by the comment above.) |
Port of #36 to
release-10.0.0.What this does
BTreeIndex's end-to-end scan paths went throughIndexReaderStream, which issues anindependent
read_record_batchper batch. Each of those builds a freshDecodeBatchScheduler, andDecodeBatchScheduler::try_newrunsinitialize()— whichfor the structural encoding initializes every page in the column, with no reference to
the rows actually requested. A full scan therefore costs O(batches x pages) metadata
reads instead of O(pages), and those reads are one small chunk-metadata buffer per page
sitting megabytes apart, so the scheduler's coalescer cannot merge them: each becomes its
own pread.
With
DEFAULT_BTREE_BATCH_SIZE = 4096and batches corresponding to pages, the per-batchsetup cost grows as roughly
sum over segments of (rows_per_segment / zone_size)^2— soit hurts most on wide segments, which is exactly production's shape.
The change adds
IndexReader::whole_file_stream, which returns a single-decode-planstream or
None, plus astream_index_filehelper that prefers it and falls back to theold per-batch behaviour for readers without a fast path. It is taken at the three
single-stream btree scan sites (
data_stream,calculate_included_frags,remap).The follow-on commits handle what that changes about memory:
merge_range_partitioned_lookupsandmerge_pagesbuild one stream per partitionagainst a shared store and construct all of them before the consumer polls any, so
they deliberately stay on the demand-paced
buffered(1)path.batch_sizecomes from the index file's own metadata, so it is clamped rather thancast — a
u64multiple of 2^32 used to truncate to 0 and silently retrain an emptyindex.
IndexStore::with_io_buffer_size(default no-op) letsmerge_segmentssplit onescan's prefetch budget across the segments it actually reads, instead of sitting on N
store budgets at once (none of which is visible to the DataFusion memory pool). The
32 MiB floor keeps a whole page in flight per source, so the aggregate bound is
max(one scan's budget, sources * 32 MiB).ScanScheduler::backpressure_stats()reports the peak of bytes debited-not-creditedand the count of requests admitted through the
priority <= min_in_flightpath despitean exhausted budget — the two numbers that make the budget claims checkable rather than
arguable.
respected, budget returned on an abandoned scan, query path never takes the whole-file
path) and that
merge_segmentsreally hands each source a 1/N share.Benchmark evidence
4.56x and 4.50x on two real 2.75B-row production manifests, memory-controlled.
Attribution was established by subtraction bisect: reverting the schema-clone commit
1543c9fmoved only 4.3s on a 17-minute run, which rules out schema-clone andfragment-open as contributors and leaves this change carrying the win.
Measured memory (added after review)
Stress-tested at
LANCE_IO_THREADS=8(256 MiB per store) with incompressible 324 MiB pagefiles, sampling the concurrent aggregate rather than summing per-scheduler high-water marks.
merge_segmentsN x 36 MiBonce the 32 MiB floor binds (32 plus a measured ~4 MiBbypass overshoot, well inside the documented
budget + one split request). The floor binds forevery
N >= io_parallelism, so the aggregate is linear in N — ~7 GiB atnum_indices_to_merge=200.Conserving one scan's budget only holds up to
N = io_parallelism; past that a caller needs tomerge in passes.
calculate_included_fragsis not rescoped.LogicalScalarIndexruns one whole-file scan persegment concurrently, each at a full store budget:
N x 256 MiB. Reachable only viamigrate_indices' corrupt-bitmap gate, and it now logs at INFO when it fires.remapis alsounrescoped but runs serially, so it is a floor raise rather than a multiplication.
stepfixture is under 500 KB against1-128 MiB budgets, so backpressure never engages and the bounds hold vacuously. They need a
fixture larger than the budget plus a saturation guard.
Adds
SchedulerPurposeand a process-widebytes_in_flight/peak_bytes_in_flightgauge sothis is observable in production; index stores are tagged
Index.🤖 Generated with Claude Code