Skip to content

perf(scalar): build one decode plan per index scan, not one per batch - #36

Closed
rerun-rmack wants to merge 7 commits into
release-8.0.0from
rmack/index-stream-one-scheduler
Closed

rerun-rmack wants to merge 7 commits into
release-8.0.0from
rmack/index-stream-one-scheduler

Conversation

@rerun-rmack

@rerun-rmack rerun-rmack commented Aug 16, 2026 •

Copy link
Copy Markdown
Member

Problem

Scanning a scalar index end to end goes through IndexReaderStream, which issues an independent read_record_batch per 4096-row batch. Each builds a fresh DecodeBatchScheduler, and try_new runs initialize() — which in StructuralPrimitiveFieldScheduler::initialize iterates every page in the column, ignoring the rows actually requested. A full scan therefore costs O(batches × pages) metadata reads. Each is one small chunk-metadata buffer, and consecutive pages' buffers sit megabytes apart, so the coalescer (gap tolerance = block_size) can never merge them — one pread each.

Fix

Adds IndexReader::whole_file_stream(batch_size, readahead) -> Option<stream>, implemented for the v2 FileReader as a single read_stream_projected over RangeFull, and uses it in the btree scan paths. Readers with no fast path return None and keep the existing per-batch behaviour.

Measurements

Two btree index files scanned end to end through both paths in one binary — large: 21.3 GB / 5,505 pages, 20,000 of 234,855 batches; small: 1.1 GB / 698 pages, full scan:

index cache per batch one plan
small 64 MB 12.00 s 4.40 s 2.7×
large ≥256 MB 16.63 s 3.54 s 4.7×

With the cache disabled the per-batch path degrades to 214 s and 835 s. The one-plan path is identical at every cache size — it does not depend on the cache holding, which is the main argument for it.

In per-batch mode IOPs/batch equals the file's page count exactly (698 and 2,755) — that is the mechanism, measured. Both paths return byte-identical output (checksummed).

Testing

cargo test -p lance-index --lib — 638 pass. The new test asserts an IOP bound and was verified to fail without the fix (315 vs a bound of 32).

Draft

whole_file_stream is implemented only for the v2 FileReader; the multi-file LazyRangedIndexReader still takes the per-batch path.

@rerun-rmack
rerun-rmack force-pushed the rmack/index-stream-one-scheduler branch from 52a2d77 to e478c7e Compare August 16, 2026 18:46
@zehiko

zehiko commented Aug 17, 2026

Copy link
Copy Markdown
Member

My main concern was switching to entire file reader, hence probed Claude for the risk. It seems there is one. I'm also wondering given that Lance team is quite responsive to issues, if we should (in parallel) open an issue describing the findings and the proposed fix, to see if there's more things we're missing.

Risk 1 (blocker): early stream drop permanently leaks the shared scheduler's byte budget

  Both agents converged on this independently, traced to the same code:

  - For a whole-file read, schedule_ranges runs on a background task and pushes IoTasks for the entire file into the IoQueue up front. Backpressure bytes are
  debited at dispatch and credited back only when the decoder consumes the response (scheduler.rs:804-810).
  - If the consumer drops the stream mid-scan, the completion callback is let _ = tx.send(...) — the bytes and the priorities_in_flight entry are never
  returned. Queued tasks are cancelled only when the ScanScheduler drops — but LanceIndexStore holds its scheduler for the store's lifetime, and the store
  lives inside the cached loaded index.
  - One cancelled scan of a file bigger than the budget (32 MiB × io_parallelism = 2 GiB on cloud, 256 MiB local) can permanently drain bytes_avail and
  head-of-line-block the heap — after which live index searches on that same store hang, since they share the same queue.

  This isn't hypothetical for us: pocgi's scalar-index OPTIMIZE passes are known to abort mid-stream on DataFusion pool exhaustion, in a loop. The leak
  technically pre-exists per-batch, but exposure per drop scales from ~64 small reads to the entire remaining 21 GB file.

  Risk 2 (major): the answer to "is one decoder per whole stream risky?" — yes, on memory

  - Old path: buffered(io_parallelism) was demand-paced — at most N single-batch reads in flight, ~tens of MB. The two merge paths were deliberately paced at
  buffered(1).
  - New path: batch_readahead in read_stream_projected bounds decode buffering only — the reader's own doc says it "has no effect on the I/O parallelism of the
  read". The background scheduler races ahead of the consumer, bounded only by the per-store 2 GiB budget, and this buffering is invisible to the DataFusion
  memory pool.
  - The converted call sites have exactly the slow consumers that fill that budget: remap inside compaction, data_stream feeding a sort during optimize,
  merge_pages gated on writes. In merge_segments, each segment is a separate store with its own budget — worst case ≈ k × 2 GiB of raw encoded buffers on a
  process that already OOMs at 60 GiB with a shared, already-exhausted memory pool.

  Risk 3 (major, magnitude unproven): head-of-line blocking of live searches

  Search-path point reads and the whole-file scan share the same per-store IoQueue, all at base_priority = 0, ordered by scan position. Old path kept queue
  depth ~64; new path parks ~5,500 tasks in the heap for the scan's duration. A concurrent search on that index can lose every pop until the scan's tasks
  dispatch — added p99 in the same process serving live traffic. Worth one targeted test: btree search p99 during optimize_indices on a multi-GB index,
  before/after.

Proposed fix (sketch):

 **Proposal: window the stream instead of going whole-file — and we may not need the new trait method at all.**

  `IndexReader::read_range_stream` already exists and its v2 impl (`lance_format.rs`) is a near-duplicate of the new `whole_file_stream` — same
  `read_stream_projected`, same `from_whole_schema`, just ranged and with hardcoded `4096, 2`. So: make `stream_index_file` a loop that issues one plan per
  bounded window (~256 MiB, aligned to `batch_size` multiples), sequentially, via `read_range_stream`, and normalize the output to exact `batch_size` batches
  with the same `chunk_concat_stream` helper `merge_pages` already uses.

  Why this keeps the win: window 1's `initialize()` populates the whole-column metadata cache entry, so windows 2..N are cache hits — total metadata IO stays
  O(pages), not O(windows × pages). (Caveat: that relies on the store having a real metadata cache; production does, `no_cache` fixtures don't.) And it fixes
  all three issues at once: prefetch ≤ one window, drop-waste/leak-exposure ≤ one window, queue depth ≤ one window's tasks.

  What goes away:
  - the new `whole_file_stream` trait method + its v2 impl (the impl duplicates `read_range_stream` 30 lines above it);
  - the `Result<Option<…>>` silent-fallback shape — the trait's *default* `read_range_stream` (materialize via `read_range`) is now an acceptable fallback
  because it's window-bounded, so `LazyRangedIndexReader`/v1 need no special-casing;
  - the `batch_size as u32` narrowing (currently: `batch_size % 2^32 == 0` → `rows_per_batch = 0` → stream silently ends after zero batches → `remap` retrains
  an empty index and reports success — please fix regardless);
  - both future rebase conflict sites (upstream moved `IndexReader` to `lance-index-core` and newtyped the reader; a btree.rs-only patch survives that).

@rerun-rmack

Copy link
Copy Markdown
Member Author

Addressed some of the review feedback in a new commit (clamp batch_size, keep shared-store merges paced) and separate PR #37 for backpressure accounting (leak is real, but it's capped at the io_buffer_size and the store/scheduler are per-operation so it doesn't persist.)

My Claude says some things we don't need to worry about:

  1. Prefetch memory: The bound is a hard cap that every full-file lance scan already has; this PR doesn't raise it. Meanwhile it deletes a bigger term (per-batch initialize() materialising full-column metadata at priority 0, which is exempt from the byte gate, up to 64 concurrent).

  2. Head-of-line blocking: The ordering mechanism is exactly as described, but the IoQueue belongs to a LanceIndexStore that is constructed per operation. It's never shared with a live search.

Recommended next steps:

  1. Send fix(io): credit the backpressure budget when a request is dropped #37 upstream now. Zero API change, pure bug fix in their code, self-contained reproduction that hangs without it. Highest acceptance odds of the three, and if taken that drift goes to zero.
  2. File the issue for perf(scalar): build one decode plan per index scan, not one per batch #36 before polishing the patch. Upstream may well prefer to fix initialize() at the root, which would delete our patch entirely.
  3. Keep perf(scalar): build one decode plan per index scan, not one per batch #36 as-is meanwhile. It's measured, it's safe, the API shape is the compatible one, and the port across the known relocation is mechanical.
  4. Skip the helper dedup for now. It's ~6 genuinely duplicated lines. Worth doing only if we end up carrying the patch long-term — and if upstream takes the issue, the shape changes anyway and the work is wasted.

@rerun-rmack
rerun-rmack requested a review from zehiko August 17, 2026 11:49
@rerun-rmack
rerun-rmack marked this pull request as ready for review August 17, 2026 11:50
Comment thread rust/lance-index/src/scalar/btree.rs Resolved
@rerun-rmack

Copy link
Copy Markdown
Member Author

Pushed a commit that bounds this. merge_segments now splits one scan's budget across the segments it actually reads, rescoping each store before the stream is awaited (that's where prefetch starts, not at execute_plan). Also made LanceIndexStore honour LANCE_DEFAULT_IO_BUFFER_SIZE, which turns out to already exist and to already be documented as applying to this exact constructor, index stores just never consulted it. So there is a knob now.

Two bits of your feedback I did not take, and one thing you should know before trusting the numbers.

Capping the number of concurrently-open segment streams. A k-way sort-preserving merge needs a live cursor on every input, and nesting the merge nodes doesn't reduce leaf concurrency, so bounding it properly means multi-pass merging with materialized intermediates (an extra full write and read per level). It also wouldn't help on its own, since the prefetch starts when the streams are constructed. Splitting the budget gets the same memory ceiling for none of that.

Windowing instead of whole-file. The premise checks out (FieldDataCacheKey has no range component, so windows after the first hit cache), but it makes the win conditional on the metadata cache holding, and cache-independence is the main reason for the whole-file path in the first place. Prod's cache was pinned full when we hit this.

What isn't measured. The A/B runs don't cover your scenario. Every index in that fixture had exactly one segment, so N was 1 throughout and the multiplicative term never ran. There's also no in-flight-bytes instrumentation in those runs, and the fixture is local disk (256 MiB budget) rather than object storage (2 GiB). The new bound is reasoned, not measured, and the underlying budget is soft in any case (a request is admitted regardless of remaining bytes when nothing of lower priority is in flight). Both caveats are in the doc comments.

Separately, on #37: it turns out upstream already fixed that in lance-format#7638 back in July and just never backported it to v8.0. So it's a backport rather than a new finding, and release-9.0.0 already has it (plus the lite scheduler half, which ours doesn't do). Nothing to send upstream.

@zehiko

zehiko commented Aug 18, 2026

Copy link
Copy Markdown
Member

Also made LanceIndexStore honour LANCE_DEFAULT_IO_BUFFER_SIZE, which turns out to already exist and to already be documented as applying to this exact constructor, index stores just never consulted it. So there is a knob now.

This is my remaining concern - we already tuned this knob for the use of the Scanner i.e. the query path. In other words - it's still hard for me to reason how this PR will impact a stack under load, will the query path be impacted, will the memory blow up, etc. Not sure what's the best way to test this.

My humble honest take is - let's see if we can merge deferral and if it's good enough. Cut an issue to Lance team today and explain what we're facing and share this proposed fix ( + the concerns) and let's see what they say.

If you think I'm being overly paranoid on this one, let me know. We've just been bitten by these knobs and OOMs to many times that I'm concerned without a proper exhaustive stack test, this is a risk.

@rerun-rmack

rerun-rmack commented Aug 18, 2026 via email

Copy link
Copy Markdown
Member Author

@rerun-rmack

rerun-rmack commented Aug 18, 2026 via email

Copy link
Copy Markdown
Member Author

@rerun-rmack

Copy link
Copy Markdown
Member Author

You're right, and it's worse than you framed it. Pushed 6bd6c56 backing it out.

LanceIndexStore::with_format_version is not maintenance-only. open_scalar_index builds one per scalar index a scan opens (scalar_logical.rs:313 is the scanner's index-query path), so hooking it to LANCE_DEFAULT_IO_BUFFER_SIZE put a query-path knob in charge of index stores. That was my mistake, not a tradeoff I'd thought about.

And the direction was backwards. We set that var to Lance's own default (2 GiB) rather than leaving it unset, so instead of letting us shrink the budget it would have raised every index store from 32 MiB x LANCE_IO_THREADS (256 MiB for us) to 2 GiB, query path included. Latent in practice, since a query-path index open does point reads and won't fill 256 MiB let alone 2 GiB, but that's a reasoning argument and your objection is precisely that you shouldn't have to take one on faith.

Worth noting the knob you're thinking of is a different one. The scanner is tuned by REDAP_LANCE_IO_BUFFER_SIZE_PER_PARTITION_MIB=32; scan.rs:317 only uses the Lance var as a min() ceiling over num_partitions_max x 32 MiB. So the var I grabbed wasn't the load-bearing one for queries either way.

Now back to max_bandwidth, unchanged from before this PR. The merge-site bound stays, via an explicit with_io_buffer_size at the one caller that needs it, so there's no behaviour change outside merge_segments. If we want a knob later it should be its own index-store variable.

Also retracting something I said earlier in this thread: I claimed the index store's scheduler "is never shared with a live search". Per-construction is right, but the scanner builds these stores too, so that was too strong.

Happy to file the upstream issue today either way. Agreed it's worth their read before we carry this.

@rerun-rmack
rerun-rmack marked this pull request as draft August 18, 2026 13:34
rerun-rmack and others added 4 commits August 18, 2026 09:40
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]>
@rerun-rmack
rerun-rmack force-pushed the rmack/index-stream-one-scheduler branch from 6bd6c56 to c65cdb1 Compare August 18, 2026 13:41
rerun-rmack and others added 2 commits August 18, 2026 15:34
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.
@rerun-rmack
rerun-rmack marked this pull request as ready for review August 18, 2026 22:37
@rerun-rmack
rerun-rmack requested a review from zehiko August 18, 2026 22:37
@rerun-rmack

Copy link
Copy Markdown
Member Author
  1. "Whole-file prefetch is unbounded memory": now bounded, instrumented, and tested. The budget is enforced per scheduler (T1: peak ≤ budget + one IOP at both 1 MiB and 32 MiB budgets, zero bypasses, at 8 and 64 threads), abandoned scans return it (T2), and backpressure_stats() means any future dispute is settled by a gauge, not RSS archaeology. Worst case on cloud defaults is ~2 GiB aggregate for the merge's sources plus the new-data scan's own budget, i.e. single-digit GiB, against the measured 216.8+ GB it replaces.
  2.  "N segments multiply it": this was the one genuinely untested claim, and T4 closed it today. The split verifiably reaches every source (exactly one rescoped store each, budget = one scan / N, floor at 32 MiB), no read path bypasses it (original schedulers provably quiescent), and it holds at both the 256 MiB and 2 GiB budget scales. The floor behavior past io_parallelism sources is documented and unit-tested.
  3.  "It leaks into the query path": structurally impossible now, not just untested. T3's panicking reader (with a positive control) proves searches can't reach whole_file_stream, and the env-var coupling that briefly did touch the query path was caught and reverted.

@zehiko

zehiko commented Sep 1, 2026

Copy link
Copy Markdown
Member

resolving in favour of #63

@zehiko zehiko closed this Sep 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants