Skip to content

perf(encoding)!: initialize only the page metadata a read will touch - #7465

Merged
wjones127 merged 6 commits into
lance-format:mainfrom
Ali2Arslan:feat/lazy-page-metadata-init
Sep 16, 2026
Merged

wjones127 merged 6 commits into
lance-format:mainfrom
Ali2Arslan:feat/lazy-page-metadata-init

Conversation

@Ali2Arslan

Copy link
Copy Markdown
Contributor

Summary

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.

Test plan

  • 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).
  • 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).
  • Updated FullZip page-scheduler tests to the init_ranges / init_from_buffers split.
  • cargo test -p lance-file --lib (76 passed).
  • cargo test -p lance --lib dataset::blob::tests::test_blob_cache_key_distinguishes_views — confirms the per-page key still distinguishes blob decoder views.
  • cargo fmt --all and cargo clippy -p lance-encoding -p lance-file --tests --benches -- -D warnings clean.

Made with Cursor

@github-actions github-actions Bot added A-encoding Encoding, IO, file reader/writer performance labels Jun 25, 2026
@Ali2Arslan
Ali2Arslan marked this pull request as ready for review June 25, 2026 16:26

@Ali2Arslan Ali2Arslan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Another option is to initialize the page's metadata on first touch (at schedule_ranges time - make it truley lazy) instead of this approach, but then we lose the possible coalescing benefits, so let me know if you guys have a preference on either. Thanks!

@wjones127
wjones127 self-requested a review June 29, 2026 23:44
@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@HolyMiss

HolyMiss commented Aug 9, 2026

Copy link
Copy Markdown

@Ali2Arslan Are there any plans to merge it? It would be very beneficial for our scenario.

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ Gate recommendation: request changes.

The existing cache-granularity concern is confirmed: range scoping solves the cold-read I/O problem, but the new layout turns one column cache record into one record per touched page. On full scans or broad page reuse, cache-key and backend overhead grows with page count while Moka capacity accounting weighs only the cached value; stateless pages also receive entries.

Keep initialization range-scoped, but batch small page states into bounded groups and skip stateless entries (or use an equivalent compact column-scoped structure). Cover both sparse reads and full scans with representative cache-entry and footprint evidence so the I/O win does not move the cost into unaccounted cache overhead.

Please mark this PR with the breaking-change label.

@lance-gatekeeper lance-gatekeeper Bot added the K-changes Latest Gatekeeper recommendation requests changes. label Aug 10, 2026
Thread requested row ranges through structural schedulers so reads initialize and cache only overlapping page metadata. Preserve existing public entry points, validate range conversion and nested scaling, recover invalid cache entries, and skip stateless pages.

Batch cold metadata reads in sorted file order and restore returned buffers to each page declaration order before initialization.
@Ali2Arslan
Ali2Arslan force-pushed the feat/lazy-page-metadata-init branch from dd100bb to b41b972 Compare August 10, 2026 18:25
@Ali2Arslan

Ali2Arslan commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@lance-gatekeeper reevaluate against new commit:

Stateful pages still create individual backend records, so generic per-entry bookkeeping scales with the number of touched pages. However, that residual overhead is much smaller than the reviewed string-key/stateless-entry behavior.

@lance-gatekeeper lance-gatekeeper Bot removed the K-changes Latest Gatekeeper recommendation requests changes. label Aug 10, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

The earlier cache-granularity blocker is addressed on this revision: fixed-size keys are capacity-accounted, stateless pages are skipped, and the production metadata cache defaults to QuickCache.

A non-blocking risk remains for very broad reads: full scans still perform one cache operation and retain one record per stateful page, without representative full-scan latency/RSS evidence. If production workloads show pressure, bounded grouping is the clearest mitigation.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Aug 10, 2026
@Ali2Arslan
Ali2Arslan requested a review from wjones127 August 13, 2026 16:19
@Xuanwo

Xuanwo commented Aug 14, 2026

Copy link
Copy Markdown
Member

Thank you @Ali2Arslan for working on this! I believe there is a tradeoff between scan and point read. I agree the review from lance-gatekeeper here. Can you try perform some bench to show the different compared to main branch?

@Ali2Arslan

Copy link
Copy Markdown
Contributor Author

@Xuanwo @wjones127 — benchmarks for the scan-vs-point-read tradeoff, plus the cache-entry/footprint evidence the gate asked for.

Headline: the selective-read win is large and unambiguous (cold point reads go from P metadata requests to 1, and even warm point reads get ~35% cheaper), the cache cost has an exact closed form of +32 accounted bytes per stateful page, and a full-scan wall-clock regression is below measurement resolution on my hardware — I would not claim one either way from this data.

Method

de2c80fe (this PR's parent) vs b41b972f, with byte-identical harness source compiled separately against each revision. New lance-file bench:

  • memory:// object store, ScanScheduler::default_for_testing(), production LanceEncodingsIo wrapped in a counting EncodingsIo that records every submit_request (calls / ranges / bytes).
  • Opened via FileReader::try_open_with_file_metadata so file metadata loads once outside the measured window; inline_scheduling: Some(true); LanceCache::with_capacity(512 MiB) (Moka backend, so eviction weight includes the 16-byte InternalCacheKey).
  • Fixture: one non-nullable UInt64 column, data_cache_bytes = 32 KiB, 4096 rows per written batch. Asserted after opening: exactly one page per batch, exactly 4096 rows per page, uniform metadata-buffer size.
  • Reads go through the public FileReader::read_tasks path with ReadBatchParams::{Ranges, Indices, RangeFull}; streams fully consumed, row counts asserted.
  • 4 formats (2.0 / 2.1 / 2.2 / 2.3) × 8 page counts (1 → 4096) × 5 selections = 160 cases per revision, each measured in three cache states: disabled, cold-enabled, warm.
  • Page-metadata I/O is attributed as cold minus warm for the same selection. Disabled-cache and cold-enabled I/O are asserted equal in every case, and a warm read is asserted never to miss.

Hardware: AMD Ryzen 9 3900X (12C/24T), WSL2, rustc 1.97.0, bench profile.

Deterministic results

Let P = pages in the column, T = pages the requested rows touch, b = metadata bytes per page. Across all 120 structural cases these held with no exceptions:

parent de2c80fe this PR b41b972f
metadata submit_request calls P 1
metadata ranges P T
metadata bytes b·P b·T
cold cache misses 1 T
warm cache hits 1 T
retained cache entries 1 T

v2.0 performs zero structural page-metadata I/O and retains zero cache entries on both revisions — it takes the RootScheduler::Array path, which never calls initialize. That makes it a clean control, which matters for the latency section below.

Pages touched on the 4096-page fixture: point 1, 1% range 42, sparse-64 64, 10% range 410, full scan 4096. Point-read metadata is invariant to P on this PR (16 B in 1 call at every page count from 1 to 4096) and linear in P on the parent (16 B / 1 call at P=1, rising to 65,536 B / 4,096 calls at P=4096).

b depends on the data, not the format

Worth recording so these numbers aren't over-generalized: b = (miniblock chunks per page) × (2 bytes for v2.1, 4 for v2.2/v2.3). Chunks per page follows from MAX_MINIBLOCK_BYTES (8186), so it tracks compressibility:

column values/chunk chunks/page v2.1 b v2.2 / v2.3 b
64-bit incompressible 512 8 16 B 32 B
≤63-bit, bit-packed 1024 4 8 B 16 B

Both layouts are measured below, since the relative cache cost depends on which one you're in.

Cache footprint: exactly +32 B per stateful page

Full scan, 4096 pages, accounted LanceCache bytes (Lance's own DeepSizeOf weight, not RSS):

per-page state parent this PR delta per page: parent → PR
172 B (4 chunks/page) 770,104 901,120 +17.0% 188 → 220
188 B (8 chunks/page) 835,640 966,656 +15.7% 204 → 236

The marginal cost is a constant, and it decomposes cleanly:

  • parent, per page: 16 (the Arc slot in the whole-column Vec) + state
  • this PR, per page: 16 (Arc in CachedPage) + state + 16 (two Arc atomics) + 16 (InternalCacheKey)

Difference: +32 accounted bytes per stateful page, independent of format and data. The relative penalty is 32 / (state + 16), so it grows as pages get smaller — which is the honest statement of @wjones127's concern, and it also quantifies the bounded-grouping fix directly: batching G pages into one entry costs 32/G bytes per page, so G = 8 takes full-scan overhead from ~16% to ~2%. That is orthogonal to the range-scoping here and easy to add as a follow-up if we want it.

Physical IOPs

Sampling lance_io::iops_counter() (post-coalescing storage requests) around each read, 4096-page fixture:

selection T parent IOPs PR IOPs
point 1 4096 1
1% range 42 4096 42
sparse-64 64 4096 64
10% range 410 4096 410
full scan 4096 4096 4096

One clarification on my own PR description, which claims the misses' ranges "coalesce into shared GETs": they do not, in the normal case. Page metadata buffers sit roughly a page apart, well outside the scheduler's 4 KiB coalescing window, so the batched submit_request issues exactly T physical requests. Full scan is 4096 → 4096 — unchanged, not batched. The benefit is entirely T ≪ P, not coalescing. That also means the win grows on real object storage, where per-request cost dominates, and that the single-request batching is a scheduling-overhead optimization rather than an I/O one.

Latency

Two independent passes of both revisions, 20 samples, 2 s warmup, 5 s measurement, 4096 pages / 16,777,216 rows. Percentages are PR vs parent, shown per pass so the spread is visible:

format selection empty cache (pass 1 / pass 2) warm cache (pass 1 / pass 2)
v2.0 — control point +43.4% / −31.1% +25.9% / −44.2%
v2.0 — control 1% range +25.5% / −37.4% +2.9% / −35.0%
v2.0 — control full scan +5.5% / −9.7% −1.3% / −17.2%
v2.1 point −92.0% / −94.6% −30.9% / −44.0%
v2.1 1% range −80.1% / −88.7% −25.4% / −45.4%
v2.1 sparse-64 −88.7% / −93.5% −35.8% / −73.4%
v2.1 10% range −41.1% / −59.2% −15.8% / −34.0%
v2.1 full scan +0.6% / −38.8% +3.3% / −1.7%
v2.2 point −91.0% / −91.5% −35.0% / −30.6%
v2.2 1% range −80.5% / −86.1% −21.2% / −31.9%
v2.2 sparse-64 −89.1% / −90.0% −34.1% / −38.8%
v2.2 10% range −31.9% / −45.9% −4.0% / −15.2%
v2.2 full scan −10.0% / −5.8% −1.5% / −5.6%
v2.3 point −90.9% / −91.0% −41.9% / −45.6%
v2.3 1% range −82.8% / −80.1% −23.6% / −24.9%
v2.3 sparse-64 −89.8% / −88.4% −37.0% / −33.1%
v2.3 10% range −45.9% / −38.9% −13.0% / −6.9%
v2.3 full scan +7.0% / −3.4% +5.9% / −3.9%

What this does and does not establish:

  1. Selective reads: solid. −80% to −95% cold on every structural format, reproduced in both passes, while the control moves the opposite direction in pass 1. Far outside any plausible noise.
  2. Warm selective reads improve too — a second, separate win. The parent's initialize calls load() on all P page schedulers even on a cache hit, so a warm point read on a 4096-page column still does 4096 Arc clones and downcasts before scheduling one page. This PR does T. That is the −25% to −55% warm column, and it is not an I/O effect at all.
  3. Full scan: no conclusion available. Structural full-scan deltas span −38.8% to +7.0%, and the v2.0 control — provably executing identical code — spans +5.5% to −9.7% on the same benchmark. Same-binary drift between passes reached 50% on the full scan and >100% on the small cases. Any ±10% full-scan claim, in either direction, is below resolution here. The established parts of the full-scan cost are the deterministic ones: +32 B/page of accounted cache and 4096 → 4096 IOPs.
  4. The benefit does not vanish at 10% selectivity, at least not where per-request cost is non-trivial: −32% to −59% cold. That is the expected shape, since the 10% read still reads 410 pages of metadata instead of 4096 — a 10× reduction in both bytes and storage requests.

Where that leaves the PR

Range scoping is a large, reliable win for selective access on both cold and warm caches, and it is exactly neutral for v2.0. The cost is deterministic and small in absolute terms: one extra cache record and +32 accounted bytes per stateful page, with no full-scan latency penalty I can measure. If the ~16% full-scan footprint growth is judged too much, bounded grouping reduces it to ~2% at G = 8 without touching the range-scoping logic — happy to fold that in here or do it as a follow-up, whichever you prefer.

I can push the harness as a bench target if it's worth keeping; the operation-count table above is exact, so it doubles as a cheap regression test for the initialization contract.

@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Aug 25, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

The new benchmark evidence closes the earlier request-count and cache-weight gaps: for the tested structural layouts, selective reads reduce metadata work from all pages to touched pages, while full scans retain the same physical metadata-I/O count. The measured retained-cache trade-off is about 16% for the 4–8-chunk/page fixtures (a marginal +32 accounted bytes per stateful page at scale).

The remaining non-blocking risk is physical memory and broad-scan overhead outside Lances eviction accounting: backend bookkeeping, peak/transient allocations, and stable full-scan latency were not measured reliably. Bounded grouping remains the clearest follow-up if production memory pressure warrants it.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Aug 25, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Sep 10, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

The latest follow-up preserves the range-scoped design while removing duplicate work: requested indices are normalized once, initialization selects only deduplicated touched page IDs, and scheduling retains the checked row ranges. The lance-encoding library suite passes on this revision.

The remaining non-blocking risk is unchanged: full scans still perform and retain per-stateful-page cache work, while backend bookkeeping, peak/transient memory, and stable broad-scan latency remain unmeasured. Bounded grouping remains the clearest mitigation if production memory pressure warrants it.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 11, 2026
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 14, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

The main-branch merge preserves the previously reviewed range-scoped implementation: the base-to-head patch ID is unchanged, and the current encoding suite plus the blob cache-view regression pass, including main’s adjacent nullable-struct decoder changes.

The remaining non-blocking risk is unchanged: full scans still perform and retain per-stateful-page cache work, while backend bookkeeping, peak/transient memory, and stable broad-scan latency remain unmeasured. Bounded grouping remains the clearest mitigation if production memory pressure warrants it.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 14, 2026
@lance-gatekeeper lance-gatekeeper Bot removed K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 15, 2026

@lance-gatekeeper lance-gatekeeper Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Gate recommendation: approve with a non-blocking risk.

The latest main merge does not touch the PR-modified files, the base-to-head patch ID is unchanged, and the encoding library suite passes on this revision.

The remaining non-blocking risk is unchanged: broad scans still perform and retain per-stateful-page cache work, while backend bookkeeping, peak/transient memory, and stable full-scan latency remain unmeasured. Bounded grouping remains the clearest mitigation if production memory pressure warrants it.

@lance-gatekeeper lance-gatekeeper Bot added K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. labels Sep 15, 2026

@wjones127 wjones127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for addressing my feedback. This looks great!

@wjones127
wjones127 merged commit 156d7e7 into lance-format:main Sep 16, 2026
39 of 41 checks passed
@Ali2Arslan
Ali2Arslan deleted the feat/lazy-page-metadata-init branch September 16, 2026 03:06
BubbleCal added a commit that referenced this pull request Sep 16, 2026
`StructuralPrimitiveFieldScheduler::try_new` built a boxed page scheduler
for every page of a column on every read, cloning buffer tables and
instantiating decompressors, even after #7465 made initialization
range-scoped. A column with hundreds of thousands of pages paid this fixed
cost for each small read, which is exactly the pattern IVF prewarm follows
(one `read_stream` per partition window) and nprobes=1 queries follow.

Add `try_new_lazy`, which stores only the per-page row boundaries at
construction and builds page schedulers in `initialize` for the pages the
requested ranges touch (or all pages when no ranges are given). The decoder
now uses it. The existing `try_new` keeps its signature and eager behaviour
and is deprecated. Scheduling a page that was not covered by the
initialized ranges returns `Error::Internal` instead of panicking on an
uninitialized page.

Linear: OSS-2276

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Xuanwo pushed a commit that referenced this pull request Sep 16, 2026
## Problem

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. #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)

## Change

- `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]`.

## Performance

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.

### End-to-end: prewarming one 1B IVF_RQ segment

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.

## Validation

- 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]>
zehiko pushed a commit to rerun-io/lance that referenced this pull request Nov 16, 2026
`TwoFileShuffleReader::partition_ranges` takes up to two rows of the offsets
file per write batch: the offset that ends the previous partition and
the offset that ends this one. With a single partition and more than
one write batch those rows coincide between consecutive batches, so the
take asked for `[0, 0, 1, 1, ...]`.

The file reader requires strictly increasing take indices. It checks
that with a `debug_assert!` today, so debug builds panic, and
lance-format#7465 turns the check into an `InvalidInput` error in
every build.

Request each offset row once and resolve each batch's range by position
in the result.


Claude-Session: https://claude.ai/code/session_01Y5gh2Y1wnv7hxuU8CUFARy
amunra pushed a commit to rerun-io/lance that referenced this pull request Nov 16, 2026
…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`.
amunra pushed a commit to rerun-io/lance that referenced this pull request Nov 16, 2026
…-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.
amunra pushed a commit to rerun-io/lance that referenced this pull request Nov 16, 2026
The page metadata cache is keyed per page since the lance-format#7465 backport.
amunra pushed a commit to rerun-io/lance that referenced this pull request Nov 16, 2026
…112)

* perf(encoding)!: initialize only the page metadata a read will touch (lance-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`.

* perf(encoding): build page schedulers only for requested pages (lance-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.

* test(encoding): check per-page cache keys after a prune check

The page metadata cache is keyed per page since the lance-format#7465 backport.

---------

Co-authored-by: Ali Arslan <[email protected]>
Co-authored-by: Yang Cen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-encoding Encoding, IO, file reader/writer breaking-change K-approved Latest Gatekeeper recommendation permits acceptance. K-risk Latest Gatekeeper recommendation includes a non-blocking risk. performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants