Skip to content

perf(scan): prune dictionary pages based on equality filter - #87

Merged
ilya-zlobintsev merged 12 commits into
release-10.0.0from
dictionary-page-pruning
Oct 26, 2026
Merged

ilya-zlobintsev merged 12 commits into
release-10.0.0from
dictionary-page-pruning

Conversation

@ilya-zlobintsev

@ilya-zlobintsev ilya-zlobintsev commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

For columns with many repeating values, lance uses dictionary encoding, storing a dictionary per page within each fragment.

Previously, if you did a simple matching filter like id = "a" or id in ("a", "b"), it would go through the whole read path of materializing the dictionary into an array, only to then hash the values of the array to compare them with the filter.

This PR adds a pruning optimization where it checks the dictionaries right away to exclude pages which are known to not have the filtered values, and only does the whole decode/materialization step otherwise. This is only applied for string/binary columns with dictionary encoding, anything else falls back to the normal path. Fragments with a pre 2.1 format, or ones with overlays, are also skipped.

@ilya-zlobintsev ilya-zlobintsev added the upstreamable change Belongs upstream, but is not there yet label Oct 20, 2026
@ilya-zlobintsev ilya-zlobintsev added the lance fork 10.0.0 Landed on the release-10.0.0 fork line label Oct 20, 2026
@ilya-zlobintsev
ilya-zlobintsev force-pushed the dictionary-page-pruning branch from 768162c to f5ed226 Compare October 20, 2026 09:28
@amunra
amunra requested a balanced review from Copilot October 20, 2026 09:59
ilya-zlobintsev and others added 4 commits October 20, 2026 12:59
Mini-block pages with a dictionary can tell when none of a set of values
occurs in them. `CoreFieldDecoderStrategy::rows_that_may_contain_any` turns
that into the row ranges of a column that may hold any of the values, loading
page metadata through the same cache key a read of the column uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ProjectedFileReader::rows_that_may_contain_any` finds a column's metadata
under full or indexed file metadata and runs the encoding-level lookup with
the reader's decoder config, I/O scheduler and per-file cache, so the read
that follows reuses the loaded page metadata.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FragmentReader::rows_that_may_contain_any` delegates to the data file that
stores the field. Fields carried by a data overlay are not checked, since the
base file's dictionaries don't list the values an overlay substitutes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Before reading a fragment, `read_fragment` takes the filter's `=`, `IN` and
`OR`-of-`=` conditions on string/binary columns (via DataFusion's
`LiteralGuarantee`) and drops the ranges of pages whose dictionary holds none
of the values. Rows that remain still go through the full filter; a fragment
with nothing left is not read. Conditions with a NULL literal, other types,
or a failing lookup are skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Sequential metadata loading introduces a cold-scan startup regression for multi-column filters.

1 open issue
What changed in this PR

Adds dictionary-based page pruning to Lance’s filtered scans, avoiding full decoding when pages cannot match string or binary equality filters.

Changes:

  • Propagates dictionary checks through decoder, file, and fragment readers.
  • Applies pruning before filtered reads, with legacy and overlay fallbacks.
  • Adds coverage for matching values, nulls, caching, and unsupported cases.
File Description
rust/​lance/​src/​io/​exec/​filtered_read.rs Applies pruning to scan ranges.
rust/​lance/​src/​dataset/​fragment.rs Exposes overlay-aware fragment checks.
rust/​lance-file/​src/​reader.rs Connects file metadata to pruning.
rust/​lance-encoding/​src/​encodings/​logical/​primitive.rs Checks dictionaries and builds retained ranges.
rust/​lance-encoding/​src/​decoder.rs Coordinates supported-column pruning.

Review effort: Balanced

Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
Comment thread rust/lance/src/io/exec/filtered_read.rs Resolved
This is done the same way as on reads. Concurrency is limited at the
lower level by the IO scheduler.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Malformed dictionary offsets can panic during pruning instead of following normal corruption-error handling.

2 open issues

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Cross-layer pruning affects query-result correctness and needs runtime validation and human review.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment on lines +1967 to +1976
fn variable_width_contains_any<O: ArrowNativeType>(
data: &[u8],
offsets: &[O],
values: &HashSet<&[u8]>,
) -> bool {
offsets.windows(2).any(|bounds| {
data.get(bounds[0].as_usize()..bounds[1].as_usize())
.is_none_or(|value| values.contains(value))
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude says that hashing here might be needlessly expensive and suggests structural equality instead and provided an example impl:


/// Above this many sought values, hashing each dictionary entry once beats comparing it
/// against every value.
const LINEAR_SCAN_MAX_VALUES: usize = 8;

/// The values an equality filter looks for, in the form that is fastest to probe.
pub(crate) enum SoughtValues<'a> {
    /// Slice equality compares lengths first, so a mismatched entry costs one compare
    /// and no hashing.
    Few(&'a [&'a [u8]]),
    Many(HashSet<&'a [u8]>),
}

impl<'a> SoughtValues<'a> {
    pub(crate) fn new(values: &'a [&'a [u8]]) -> Self {
        if values.len() <= LINEAR_SCAN_MAX_VALUES {
            Self::Few(values)
        } else {
            Self::Many(values.iter().copied().collect())
        }
    }

    fn contains(&self, entry: &[u8]) -> bool {
        match self {
            Self::Few(values) => values.iter().any(|value| *value == entry),
            Self::Many(values) => values.contains(entry),
        }
    }
}

fn variable_width_contains_any<O: ArrowNativeType>(
    data: &[u8],
    offsets: &[O],
    values: &SoughtValues<'_>,
) -> bool {
    offsets.windows(2).any(|bounds| {
        data.get(bounds[0].as_usize()..bounds[1].as_usize())
            .is_none_or(|entry| values.contains(entry))
    })
}

What changes around it:

  • StructuralPageScheduler::may_contain_any takes &SoughtValues<'_> instead of &HashSet<&[u8]>. Eight implementors, all mechanical, and the seven that ignore the argument do not care about its type.
  • CoreFieldDecoderStrategy::rows_that_may_contain_any at decoder.rs:654 builds SoughtValues::new(values) where it builds the set today. For the common case that is now zero allocations per call. For a long
    IN list it is the same HashSet as before.
  • Behaviour is identical, including the empty-set case, which still prunes every dictionary page, and the corrupt-offset case, which still answers "may contain".

Expected effect on a 100,000-entry page with a single-literal miss: from roughly one SipHash per entry, a few milliseconds, to one length compare per entry, well under a millisecond. Honest framing: that is
small against the tens of milliseconds a pruned page saves in decode, and most dictionary pages are far smaller than the cap. It is worth doing because it removes the only per-entry loop the PR adds and
costs nothing in complexity, not because it will show up in a benchmark.

One optional extra while in there: reading the offsets with chunks_exact(8) and u64::from_le_bytes instead of borrow_to_typed_slice:: removes the misaligned-copy branch for LargeUtf8 entirely. Separate
change, same function.

✻ Cooked for 1m 4s · done 12:27 PM

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Initially I wanted to be smarter about this and move out the HashSet construction to happen once per scan, so this cost isn't an issue in the first place, but that requires more logic on the planning stage and a lot more plumbing to get it in. Maybe upstream will point me in the right direction once I submit the PR there.

So In the end, I implemented this suggestion 🙂


/// The rows of the field with `field_id` that may hold any of `values`, `None` when this
/// file can't tell (see [`ProjectedFileReader::rows_that_may_contain_any`]).
fn rows_that_may_contain_any<'a>(

@amunra amunra Oct 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ditto, I think this should not be a default trait. There's only three impls anyhow (v2_adapter::Reader, V1Reader and NullReader).

  • The v2 reader logic exists already
  • The V1 reader should return futures::future::ready(Ok(None)).boxed()
  • And arguably the null reader should return Some(vec![]).

@amunra

amunra commented Oct 21, 2026

Copy link
Copy Markdown

Possibly this or a follow-up PR

I think there's a more elegant and more generic way to express this PR. One that would help with additional query types, rather than just exact matches.

The current impl is tied to one operator and if we wanted to support BETWEEN or <, the approach would bloat a lot of methods.
Instead the logic in rust/lance/src/io/exec/filtered_read.rs that deals with evaluating the predicate could just ask the page what values it knows about.

pub enum PageValues<'a> {
    /// Every non-null value on the page is in this array. No nulls in the array.
    /// Dictionary entries, or the single scalar of a constant page.
    Exactly(&'a dyn Array),
    /// The page has no non-null values.
    Empty,
    /// Nothing is known. The page may hold anything.
    Unknown,
}
trait StructuralPageScheduler {
    fn known_values(&self) -> PageValues<'_>;
}

This would expose things at the lowest level.

Then a generalisation of rows_that_may_contain_any could express the match:

pub trait ValuePredicate: Send + Sync {
    fn any_may_match(&self, values: &dyn Array) -> Result<bool>;
}

Then, glue with DataFusion:

use datafusion_physical_expr::PhysicalExpr;

struct PhysicalExprColumnPredicate {
    expr: Arc<dyn PhysicalExpr>,
    schema: SchemaRef,
}

impl ValuePredicate for PhysicalExprColumnPredicate {
    fn any_may_match(&self, values: &dyn Array) -> Result<bool> {
        // RecordBatch wants an owned ArrayRef. to_data() is a shallow clone, the
        // buffers are refcounted, so this is one small allocation and no copy.
        let values = make_array(values.to_data());
        let batch = RecordBatch::try_new(self.schema.clone(), vec![values])?;
        let mask = self.expr.evaluate(&batch)?.into_array(batch.num_rows())?;
        Ok(mask.as_boolean().true_count() > 0)
    }
}

@ilya-zlobintsev ilya-zlobintsev added permanent fork change No upstream path; Rerun-specific by construction and removed upstreamable change Belongs upstream, but is not there yet labels Oct 26, 2026

@amunra amunra left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approving for our own internal fork use.

Kindly follow up with a more generic implementation that can be accepted upstream. The approach taken here is conceptually valid, but I don't believe would scale to other query operations, as such would be difficult to upstream.

See #87 (comment)

@ilya-zlobintsev
ilya-zlobintsev merged commit 9764da3 into release-10.0.0 Oct 26, 2026
40 checks passed
@ilya-zlobintsev ilya-zlobintsev added upstreamable change Belongs upstream, but is not there yet and removed permanent fork change No upstream path; Rerun-specific by construction labels Nov 12, 2026
@ilya-zlobintsev

Copy link
Copy Markdown
Member Author

Upstream submission: lance-format#10991

amunra pushed a commit 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 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 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-deps A-encoding A-java A-python lance fork 10.0.0 Landed on the release-10.0.0 fork line performance upstreamable change Belongs upstream, but is not there yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants