Skip to content

perf(encoding): backport per-page, range-scoped page initialization - #112

Merged
amunra merged 3 commits into
release-10.0.0from
zeljko/r10-lazy-page-init
Nov 16, 2026
Merged

amunra merged 3 commits into
release-10.0.0from
zeljko/r10-lazy-page-init

Conversation

@zehiko

@zehiko zehiko commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

This PR was written by Claude Opus 5.5 (an AI assistant), on behalf of @zehiko, to fix a Metastore querier OOM on btree index lookups.

Related

What

Backports range-scoped, per-page page initialization from upstream.

On release-10.0.0, StructuralPrimitiveFieldScheduler::initialize initializes every page of a column and caches the result as one per-column entry.
A btree index lookup reads one page of the index's page_data file but pays for all of them: on 10x, 7,567 pages and ~108 MB per cold initialization of the chunk_partition_id index, and two ~300 MB entries for chunk_id.
The initialization is not single-flight, so concurrent cold lookups each build their own copy.
Entries above the metadata cache's hot target are dropped silently, so the chunk_id ones are rebuilt on every request.

After this backport a read initializes only the pages its requested ranges overlap, and caches each page under its own key.
The btree lookup path (BTreeIndex::lookup_page → read_record_batch → FileReader::read_range → schedule_and_decode → DecodeBatchScheduler::try_new_with_ranges(Some(ranges))) already passes its ranges down, so it gets the lazy path without further changes.

Fork commit Upstream commit Upstream PR How
297342e 156d7e7 lance-format#7465 adapted, see below
d8b1217 525136d lance-format#9278 adapted, see below

Adaptations for fork-only code (the dictionary-page pruning from #87):

  • MiniBlock dictionary initialization calls the fork's BlockDecompressor::decompress(LanceBuffer, ..), which takes the buffer directly rather than an Option.
  • CoreFieldDecoderStrategy::rows_that_may_contain_any keeps its eager behaviour: it builds every page scheduler (try_new, deprecated upstream, #[allow(deprecated)] here) and initializes with None, since pruning inspects every page.
  • StructuralPrimitiveFieldScheduler::rows_that_may_contain_any reads page bounds from row_range, which replaced num_rows.

80987d397 updates the fork's test_rows_that_may_contain_any to the per-page cache key.

Each backport commit carries (cherry picked from commit …).
Please rebase-merge (not squash), so the backports can be dropped on the next rebase onto upstream.

Not included: single-flight for page initialization (upstream still does get_with_key then insert_with_key; the herd now costs one page per request instead of the whole column), and upstream's dictionary-size cap on write (lance-format#9939).

Confirmed on a stack: D1 and D2 on 10x no longer OOM the querier at their spec concurrency (see Testing).

Testing

  • cargo test -p lance-encoding --lib: 605 passed
  • cargo test -p lance-file --lib: 142 passed
  • cargo test -p lance-index --lib btree: 61 passed
  • cargo clippy -p lance-encoding -p lance-file -p lance-index -p lance --tests -- -D warnings: clean.

Load tests on a 1 CU stack (querier 3 CPU / 6 GiB), abc-130k-10x (195M chunk rows, 1.43M segments), reality branch zeljko/abc130k-10x-cs-limits, before (dfaa7b8) and after this patch (b2b023c); 5-minute runs:

Workload Before After
D1 10x, 64 workers querier OOM-killed (also at 32) 1,773 samples/s, 0 failed, querier peak 1.48 GiB
D2 10x, 56 workers querier OOM-killed (also at 28) 2,852 samples/s, 0 failed, querier peak 2.7 GiB
D1 10x, 16 workers 1,615 samples/s, querier peak ~3.5 GiB —

For reference, on 1x: D1 2,748 samples/s at 64 workers (querier peak 1.07 GiB), D2 3,654 at 56 workers (1.4 GiB).
Both 10x runs saturate the querier CPU (95%); the remaining gap to 1x is CPU, not memory.

Not fixed by this PR: D1 with sample shuffle still OOM-kills the querier, on 1x as well.
That is a request flood (~950 concurrent FindChunks), not index initialization.

Not measured: a local before/after probe of a single cold btree lookup.

Compatibility

On-disk format unchanged.
API: StructuralFieldScheduler::initialize and DecodeBatchScheduler::try_new gain a requested_ranges argument (breaking for direct callers of lance-encoding; no callers in reality).
FieldDataCacheKey is replaced by per-page PageDataCacheKey, so metadata cached by an older build is not reused (in-memory only).

🤖 Generated with Claude Code

@zehiko
zehiko marked this pull request as ready for review November 13, 2026 14:23
@zehiko zehiko added the upstream backport Already upstream, on a release later than ours label Nov 13, 2026
@amunra

amunra commented Nov 13, 2026 •

Copy link
Copy Markdown

This review was written by Claude Fable 5.2 (an AI assistant) on behalf of Adam, from three independent review passes at 80987d397: port fidelity, composition with fork code, and test port quality.

Summary: the port is faithful and upstream's tests came over intact, but the backport breaks one vector-index build path in the fork. That one should be fixed before merge.

PRs this review refers to:

PR What it is Relation to this PR
lance-format#7465 Initialize only the page metadata a read will touch Backported here as 297342e07
lance-format#9278 Build page schedulers only for requested pages Backported here as d8b12175b
lance-format#8941 Use the writer's in-memory shuffle offsets instead of re-reading them Upstream only, not in the fork; see Blocking
#87 Prune dictionary pages based on an equality filter Fork only; source of the three adaptations
#63 Build one decode plan per index scan, not one per batch Fork only; its test and docs are now stale

Blocking

Building a vector index with exactly one partition now fails once the build spills to disk more than once.

Background: an IVF (inverted file) vector index groups vectors into partitions. While building one, Lance writes the rows to a temporary "shuffle" file in batches, and writes a second file of offsets saying where each partition's rows sit inside each batch. TwoFileShuffleReader::partition_ranges (rust/lance-index/src/vector/v3/shuffler.rs:693-711) reads that offsets file to find one partition's rows.

  • What goes wrong. For batch b, partition p and P partitions in total, it requests offset rows b*P+p-1 and b*P+p. With P == 1 and two or more batches, the requested rows are [0, 0, 1, 1, ...]: each row is asked for twice.
  • Why this PR triggers it. perf(encoding)!: initialize only the page metadata a read will touch lance-format/lance#7465 replaces a debug_assert! that take indices are strictly increasing with a hard InvalidInput error (RequestedRows::indices_to_ranges, rust/lance-encoding/src/decoder.rs:2183). Before, release builds accepted the duplicates. The check runs before any scheduler is built, so it applies to every file format version.
  • When it is reached. A one-partition index build whose shuffle writes at least two batches. A batch is flushed at 128 MiB by default.
  • Why upstream is not affected in the same way. Since fix(index): use writer-side IVF shuffle offsets instead of re-decoding lance-format/lance#8941, upstream keeps the offsets in memory while writing and normally never reads the offsets file back. The fork does not have that change, so the file read is its only path. Upstream's fallback read uses row ranges instead of indices; I could not identify the PR that introduced it (the local upstream history is shallow). That fallback also repeats a range when there is one partition, so the same problem may be latent upstream.
  • Evidence. Found by reading both sites; not reproduced by running. No existing test covers one partition with multiple batches.
  • Fix options. Smallest: deduplicate the requested rows in partition_ranges and index into the result, with a test for one partition and multiple batches. Alternative: backport fix(index): use writer-side IVF shuffle offsets instead of re-decoding lance-format/lance#8941.

Should fix before merge

  1. A test is red for two commits, then fixed by the third. At 297342e07 and d8b12175b, test_rows_that_may_contain_any (added by perf(scan): prune dictionary pages based on equality filter #87) still asserts on FieldDataCacheKey, which nothing inserts any more, so its cases should fail until 80987d397 (by reading; not run at those commits). Fold 80987d397 into 297342e07.
  2. Description corrections.
    • DecodeBatchScheduler::try_new keeps its signature and delegates to a new pub(crate) try_new_with_ranges. Only StructuralFieldScheduler::initialize breaks.
    • FieldDataCacheKey and CachedFieldData remain as unused public types, as upstream.
    • Missing from Compatibility: StructuralPrimitiveFieldScheduler::try_new is deprecated, try_new_lazy is new public API, and the strict validation below.
  3. Strict validation of requested rows is a behaviour change (from perf(encoding)!: initialize only the page metadata a read will touch lance-format/lance#7465, the same change behind the blocking item). Duplicate or unsorted take indices (all file format versions, the legacy 2.0 format included) and overlapping or unordered ranges (2.1 and later) now return InvalidInput; release builds previously tolerated them. User input reaches this unchecked through python/src/file.rs:943-952 (LanceFileReader.take_rows) and java/lance-jni/src/file_reader.rs:326. Downstream callers of take_rows / read_ranges / read_stream_projected have not been audited for strictly increasing input.

Port fidelity

The three adaptations listed in the description are the only production-code deviations from lance-format#7465 and lance-format#9278. Each is forced by #87 and is correct. No upstream hunks or files were dropped. Test-only deviations: FakePageScheduler gains may_contain_any / can_rule_out_values (the trait methods #87 added have no default implementations), plus import adjustments.

Tests

Upstream's tests are ported without dropped cases, weakened assertions, #[ignore] or resized inputs. At HEAD: lance-encoding --lib 605 passed, lance-file --lib 142 passed, and test_blob_cache_key_distinguishes_views plus the #87 prune tests in lance pass. The 80987d397 assertion is stronger than what it replaces (every page's cache key rather than one per-column key).

Gaps:

  • Nothing asserts that readers pass the requested ranges down. The two tests that check which pages were initialized (test_initialize_coalesces_missed_page_metadata, initialize_builds_only_requested_page_schedulers) use synthetic pages. By reading, replacing Some(&requested_ranges) with None at decoder.rs:2415 and :2545 would leave every test green. The B-tree index page lookup this PR targets is therefore unguarded. Upstream has the same gap. Suggested: write a multi-page file in lance-file, do one ranged read on a fresh cache, and assert one cached page entry per column or a bound on the number of read operations.
  • Cache sharing between the perf(scan): prune dictionary pages based on equality filter #87 prune path and the read path is covered in one order only (prune, then a full-range read, in lance-file's test_rows_that_may_contain_any). Ranged read then prune, and prune then single-page read, are untested.
  • test_data_stream_builds_one_decode_plan (from perf(scalar): build one decode plan per index scan, not one per batch #63) asserts fewer than 64 read operations, against a per-batch figure measured when every decode plan initialized every page. This PR removes that cost, so the margin is smaller than the test's comment says.

Latent, not blocking

Checked and sound

Not run: lance-index tests, clippy, Python and Java.

Ali2Arslan and others added 3 commits November 16, 2026 14:42
…ance-format#7465)

The structural decoder's `StructuralFieldScheduler::initialize` eagerly
initializes **every** page in a column before scheduling, even when the
read only touches one page. For a column with thousands of large,
non-coalescing pages (e.g. a BTree leaf scan that reads one leaf), this
means paying metadata IO proportional to the page count regardless of
how few rows are actually requested.

This PR makes page-metadata initialization **range-scoped and
per-page**:

- `DecodeBatchScheduler::try_new` and
`StructuralFieldScheduler::initialize` now take an optional
`requested_ranges: Option<Arc<[Range<u64>]>>` — the top-level row ranges
that will later be scheduled. The structural path initializes only the
pages those ranges overlap (`pages_overlapping_ranges`). `None`
preserves the prior eager behavior.
- The page-scheduler `initialize` is split into `init_ranges()` (declare
the byte ranges the page needs) and `init_from_buffers(buffers, io)`
(finish initialization from those bytes). The field scheduler
concatenates the misses' ranges into a **single** `submit_request` so
adjacent ranges coalesce into shared GETs instead of one request per
page.
- Page metadata is cached per page via `PageDataCacheKey { column_index,
page_index, view_tag }` (replacing the per-column `FieldDataCacheKey`).
`view_tag` is retained so a column decoded under two shapes (blob
descriptor `Struct<pos,size>` vs raw `LargeBinary`) can't collide on
cached state.
- Nested schedulers forward ranges consistently with their existing
`schedule_ranges`: lists/maps/structs pass the top-level ranges through
unchanged; fixed-size-list scales by `dimension`. The requested ranges
are always a **superset** of what `schedule_ranges`/`schedule_take`
later touch, so any page a read schedules was initialized here.

Net effect: a cold point/range read's metadata IO is invariant to the
column's total page count.

- [x] `cargo test -p lance-encoding --lib` (393 passed) — the round-trip
encoding harness now exercises **both** the eager path (full scan,
`None`) and the lazy path (range reads and scattered takes pass their
`requested_ranges`).
- [x] New unit test `test_initialize_coalesces_missed_page_metadata`: an
N-page cache miss issues exactly **one** `submit_request` carrying every
page's metadata range (not one request per page).
- [x] Updated FullZip page-scheduler tests to the `init_ranges` /
`init_from_buffers` split.
- [x] `cargo test -p lance-file --lib` (76 passed).
- [x] `cargo test -p lance --lib
dataset::blob::tests::test_blob_cache_key_distinguishes_views` —
confirms the per-page key still distinguishes blob decoder views.
- [x] `cargo fmt --all` and `cargo clippy -p lance-encoding -p
lance-file --tests --benches -- -D warnings` clean.

Made with [Cursor](https://cursor.com)

---------

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 156d7e7)

Backport conflicts resolved for fork-only code:
- MiniBlock dictionary init calls the fork's `BlockDecompressor::decompress(LanceBuffer, ..)`.
- The dictionary-page prune check (#87) initializes with `None` (all pages), as before.
- `rows_that_may_contain_any` reads page bounds from `row_range`.
…-format#9278)

Every `read_stream`/`read_range` on a structural (2.1+) file rebuilt a
boxed `StructuralPageScheduler` for **every page of every projected
column** in `StructuralPrimitiveFieldScheduler::try_new`, cloning buffer
tables and instantiating decompressors. lance-format#7465 made page *initialization*
range-scoped, but construction stayed O(pages). For a column with
hundreds of thousands of pages this is a large fixed cost per read,
which is exactly the pattern IVF prewarm follows (one read per partition
window; 4,069+ windows over a 620,881-page `auxiliary.idx` in the
September 10B RQ benchmark) and that nprobes=1 queries pay per query.
The captured CPU profile was dominated by malloc/free of
`PageInfoAndScheduler`/`MiniBlockScheduler`.

Linear: [OSS-2276](https://linear.app/lancedb/issue/OSS-2276)

- `try_new` now stores only the per-page row boundaries
(`page_row_ends`, one `u64` per page) plus a `PageSchedulerSource`
(column info, decompression strategy, target field).
- `initialize(Some(ranges))` builds schedulers only for the pages those
ranges touch, merged in page order; `initialize(None)` keeps the eager
behaviour and builds every page.
- Range-to-page mapping works from `page_row_ends`, so it no longer
needs built schedulers.
- Scheduling a page that was not covered by the initialized ranges
returns `Error::Internal` with a descriptive message instead of
panicking on an uninitialized page.

- The lazy scheduler must own its column info and decompression
strategy, so the new constructor is `try_new_lazy(Arc<ColumnInfo>,
Arc<dyn DecompressionStrategy>, ..)`. The existing `try_new(&ColumnInfo,
&dyn DecompressionStrategy, ..)` keeps its signature and eager behaviour
and is marked `#[deprecated]`.

Matched local micro-benchmark against `main` (3a12096): a v2.1 file
with 5 `UInt8` columns, 131,072 pages per column (655,360 pages total),
read from local disk, reading successive disjoint row windows with
`read_stream`, 200 reads per pass, two repetitions per binary. Both
binaries built from the same harness with `cargo build --release`;
numbers below are the second repetition's warm pass (page metadata
cached), lower is better. Machine: Apple Silicon Mac, single process.

| Scenario / metric | Baseline | This PR | Benefit |
| --- | ---: | ---: | ---: |
| 64K-row read (256 pages/column touched), mean latency | 83.0 ms | 19.5
ms | 4.3x speedup |
| 64K-row read, p99 latency | 106.5 ms | 22.5 ms | 4.7x speedup |
| 4K-row read (16 pages/column touched), mean latency | 68.0 ms | 7.8 ms
| 8.7x speedup |
| 4K-row read, p99 latency | 79.2 ms | 11.2 ms | 7.1x speedup |

Cold-pass numbers (first touch of each window's page metadata) show the
same ratios. The baseline's ~68 ms floor is the whole-file scheduler
construction; this PR removes it.

Same index as the Linear issue (RQ1 1-bit, 244,140 partitions, 1B rows,
`auxiliary.idx` 113.8 GB), copied to local EBS on an r8i.8xlarge (32
vCPU, 247 GiB RAM), `LANCE_CPU_THREADS=30`, 192 GiB index cache, both
wheels built from source with `--profile release`. Cold = page cache
dropped before the run. Lower is better for time, higher for fill rate.

| Scenario / metric | Baseline (`main` 3a12096) | This PR | Benefit |
| --- | ---: | ---: | ---: |
| Cold prewarm of 118.0 GB, 64 MiB windows, wall time | > 3,600 s (timed
out at 104.4 GB, 88%) | 153.8 s | > 23x speedup |
| Cold prewarm, average cache fill rate | 29 MB/s (decaying from 77 to
15 MB/s) | 767 MB/s | 26x |
| Cold prewarm, process CPU | 1 core at 100% for the whole hour | 285
CPU-s over 154 s | n/a |
| Warm page cache prewarm, 64 MiB windows | not run (baseline too slow)
| 61.1 s (1,933 MB/s, 0 physical reads) | n/a |
| Warm page cache prewarm, 1 GiB windows (issue config) | not run | 60.9
s | n/a |
| 64 nprobes=1 queries without prewarm (partition loads on demand) |
19.0 s | 6.9 s | 2.8x speedup |

Peak RSS after prewarm was 121 GB on this PR (cache 118.0 GB). The 64
nprobes=1, k=10 query results (row ids and float32 distances) hash
identically on `main` and this PR, both with and without prewarm. Raw
summaries and 5-second progress logs:
`s3://mmlb-us-east-1/rq-benchmark/results/20260916-oss-2276-prewarm-ab/`.

**Not yet verified:** QPS under load on the 10B index. The remaining
~7.7 ms fixed cost per read at this page count is two O(pages) walks
over immutable `ColumnInfo` (the `page_row_ends` prefix sum here and
`normalized_column_num_rows` in lance-file's read-length validation);
caching those per file is a follow-up.

- New test `initialize_builds_only_requested_page_schedulers`:
construction builds nothing; range-scoped initialize builds exactly the
touched pages in order; scheduling an uncovered page errors instead of
panicking; widening the request adds only new pages; `None` builds all
and drops the source.
- Existing lazy-initialization tests adapted to the new constructor.
- `cargo test -p lance-encoding` (1826 passed), `cargo test -p
lance-file` (182 passed), `cargo test -p lance --lib ivf` (277 passed),
`cargo check --workspace --tests --benches`, `cargo fmt --all --
--check`, `cargo clippy --all --tests --benches -- -D warnings`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5.1 <[email protected]>
(cherry picked from commit 525136d)

Backport conflict resolved for fork-only code: the dictionary-page prune
helpers (#87) are kept next to the new lazy constructors. The prune check
still builds every page with the eager `try_new`, since it inspects every page.
The page metadata cache is keyed per page since the lance-format#7465 backport.
@amunra
amunra force-pushed the zeljko/r10-lazy-page-init branch from 80987d3 to f2b743f Compare November 16, 2026 13:47
@amunra

amunra commented Nov 16, 2026

Copy link
Copy Markdown

Follow-up to the review above, written by Claude Fable 5.2 (an AI assistant) on behalf of Adam. Re-assessed at f2b743ff0, after the rebase onto #113.

Summary: nothing blocking remains. Three small items are still open: the commit split, the description, and a missing label.

Corrections to the review

Status of each item

Item Status
Blocking: vector index build with one partition fails Resolved by #113, now underneath this PR. The eight shuffler tests pass at f2b743ff0, including the new single-partition one.
1. Test red for two commits Open, now confirmed by running. At ef73858ac, all 12 cases of test_rows_that_may_contain_any fail (primitive.rs:10470). Fold f2b743ff0 into ef73858ac.
2. Description corrections Open. The Compatibility section is unchanged.
3. Strict validation of requested rows Open as a documentation item. The one in-tree caller found to violate it is fixed by #113. Python LanceFileReader.take_rows and the Java file reader still pass user input through unchecked.
Test gaps Unchanged, not blocking.
Latent items Unchanged, not blocking.

New since the review

Checked at f2b743ff0

cargo test -p lance-encoding --lib: 605 passed. cargo test -p lance-index --lib two_file_shuffler: 8 passed. Not rerun after the rebase: clippy, lance-file and lance tests.

@amunra amunra added the lance fork 10.0.0 Landed on the release-10.0.0 fork line label Nov 16, 2026
@amunra
amunra merged commit f35fe84 into release-10.0.0 Nov 16, 2026
40 of 41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-encoding lance fork 10.0.0 Landed on the release-10.0.0 fork line performance upstream backport Already upstream, on a release later than ours

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants