Repository navigation
feat(scanner): support unordered vector and full-text search results - #11669
Merged
Merged
Conversation
BubbleCal
marked this pull request as ready for review
December 1, 2026 04:27
There was a problem hiding this comment.
Claude Code Review
This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.
Tip: disable this comment in your organization's Code Review settings.
Contributor
There was a problem hiding this comment.
✅ Gate recommendation: approve.
No merge-blocking issue found. Local tests preserved ranked-page membership and row/score/payload attachment across multiple index segments, stable IDs, deletions, and an unindexed tail. Positive-offset pages and explicit column ordering were unchanged.
Xuanwo
approved these changes
Dec 1, 2026
5 of 7 tasks
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> ``` ---------
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add
Scanner::ordered_results(bool)and the Pythonordered_resultskeyword for vector and full-text search. The default returns results in rank order. Callers consuming hits as a set can opt into any delivery order. The search retains its existing scoring, cutoff tie handling, explicit column order and positive-offset pagination.For eligible terminal queries, the ANN selector partitions narrow candidates at the original distance/row-ID cutoff and BM25 emits its final heap directly. Wide fixed-width projections read a bounded window of selected keys in physical order. Each selected row retains its score and projected columns. If the ANN selector cannot reserve its scratch space, the query uses the original DataFusion sort.
Validation
Managed Linux passed six Rust regression tests, full workspace clippy with tests and benches, and the Python package lint target. Public Python scanner tests cover vector and BM25 rank membership, positive offsets, explicit sort, tombstones and an unindexed tail. The duplicate-key integration test checks per-occurrence scores, query-side metadata and wide payload bytes while counting active decoder tasks across multiple physical windows. Its second variant uses stable IDs without physical addresses.
The benchmark compares the base default at
65e422aabwithordered_results=Falseat35b6c6598. Both use the official Linux x86-64 wheels from the same CI workflow. The frozen S3 table has 241,679 live rows, 16 IVF_RQ and BM25 segments, 64-dimensional vectors, 5,167 deleted rows and a 3,456-byte projected column. A dedicated AWS m7i.12xlarge ran two AB/BA pairs with 16 CPUs and one synchronous request per process. Cold uses a fresh dataset session. Hot runs one warmup. TTFT measures time to the first batch. Each query ran to EOF and validated the projected payload. The comparison reports median values across the two fresh processes per arm. Lower values are better.All 24 V1 trials passed the expected-plan, cgroup, drain and semantic checks. All scored row IDs and projected bytes matched. The three base and PR default physical plans were identical. For filtered IVF_RQ at k=500, the two warm EOF pairs varied from 60.8 to 325.8 ms and from 73.4 to 58.6 ms. Both versions read the same 16 objects/ranges and byte count.
Same-wheel S3 control
Both arms used the product wheel at
35b6c6598on the same dedicated instance. Each shape used four fresh processes in AB/BA order. Each process completed a cold scan followed by two warm scans, or 16 warm scans for filtered IVF_RQ. The table shows the warm EOF medians. Lower is better.Peak process RSS fell by 36.1% for fully indexed BM25 and 31.5% for fully indexed IVF_RQ. With the unindexed tail it fell by 26.1% and 9.6%, respectively. The mixed plans retained their ranked merge and issued nearly identical read counts across modes. Nine BM25 cutoff slots held interchangeable tied rows across repeated default queries. The exhaustive oracle verified all rows above the cutoff, returned score bits and projected payloads.