Skip to content

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

Merged
zehiko merged 8 commits into
release-10.0.0from
zehiko/index-stream-one-scheduler-r10
Sep 4, 2026
Merged

zehiko merged 8 commits into
release-10.0.0from
zehiko/index-stream-one-scheduler-r10

Conversation

@zehiko

@zehiko zehiko commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Port of #36 to release-10.0.0.

What this does

BTreeIndex's end-to-end scan paths went through IndexReaderStream, which issues an
independent read_record_batch per 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 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 = 4096 and batches corresponding to pages, the per-batch
setup cost grows as roughly sum over segments of (rows_per_segment / zone_size)^2 — so
it hurts most on wide segments, which is exactly production's shape.

The change adds IndexReader::whole_file_stream, which returns a single-decode-plan
stream or None, plus a stream_index_file helper that prefers it and falls back to the
old 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_lookups and merge_pages build one stream per partition
    against 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_size comes from the index file's own metadata, so it is clamped rather than
    cast — a u64 multiple of 2^32 used to truncate to 0 and silently retrain an empty
    index.
  • IndexStore::with_io_buffer_size (default no-op) lets merge_segments split one
    scan'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-credited
    and the count of requests admitted through the priority <= min_in_flight path despite
    an exhausted budget — the two numbers that make the budget claims checkable rather than
    arguable.
  • Tests T1–T4 assert the three memory objections raised in review on perf(scalar): build one decode plan per index scan, not one per batch #36 (budget
    respected, budget returned on an abandoned scan, query path never takes the whole-file
    path) and that merge_segments really 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
1543c9f moved only 4.3s on a 17-minute run, which rules out schema-clone and
fragment-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 page
files, sampling the concurrent aggregate rather than summing per-scheduler high-water marks.

N merge_segments unrescoped fan-out
8 288 MiB 2060 MiB
24 864 MiB 5643 MiB
  • The merge's split holds: N x 36 MiB once the 32 MiB floor binds (32 plus a measured ~4 MiB
    bypass overshoot, well inside the documented budget + one split request). The floor binds for
    every N >= io_parallelism, so the aggregate is linear in N — ~7 GiB at num_indices_to_merge=200.
    Conserving one scan's budget only holds up to N = io_parallelism; past that a caller needs to
    merge in passes.
  • calculate_included_frags is not rescoped. LogicalScalarIndex runs one whole-file scan per
    segment concurrently, each at a full store budget: N x 256 MiB. Reachable only via
    migrate_indices' corrupt-bitmap gate, and it now logs at INFO when it fires. remap is also
    unrescoped but runs serially, so it is a floor raise rather than a multiplication.
  • T1/T2/T4 assert the right properties but their 40k-row step fixture is under 500 KB against
    1-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 SchedulerPurpose and a process-wide bytes_in_flight / peak_bytes_in_flight gauge so
this is observable in production; index stores are tagged Index.

🤖 Generated with Claude Code

@rerun-rmack rerun-rmack left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thank you!

rerun-rmack and others added 8 commits September 3, 2026 16:13
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]>
@zehiko
zehiko force-pushed the zehiko/index-stream-one-scheduler-r10 branch from d063560 to d69baec Compare September 3, 2026 14:20
@zehiko
zehiko merged commit a919935 into release-10.0.0 Sep 4, 2026
39 checks passed
@amunra amunra added lance fork 10.0.0 Landed on the release-10.0.0 fork line upstreamable change Belongs upstream, but is not there yet labels Sep 16, 2026
@amunra

amunra commented Oct 6, 2026

Copy link
Copy Markdown

Closed the upstream port of this PR's scheduler instrumentation, lance-format/lance#9738, as not needed.

ScanScheduler::backpressure_stats() has no consumer outside this PR's own btree tests: reality never calls it, no metric is derived from it, and there are no dashboards, alerts or Prometheus series for any of its fields. Upstream it would have landed as an API nobody invokes.

The four test call sites here all read max_bytes_in_flight; priority_bypass_admissions is never read anywhere. If the single-decode-plan work is ever taken upstream, the instrumentation should go with it in that PR, where it has a caller.

@amunra amunra added permanent fork change No upstream path; Rerun-specific by construction superseded upstream Upstream solved this another way, or the need went away; drop when rebasing past it and removed upstreamable change Belongs upstream, but is not there yet labels Oct 6, 2026
westonpace pushed a commit to lance-format/lance 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]>
@amunra amunra removed the permanent fork change No upstream path; Rerun-specific by construction label Oct 14, 2026
@amunra

amunra commented Oct 14, 2026

Copy link
Copy Markdown

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 main independently while our port (lance-format/lance#9289) was open, so lance-format#9289 was closed:

  • #9463 streams btree pages sequentially for update, remap and prewarm (merged 2026-09-22)
  • #9462 assembles btree search results once instead of per page (merged 2026-09-22)
  • #9310 coalesces btree page loads into one read_ranges request (merged 2026-09-25)

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 merge_segments held one full budget per source. That is now upstream as #9761 (merged 2026-10-13, c177003b5).

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 first.store.io_parallelism(), where upstream takes the maximum over the sources actually read — first can be a segment the filter skips. Prefer upstream's.

(The scheduler-instrumentation side-branch is covered by the comment above.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-encoding A-index lance fork 10.0.0 Landed on the release-10.0.0 fork line performance superseded upstream Upstream solved this another way, or the need went away; drop when rebasing past it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants