Skip to content

feat(index): add ordered search to the B-tree index - #10346

Merged
wjones127 merged 12 commits into
lance-format:mainfrom
Ali2Arslan:feat/btree-search-ordered
Nov 4, 2026
Merged

wjones127 merged 12 commits into
lance-format:mainfrom
Ali2Arslan:feat/btree-search-ordered

Conversation

@Ali2Arslan

@Ali2Arslan Ali2Arslan commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #10250, which lays out the ordered index scan design and the PR sequence. This is O1 there.

Why

ORDER BY x LIMIT n on a column with a B-tree index still scans every matching row and keeps the top n. This PR adds the index side of an ordered scan, a stream of keys and row ids in key order that reads pages only as the consumer pulls them. A follow-up PR builds OrderedIndexScanExec on it.

What changed

  • OrderedScalarIndex::search_ordered(query, SortOptions, metrics) in lance-index-core, re-exported from lance_index::scalar beside ScalarIndex. OrderedScalarIndex is a supertrait of ScalarIndex, and a loaded index offers it through ScalarIndex::as_ordered(), which returns None by default. BTreeIndex returns Some(self). The method is synchronous, because building the stream awaits nothing, and the stream owns its index handle. The id column is _rowaddr or _rowid, matching results_are_row_addresses. The doc says the stream is complete and exact, and that a consumer that stops early owns the truncation.
  • The method takes Arrow's SortOptions because that type already holds descending and nulls_first, and B-tree training sorts with it.
  • The method takes Arc<dyn MetricsCollector> because the stream reads pages after the method returns, so the stream has to own the collector.
  • ScalarIndexPlugin::ordering_capability(index_details) returns IndexOrderingCapability::{Unordered, Bidirectional}, so a planner can decide before it loads an index. The B-tree plugin returns Bidirectional. A loaded index can still return None from as_ordered or NotSupported from search_ordered, so a planner keeps a fallback.
  • On a string index, ordered search casts each Utf8, LargeUtf8, or Utf8View literal in the query to the index's key type before it plans the walk, so the page bounds and the page predicate compare one type.
  • btree/ordered.rs walks the candidate pages forward or in reverse and moves the null run to either end. It restricts pages with the same page bounds search uses and sorts each page by key and then by id. An exclusive upper bound x < v also skips the pages whose min is v. Those pages hold no matching row, though search still reads them.
  • The walk reads the first page alone. Read-ahead starts after that page is read and then keeps at most three pages in flight. A consumer that stops after the first batch pays for one page read.
  • Before its first page read, a call does work that grows with the log of the page count, not the page count. The page-order check runs on the first ordered search of a loaded lookup, and the shared BTreeLookup keeps the verdict, so plain search never pays for it. All-row and range walks come lazily from the lookup rows. In a lookup that passes the page-order check, no two pages' key ranges overlap, so binary searches find the run of pages a range reads, and a CheckedLookup type keeps the walk from running on an unchecked lookup. Equality and IN walks collect only their matched pages.

Scope

  • Single-column B-trees with one segment. It leaves out covering values, composite keys, the exec node, and multi-segment and JSON indices, whose as_ordered returns None.
  • Equal keys come in ascending id order within a page. Training sorts by key alone, so the stream promises no tie order across pages.
  • A range unbounded at both ends is the literal true, so it returns null keys, as search does. On page stats written before Lance 0.25.2, search reports the null on the page that holds both null and non-null keys as NULL for that query. Ordered search returns that row. Fixing search is a follow-up.
  • Ordered search casts a Utf8, LargeUtf8, or Utf8View literal to the key type of a Utf8 or LargeUtf8 index. B-tree training rejects Utf8View keys. With a LargeUtf8 literal on a Utf8 index, or the reverse, search returns an Arrow error for LIKE and ranges and panics for = and IN. search sends a Utf8View prefix to its non-string branch, which marks pages as fully matching, so it returns non-null rows that do not match the prefix as an exact answer. The query parser normalizes Utf8View literals first, so only a direct SargableQuery caller reaches that branch. Fixing search is a follow-up.
  • The page that holds both null and non-null keys is read once in ASC NULLS FIRST and DESC NULLS LAST. In ASC NULLS LAST and DESC NULLS FIRST, a walk over all rows reads it twice, once for each run. Reading it once would mean holding up to a page of rows for the whole walk.
  • If the first page has no matching row, read-ahead starts during the consumer's first poll.
  • Pages are read directly, not through the page cache. Sharing the cache is a follow-up.
  • The design follows a downstream fork's ordered scan (rust/lance-index/src/scalar/btree/covering.rs and rust/lance-index-core/src/scalar.rs there), re-implemented here without its covering, tuple, and row id parts.

Blast radius

The change is additive. ScalarIndex::as_ordered and ScalarIndexPlugin::ordering_capability have defaults, and OrderedScalarIndex is a new trait, so no existing index or plugin has to change. search and the other B-tree paths do not change. A lookup out of key order, from some range-partitioned merges or from input sorted nulls last, returns NotSupported instead of a misordered stream. The error names the failed check. A page whose min sorts after its max names that page and both values. Page ids that do not increase name both ids. A max above the next page's min names both page ids and both values. Ordered search reports the lookup rows that check compares through record_comparisons, once per loaded lookup.

Verification

  • cargo test -p lance-index btree: 317 tests pass, 223 of them new. An rstest matrix checks the four direction and null pairs, six query kinds, and six index shapes against a sort of the search output. A second matrix runs LIKE, =, range, and IN with Utf8, LargeUtf8, and Utf8View literals on Utf8 and LargeUtf8 indices in both directions, against search with the literal in the key type. Before the literal cast, 30 of its 48 cells failed. Other tests cover all-null pages, an IN list with NULL that skips null-only pages, ties, page stats written before 0.25.2, rejected LIKE prefixes, the page-order error, a check that only the first ordered search on a lookup runs the page-order check, and laziness. Another test checks that the lazy range walk picks the same pages as search's page bounds, minus the pages whose min is an exclusive upper bound, for every pair of bounds around each page's keys, including ties across pages and legacy page stats. A test runs x < 2 on an index where ten pages have min 2. Both directions read one page before the first row. When the walk kept those pages, the descending walk read 11. One test counts object reads through the local store's IOTracker and checks that the first batch costs the file open plus one page.
  • On a 10,000,000-row index built with release-with-debug, once the page file's metadata is cached, the first 100 rows cost 0.04 to 0.75 ms more than opening the index and reading one page in the same run. On an idle machine that is a p50 of 3.1 to 3.3 ms. Starting the two read-ahead reads together with the first page put it at 5.5 to 5.7 ms. Under load from parallel builds, the one-page read alone rose to 5.4 ms, and the first 100 rows to 5.1 to 6.0 ms. With no cache, opening the page file alone takes about 20 ms, and ordered search costs the same as a one-page search equality (22.6 ms against 23.2 ms). These release timings were measured on an earlier main, when every call ran the page-order check.
  • Startup on a synthetic lookup of 244,141 pages, about 1 billion rows at 4,096 rows per page, in a debug build on an earlier main. A call after the first builds the stream in 3.8 µs for all rows and 20 µs for a range, as at 2,442 pages. When every call ran the page-order check and built its walk up front, a call took 54 to 90 ms there, about 100 times its cost at 2,442 pages. The first ordered search on a loaded lookup still runs the page-order check once, 30 ms in that build.
  • cargo clippy --all --tests --benches -- -D warnings, cargo fmt --all -- --check, and RUSTDOCFLAGS='-D warnings' cargo doc -p lance-index -p lance-index-core --no-deps pass.
  • ci/check_module_size.py exits 0 and warns that rust/lance-index/src/scalar/btree.rs grows from 8,741 to 8,759 lines. That file was already over 3,000 lines. The 18 added lines are the mod ordered line, the OrderedScalarIndex import and as_ordered, the plugin's ordering_capability, and the lookup's page-order field and batch equality.
  • The bench group btree_ordered_first_k builds its own index with a _rowaddr column. The shared generators in benches/common.rs still write _rowid, which B-tree training rejects, so the other groups in benches/btree.rs that train from those generators fail the same way on main. main's btree_lookup groups train their indices from those generators while the groups register, so cargo test -p lance-index --bench btree -- btree_ordered_first_k now panics in bench_lookup before it reaches this group. With the bench_lookup(c) call removed locally, that command runs all three cases and leaves no index directory behind. No release samples were recorded.

Add ScalarIndex::search_ordered, which streams keys and row ids in key order and reads index pages only as the consumer pulls them, and ScalarIndexPlugin::ordering_capability, so a planner can check support before it loads an index. The B-tree index implements both for single-segment indices, and other indices keep the NotSupported default. A B-tree lookup whose pages are out of key order returns NotSupported instead of a misordered stream.

@claude claude Bot 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.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@github-actions github-actions Bot added the A-index Vector index, linalg, tokenizer label Oct 26, 2026
@github-actions github-actions Bot added the enhancement New feature or request label Oct 26, 2026
lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 26, 2026
Ali2Arslan and others added 4 commits October 26, 2026 11:22
For `x < v`, `ValuePages::between` ended the walk at the first page whose
min is greater than `v`, so pages whose min equals `v` stayed in it. Those
pages hold only keys at or above `v`, so none of their rows match. A
descending walk reads them first, so `ORDER BY x DESC LIMIT n` on a key
with many rows equal to `v` read every one of those pages before its first
row. The walk now ends at the first page whose min is at least `v`.
`search` still keeps those pages through `pages_between`, which this change
leaves alone.

`test_ordered_range_walk_picks_the_pages_search_picks` now asserts that the
walk drops exactly the pages `search` keeps whose min is an excluded upper
bound. `test_ordered_exclusive_upper_skips_pages_at_the_bound` runs `x < 2`
on an index where ten pages have min 2. Both directions read one page
before the first row, and a full walk reads only the 21 pages whose min is
below 2. With the fix reverted, the descending walk read 11 pages before
its first row and the ascending full walk read 31.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 5877566)
The pin test splits `pages_between`'s pages into those whose min is an
excluded upper bound and those the walk must read. The variables now say
which is which.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit bf583d1)
Conflicts and adaptations:

- lance-index-core scalar.rs: keep ScalarIndex::search_ordered beside
  main's ScalarIndex::lookup and its lookup schema helpers, and merge both
  sides' arrow imports (7f9ec61).
- scalar/btree.rs: keep BTreeIndex::search_ordered beside main's
  BTreeIndex::lookup (7f9ec61).
- benches/btree.rs: merge both sides' imports (7f9ec61), and import
  DatafusionDatagenExt from lance_datafusion_exec, because lance-index no
  longer enables lance-datafusion's datagen feature (4158d49).
- scalar/btree/ordered.rs: import SendableRecordBatchStream and
  RecordBatchStreamAdapter from datafusion_physical_plan, because datafusion
  is now only a dev-dependency of lance-index (4158d49).

Co-authored-by: Cursor <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 29, 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.

No merge-blocking issues found in the single-segment ordered-search scope. The exclusive-upper-bound walk now avoids pages with no possible matches while preserving exact results; truncation remains the consumer's responsibility.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 29, 2026
@wjones127
wjones127 self-requested a review October 30, 2026 20:23

@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.

This looks good. I have some optional feedback. Otherwise I'll merge Monday.

Comment thread rust/lance-index-core/src/scalar.rs Outdated
Comment on lines +761 to +771
async fn search_ordered(
&self,
_query: Option<&dyn AnyQuery>,
_options: SortOptions,
_metrics: Arc<dyn MetricsCollector>,
) -> Result<SendableRecordBatchStream> {
Err(Error::not_supported(format!(
"ordered search is not supported by this {} index",
self.index_type()
)))
}

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.

suggestion(non-blocking): this pattern already exists with lookup, but it does seem unfortunate to provide an API that isn't supported most of the time. An alternative design might be:

pub trait OrderedScalarIndex: ScalarIndex {
    fn search_ordered(&self, query, sort: SortOptions, metrics) -> Result<SendableRecordBatchStream>;
}

// on ScalarIndex
fn as_ordered(&self) -> Option<&dyn OrderedScalarIndex> { None }

Which has the advantage of communicating directly through types that this is only supported by indexes that implement it.

Not something you have to do for this PR, but something we should consider for a future refactor.

cc @westonpace As I'm sure you're thinking of things similar to this in future planned refactors of indexes.

@Ali2Arslan Ali2Arslan Oct 30, 2026 •

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.

Yeah, I like this patten (supertraits) a lot more as well. Unfortunately I was not sure about your guys preference is and AI defaults to the patterns used in the repo :)

| ScalarValue::Utf8View(Some(text))),
) => {
let key = |text: String| match prefix {
ScalarValue::LargeUtf8(_) => ScalarValue::LargeUtf8(Some(text)),

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.

question (non-blocking): The bound type follows the prefix literal, not self.data_type. On a LargeUtf8 or Utf8View index queried with a Utf8 prefix, won't make_comparator in ValuePages::between hit a type mismatch? test_ordered_like_prefix only covers a Utf8 index. Could you add the other index types as cases?

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.

Yes, and it went beyond LIKE. With Utf8 and LargeUtf8 crossed, LIKE and ranges returned an Arrow error, and = and IN panicked. A Utf8View literal returned an error for =, range, and IN on both key types, and for LIKE on a LargeUtf8 key. f57b891 casts string literals to a string key's type before planning. test_ordered_string_literal_types covers Utf8 and LargeUtf8 keys with Utf8, LargeUtf8, and Utf8View literals for LIKE, =, range, and IN in both directions, and 30 of its 48 cells failed before the fix. B-tree training rejects Utf8View keys, so there is no Utf8View index case.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IndexOrderingCapability {
/// The index cannot stream keys in order.

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.

nitpick: A variant named None shadows Option::None under a glob import (use IndexOrderingCapability::*). Consider Unordered.

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.

Renamed to Unordered in 470f754, and the ordering_capability doctest now also checks that the bitmap plugin reports it.

Comment thread rust/lance-index/benches/btree.rs Outdated
train_btree_index(stream, store.as_ref(), DEFAULT_BTREE_BATCH_SIZE, None, None)
.await
.unwrap();
let _ = tempdir.keep();

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.

nitpick: tempdir.keep() leaks the index directory on every bench run. That's fine for a bench, but a comment saying it's intentional would help.

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.

Fixed instead of commented in 7aaead6. The bench function owns the TempDir and passes it to the builder, so the directory is deleted when the group finishes.

Ali2Arslan and others added 5 commits October 30, 2026 15:35
Ordered search compared each query literal with the B-tree's page bounds
and page predicate in the literal's own Arrow type. Those comparisons
accept only arrays of one type. A Utf8 literal on a LargeUtf8 index, or a
LargeUtf8 or Utf8View literal on a Utf8 index, failed: LIKE and range
queries returned an Arrow error, and equality and IN queries panicked in
the page lookup.

Cast every string literal in the query to the key type once, before the
walk is planned, so the page bounds and the page predicate both use it.
Literals of other types stay as they are. B-tree training rejects Utf8View
keys, so a string key is Utf8 or LargeUtf8.

test_ordered_like_prefix becomes test_ordered_string_literal_types, a
matrix over direction, key type, literal type, and query kind. Its oracle
is search with the literal in the key type. Before the fix, 30 of its 48
cells failed.

Co-authored-by: Cursor <[email protected]>
ScalarIndex::search_ordered had a NotSupported default, so every index
type carried a method that most of them cannot serve. Ordered search now
lives on OrderedScalarIndex, a supertrait of ScalarIndex, and a loaded
index offers it through ScalarIndex::as_ordered, which returns None by
default. The types now say which indices stream in key order.

BTreeIndex implements OrderedScalarIndex in btree/ordered.rs and returns
Some(self) from as_ordered. search_ordered is no longer async, because
building the stream awaits nothing. The stream still owns its index
handle and borrows nothing. The doctest, the tests, and the bench reach
ordered search through as_ordered.

LogicalScalarIndex and JsonIndex keep the default None. A multi-segment
index needs a merge across segments, and a JSON index would have to
unwrap its JsonQuery before the B-tree under it could serve the query.
Neither forwarded search_ordered before.

ScalarIndexPlugin::ordering_capability stays, so a planner can decide
before it loads an index. Its doc now says that a loaded index can still
return None from as_ordered or NotSupported from search_ordered.

Co-authored-by: Cursor <[email protected]>
A variant named None shadows Option::None under a glob import such as
use IndexOrderingCapability::*, so every bare None in that scope names
the enum variant. Unordered says what the variant means and collides
with nothing.

The ordering_capability doctest now also checks that the bitmap plugin,
which keeps the default, reports Unordered.

Co-authored-by: Cursor <[email protected]>
create_int_unique_row_addr_index called tempdir.keep(), so every bench
run left a trained index on disk. bench_ordered_first_k now owns the
TempDir and passes it to the builder. The directory lives until the
function returns, after the benchmark group finishes, and is deleted
then. The change is one line shorter than the keep() it replaces.

Co-authored-by: Cursor <[email protected]>
lance_index::scalar re-exports ScalarIndex and the other core scalar index types, so callers import the ordered search trait from the same place.

Co-authored-by: Cursor <[email protected]>
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Oct 31, 2026
Ali2Arslan and others added 2 commits November 2, 2026 08:39
Co-authored-by: Cursor <[email protected]>

# Conflicts:
#	rust/lance-index/src/scalar/registry.rs
@wjones127
wjones127 merged commit 7f8d4d0 into lance-format:main Nov 4, 2026
42 checks passed
Xuanwo added a commit that referenced this pull request Nov 13, 2026
Part of #10250, which lays out the ordered index scan design and the PR
sequence. This is O2 there.

## Why

`ORDER BY <column> LIMIT n` sorts every row today, even when a B-tree
index already holds the keys in order. This PR adds a plan node that
reads one B-tree index segment in key order and stops after `n` live
rows. It builds on the B-tree ordered search from #10346, which a loaded
index offers as `OrderedScalarIndex::search_ordered` through
`ScalarIndex::as_ordered`.

## What changed

- `OrderedIndexScanExec` streams the key and `_rowaddr` from
`search_ordered`. It drops deleted rows and rows outside the fragment
scope before they count toward `fetch`.
- The key column keeps the indexed column's name, taken from
`field_path_minimal`, so `my-col` stays `my-col`. A key under a nullable
struct is nullable.
- The node declares its sort order, supports `with_fetch`, and reports
`pages_loaded`, `rows_scanned`, `rows_deleted`, `rows_excluded`, and
`deletion_vectors_loaded`. `reset_state` starts a fresh metrics set.
- The node masks deleted rows with each fragment's deletion vector, not
with `DatasetPreFilter`. On a dataset with stable row ids,
`DatasetPreFilter` holds row ids, but the index yields row addresses.
- The node implements `ExecutionPlan::apply_expressions`. It holds no
physical expressions, so it returns `TreeNodeRecursion::Continue`, as
the other leaf scans in `io/exec` do.

## How to read it

- **`try_new` is async and fails early.** It opens the segment, takes
the index's `OrderedScalarIndex` from `as_ordered`, and calls
`search_ordered`, which checks that the lookup lists pages in key order
before it returns a stream. That check reads no data page. A planner
therefore gets `NotSupported` while it can still keep its sort. That
happens when `as_ordered` returns `None`, as it does for a bitmap index,
and when two range partitions were merged out of key order. The `None`
error names the segment, the index, its type, and the column. The node
keeps the opened index, and each execution calls `search_ordered` on it
again with its own page counter. The lookup keeps the page-order verdict
and the walk starts lazily, so only the plan-time call pays for the
check. On a synthetic 244,141-page lookup in a debug build, measured on
an earlier revision of both PRs, the plan-time call took 30 ms and the
execution call 3.6 µs for all rows and 20 µs for a range. Reopening at
execution would repeat the metadata lookup and the cache probe for an
index that cannot change under the node's dataset snapshot.
- **A newer key overlay declines the scan.** `try_new` returns
`NotSupported` naming the index, the segment, the column, and the
overlay version when a data overlay committed after the segment changes
the key column in a fragment the scan reads. Dropping the stale rows is
not enough, because a row whose new key enters the range would be
missing. An overlay on another column, an overlay the segment already
reflects, and an overlay on a fragment outside the scope do not block
the scan.
- **`query` is optional.** It is a predicate on the same column, such as
a range, and it bounds the pages the walk reads. `None` reads the whole
segment.
- **Deletion vectors load lazily.** A fragment's deletion vector loads
the first time the scan reaches one of its rows, concurrently with the
other new fragments of that round, and stays loaded for the rest of the
stream. Without a `fetch`, a round covers the whole batch. With one, the
first round covers as many in-scope rows as the fetch still needs, and
each later round doubles the in-scope rows covered, so a batch takes
O(log rows) rounds. Rows outside the fragment scope never start a round
and never count toward its size. On one 4,096-row page over 64
fragments, with consecutive keys in different fragments and one deleted
row per fragment, `fetch=1` reads 2 vectors and `fetch=10` reads 20,
where loading per batch read all 64. With only fragments 32 to 63
allowed, `fetch=1` reads 1 vector, and with every other fragment allowed
and the first three keys deleted it reads 4. With `fetch=0` it reads
none. The deletion check still runs before a row counts toward `fetch`.
- **`with_fetch` replaces the fetch.** `with_fetch(None)` clears it.
That matches DataFusion 55.2, where `SortExec::with_fetch` also
replaces, and `LimitPushdown` combines a node's current fetch with the
parent's before it calls `with_fetch`.
- **The module is `pub`.** That matches `scalar_index`, `filtered_read`,
`fts`, and the other exec modules in `exec.rs`, which the file header
marks as internal API.

## Scope

- Nothing in the scanner plans the node yet. A follow-up PR adds that.
- The node reads one segment. It rejects an older segment that stores
stable row ids instead of row addresses, so a planner can fall back to a
sort.
- It leaves out covering columns, tuple keys, pruning, search budgets,
and segment merges.

## Blast radius

The PR adds one module and changes no existing code path. Only future
callers of the node can see a difference.

## Verification

- `cargo test -p lance --lib ordered_index_scan`: 58 tests pass in 0.43
s. They cover deletions, a fetch of 0, a fetch past the end, every row
deleted, a fragment allow-list with exact `rows_deleted` and
`rows_excluded` counts, the four null orders, both row id modes, newer
and current overlays, pages out of key order, an index without ordered
search, a nested key under a nullable parent, a hyphenated column,
`reset_state`, lazy deletion-vector loads, and exact vector and row
counts on a 4,096-row page for fetches of 1, 10, and 100, no fetch, four
load rounds, and two fragment allow-lists. Run alone on one thread, each
case takes 0.01 to 0.44 s.
- With the first four keys deleted, `fetch=10` returns keys 4 to 13, and
`analyze_plan` shows `rows_deleted=4, rows_scanned=14, pages_loaded=1`.
On an earlier revision it also showed `output_batches=2` for one batch,
because the shared `InstrumentedRecordBatchStreamAdapter`
(`utils.rs:764`) and `BaselineMetrics` both register that metric. The
double count predates this PR.
- Release perf on 10,000,000 rows in 10 fragments with 10% deleted, page
size 4096, timing `try_new` through the last batch, measured on an
earlier revision. The baseline is a one-page equality `search` plus the
deletion vectors the first batch needs, loaded concurrently. With keys
in fragment order, the first batch needs 1 vector, and cold `fetch=10`
p50 is 2.25 to 3.27 ms against a baseline of 2.10 to 2.65 ms, a ratio of
1.07 to 1.28. With keys spread so the first batch reaches all 10
fragments, the ratio is 1.22 to 1.34. That revision predates the
fetch-sized prefix and the last changes to #10346. The current code adds
one `as_ordered` call per `search_ordered` call, not per batch.
- `cargo test -p lance --doc ordered_index_scan` passes 1 test. `cargo
test -p lance-index btree` passes 330 tests. `cargo test -p lance --lib`
passes 9,558 tests, with 9 ignored. `cargo clippy --all --tests
--benches -- -D warnings`, `cargo fmt --all -- --check`, and
`RUSTDOCFLAGS="-D warnings" cargo doc -p lance --no-deps` pass.

## Integration

Current main (`7112e250`) is merged into the branch (`1c96431`). The
only conflict was the module list in `io/exec.rs`, where `mod
prefilter_union` and `pub mod ordered_index_scan` now coexist.

`IndexMetadata::fields` may carry a covered index's carried suffix, so a
single-key B-tree that declares covering fields was rejected as a
multi-column index. The node now selects its key with `keyed_field()`
and filters newer overlays by `keyed_fields()`; the shared staleness
gate stays dependency-wide.
`carried_columns_are_not_keys_and_do_not_block_key_order` reads a
covered segment and an overlay on its carried column.

At `e676d6a6e`, `ordered_index_scan` passes 59 lib tests and 1 doctest,
`lance-index btree` passes 371 tests, and workspace clippy (`-D
warnings`), `cargo fmt --all -- --check`, and `RUSTDOCFLAGS="-D
warnings" cargo doc -p lance --no-deps` pass. The 58/330 counts and the
performance numbers above are the author's, measured on earlier
revisions; this integration did not re-measure them.

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: Xuanwo <[email protected]>
Xuanwo pushed a commit that referenced this pull request Dec 2, 2026
Part of #10250, which lays out the ordered index scan design and the PR
sequence. This is O3 there.

## Why

`ORDER BY <column> LIMIT n` sorts every row, even when a B-tree on that
column already holds the keys in order. This PR reads the B-tree in key
order instead and stops after `offset + limit` live rows. It builds on
#10777, which merged and added `OrderedIndexScanExec` over the B-tree
ordered search from #10346.

## What changed

- `create_plan_impl` in `scanner/plan.rs` asks the new
`Scanner::try_ordered_read` for an `OrderedIndexScanExec` before it
plans a filtered read. When it gets one, the plan has no `SortExec`. The
existing take runs on top of the node, and the limit either stays above
it or folds into the node's `fetch`.
- The scan reads in order only when it orders by one top-level column,
has a limit, and has no filter or a filter that the same B-tree answers
exactly, on a dataset without stable row IDs. The B-tree must be keyed
on that column alone and have one segment that covers every fragment. In
every other case, including any error while it opens the index, the plan
is the same as before.
- The read picks a B-tree by its key, `IndexMetadata::keyed_field()`.
Since #10662, a covered B-tree lists its carried columns after its key
in `IndexMetadata::fields`, so the read compares the key the same way
`OrderedIndexScanExec::try_new` does after #10777's covered-segment fix.
A single-key B-tree with covering columns serves the read. An overlay on
a carried column keeps the ordered read, and an overlay on the key makes
the scan sort.
- The `ordered_index` mode controls the read, with `auto` (the default)
and `off`. Rust has `OrderedIndexMode::{Off, Auto}` and
`Scanner::ordered_index(mode)`. Python takes `ordered_index="off"` on
`scanner`, `to_table`, `to_pandas`, `to_batches`, and
`ScannerBuilder.ordered_index`. Java takes
`ScanOptions.Builder.orderedIndex(ScanOptions.OrderedIndexMode.OFF)`.
Python passes its string and Java passes `toRustString()`, and Rust
parses both. The parser ignores ASCII case and rejects any other name
with an error that lists `off, auto`. `off` plans the same sort as a
scan without this PR. A later PR in #10250 adds `required`, which fails
instead of sorting.
- The ordered read skips every index named in `ignored_scalar_indices`.
If no other B-tree on the order column qualifies, the scan sorts, as it
does for the other declines. Ignoring an index on another column leaves
the plan unchanged. The Rust, Python, and Java docs for the ignore
option and for the `ordered_index` mode say that an ignored index never
serves the read.
- The `ordered_limit` bench group in `scalar_index.rs` times `auto`,
`off`, and a declined query.
- `OrderedIndexScanExec` now builds its key field from the column's
Arrow field, so a projected key keeps its field metadata.
- `OrderedIndexScanExec` now caps each batch at the task context's batch
size, which the scanner sets from `batch_size`, so the ordered read
keeps the scan's documented limit. Before, it emitted one batch per
B-tree page, up to 4,096 rows by default, and nothing above it split a
batch by rows. The take that reads non-key columns splits batches only
to meet a byte limit (`batch_size_bytes`). Otherwise it merges
consecutive batches while the merged batch stays within its target and
passes a larger batch through whole. The projection and limit work batch
by batch. The node now slices a longer batch, and the slices share the
page's buffers instead of copying them. The take's target is the
scanner's `batch_size` when one is set, so it may merge slices but never
past `batch_size`. With `batch_size` unset, the cap is DataFusion's
default of 8,192 rows, which a default page of 4,096 rows never reaches,
so nothing is sliced.
- The `order_by`, `scan_in_order`, and `ordering` docs name the ordered
index read as the exception to reading in parallel, sorting, and reading
all data before the first batch.
- This head merges main at `47f14ab03`. The Python binding, its stub,
and the call that passes the scanner options by position keep #11669's
`ordered_results` next to this PR's `ordered_index`. The Java async
scanner keeps #11482's optional `batch_readahead` next to the
`ordered_index` argument. The test that removes an index's files reaches
the object store through `dataset.table_state`, where main moved it.

## Scope

- One index segment over the whole dataset. Merging segments, residual
filters, unindexed fragments, and the `required` mode are later PRs.
- The scan also sorts for a fragment list other than the dataset's, row
prefilters, `include_deleted_rows`, nested keys, and the legacy file
format. A narrower fragment list could make the walk skip most of the
index.
- The scan also sorts on a dataset with stable row IDs. On such a
dataset, an update can add the fragment it writes to the index's
fragment bitmap without indexing its rows. An update by pylance 13.0.0
does this (#10351). The coverage check then passes, and the ordered read
skips the updated rows. A filter on that column already misses them, and
the ordered read would spread the miss to every default `ORDER BY ...
LIMIT`. Follow-up: lift this decline once #10351 has a fence.

## Blast radius

Every scan that orders by a B-tree column with a limit now reads the
index by default, whether or not the B-tree declares covering columns.
Rows with equal keys can come back in a different order than the sort
returned, so a limit that cuts through a run of equal keys or nulls can
return different rows from that run. If the index fails to open, the
scan sorts and logs a warning, or a debug message when the error is
`NotSupported`. If an index data file goes missing after the index
opens, the scan fails with `Not found`, as a filter on that column
already does. `ordered_index="off"` (`OrderedIndexMode.OFF` in Java)
restores the sort.

## Verification

- `cargo test -p lance --lib ordered`: 160 passed, 0 failed, 1 ignored
(a full-text-search reuse case that links its issue). 61 of them are
this PR's `scanner::ordered` cases. The plan and row cases start from
three fragments with deleted rows. Among the index shapes, one appends a
fourth fragment, one moves updated rows into a new fragment, and
`MissingIndexFiles` deletes nothing. The 5 batch-size cases write three
fragments without deletions. Every decline case checks that the plan
equals the `off` plan and that the rows match under `auto` and `off`.
The vector and full-text search declines run with `ordered_results` both
true and false, because the ordered read serves only plain scans.
- `cargo test -p lance --lib scanner` passes 1,760 tests with 1 ignored.
`cargo test -p lance --lib` passes 12,260 tests with 9 ignored and none
failed.
- `test_ordered_read_honors_batch_size` is the review's case. It writes
48 rows in three fragments, indexes `ts`, and reads `ORDER BY ts LIMIT
16` with `batch_size(2)` and only `ts` projected, through
`Scanner::try_into_stream`. It checks that the plan has
`OrderedIndexScan` and no `SortExec`, that no batch has more than 2
rows, and that the batches concatenate to 0 through 15. The other four
cases vary that read: one also takes `v`, one uses `LIMIT 15`, one
filters on `ts >= 5`, and one takes `v` with `batch_size(8)` from 4-row
pages. With the cap reverted alone, the 4 cases whose page holds more
rows than `batch_size` fail with batch sizes `[15]` or `[16]`, and the
4-row-page case passes either way. The taken-column case fails with one
16-row batch too, because the take passes a batch larger than its target
through whole. Each case runs in under 0.2 s.
- `test_ordered_read_serves_a_covered_index_by_its_key` declares `id` as
a covering column of the B-tree on `ts`. The scan plans
`OrderedIndexScan: index=ts_idx` with the same rows as `off`. After an
overlay changes `id` in one of the first ten rows, it still reads in
order and returns the new value. After an overlay on `ts`, it plans the
same sort as `off`. With the candidate loop comparing
`IndexMetadata::fields` to the order column instead of `keyed_field()`,
only this test fails, because `auto` plans `SortExec: TopK(fetch=10)`.
- Before the batch-size cases were added, three more reverts showed that
the tests pin each guard. Without the ignore-list check in the candidate
loop, only
`test_ordered_read_skips_ignored_indices::case_1_order_column_index`
fails, because `auto` plans `OrderedIndexScan: index=ts_idx` where `off`
plans `SortExec: TopK(fetch=10)`. With `off` dropped from the decline,
23 of the 54 cases fail. Those are the cases where `auto` plans
`OrderedIndexScan`, because `off` then plans it too. With the parser
mapping any unknown name to `auto`, the 3 rejection cases fail
(`sorted`, the empty string, and ` auto`).
- On an earlier head of this branch, the stable-row-ID case rebuilt the
#10351 state in Rust. It updates six rows into a new fragment, then
commits the index with a bitmap that claims that fragment. Without the
decline, the case failed on the plan, and the ordered read returned keys
`[10, 12, 13, 14, 15, 17, 18, 19, 20, 21]` where the sort returned `[3,
4, 6, 7, 8, 9, 10, 12, 13, 14]`.
- On an earlier head, a build with seven guards removed, from the sort
skip to the `NotSupported` fallback, failed 32 tests, each one
predicted. The 9 that still passed decline for structural reasons.
- `cargo fmt --all -- --check` and `cargo clippy --all --tests --benches
-- -D warnings` are clean. `python ci/check_module_size.py` passes and
adds no exception, with a warning that `python/src/dataset.rs` grows
from 5,244 to 5,249 lines. `cargo test -p lance --doc ordered` passes
all 4 doctests it selects: this PR's for `OrderedIndexMode` and
`Scanner::ordered_index`, and the existing ones for
`OrderedIndexScanExec` and `Scanner::ordered_results`. `RUSTDOCFLAGS="-D
warnings" cargo doc -p lance --no-deps` passes.
- `cargo test -p lance --bench scalar_index` runs the whole bench in
test mode and reports `Success` for all 8 cases, including the 3
`ordered_limit` cases.
- Python: `uv run make lint` is clean: ruff, pyright with 0 errors,
`cargo fmt -- --check`, and `cargo clippy -- -D warnings`. `pytest
python/tests/test_scalar_index.py` passes the 5 cases of this PR: the
default, `ordered_index="off"`, `use_scalar_index=False`, an unknown
mode, and the review's batch-size case through `to_batches()`.
- Java: `./mvnw test -Dskip.build.jni=true
-Dtest=ScannerTest,AsyncScannerTest,JNITest`, against a
`liblance_jni.so` that `cargo build` built from this head, passes 101
tests, including `testOrderedIndex` and `testParseOrderedIndexMode`.
`testOrderedIndex` checks that both modes return the same rows and that
only `auto` reports the `pages_loaded` counter.
`testParseOrderedIndexMode` sends every Java constant and `sorted`
through the Rust parser. `cargo test` for `java/lance-jni` passes 39
tests. `./mvnw spotless:check`, plus `cargo fmt` and `cargo clippy
--tests -- -D warnings` for `java/lance-jni`, are clean.

Each perf case below ran at `d4dab02fc`, an earlier head of this branch,
before it merged main at `c36ee5445`. The cases were not rerun after
that merge, the merge of main at `47f14ab03`, or the batch-size cap. The
bench reads `LIMIT 100` with the default batch size, so the cap never
slices there, and a slice shares its buffers rather than copying them.
At this head, the 3 `ordered_limit` cases pass in test mode. Each ran in
three interleaved rounds after one warmup, and every timed call returned
100 rows. The declined query adds the filter `id >= 0`, which the B-tree
on `ts` cannot answer, so both modes sort.

- The S3 runs used LocalStack 4.0 and a debug pylance build of that
head, on 10,000,000 rows in 10 fragments with no stable row IDs. On a
dataset where 1% of `ts` values are null, `ORDER BY ts DESC LIMIT 100`
returns the same 100 rows under `auto` and `off`. There the ordered read
reads 811 KB, against 59 MB for the sort. On the bench's dataset shape,
`auto` p50 is 0.212 s against 1.392 s for `off`, or 0.153 times. The
declined query takes 1.957 s under `auto` against 2.025 s under `off`,
or 0.966 times. Most of the ordered read's time is the take, 77 range
reads from the object store after a 10.5 ms index walk that loads one
page.
- The local runs used a `release-with-debug` build of the
`ordered_limit` bench at that head, on its dataset of 10,000,000 rows in
10 fragments with no stable row IDs. A scratch loop in place of
criterion interleaved the ordered and declined queries under both modes.
`auto` p50 is 9.01 ms against 70.1 ms for `off`, or 0.129 times. The
declined query takes 84.9 ms under `auto` against 88.7 ms under `off`,
or 0.957 times. A second run of the same binary gave ratios of 0.131 and
0.972. Most of the ordered read's time is the take, 98 range reads from
the page cache after a 1.1 ms index walk that loads one page.

The plan with this PR:

```text
lance 16.0.0-beta.6, 100,000 rows in 10 fragments, with deletions
>>> ds.scanner(order_by=order_by, limit=10).explain_plan()
ProjectionExec: expr=[ts@0 as ts, payload@2 as payload]
  LanceRead: uri=<tmp>/data, projection=[payload], source=stream(_rowaddr)
    OrderedIndexScan: index=ts_idx, order=[ts DESC NULLS LAST], fetch=10

>>> ds.scanner(order_by=order_by, limit=10, ordered_index='off').explain_plan()
SortExec: TopK(fetch=10), expr=[ts@0 DESC NULLS LAST], preserve_partitioning=[false]
  LanceRead: uri=<tmp>/data, projection=[ts, payload], num_fragments=10, range_before=None, range_after=None, row_id=false, row_addr=false, full_filter=--, refine_filter=--

>>> ts of the first 10 rows, ordered read: [99990, 99989, 99988, 99987, 99986, 99985, 99984, 99983, 99982, 99981]
>>> equal to ordered_index='off': True
>>> batch sizes of to_batches(columns=['ts'], ..., batch_size=4): [4, 4, 2]
>>> ds.scanner(..., ordered_index='sorted'): ValueError: Invalid user input: unknown ordered_index mode 'sorted', expected one of: off, auto, <source location>
```

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

Labels

A-index Vector index, linalg, tokenizer enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants