Repository navigation
feat(scanner): serve ORDER BY LIMIT from a single-column B-tree - #11124
Conversation
ORDER BY <column> LIMIT n sorts every row even when a B-tree on that column already holds the keys in order. Read the B-tree in key order through OrderedIndexScanExec and stop after offset + limit live rows. The scanner picks a B-tree by its key field, so a single-key B-tree with covering columns serves the read. It falls back to the sort when the index does not cover every fragment, when a fragment has an overlay on the key, on datasets with stable row ids, and for indices named in with_ignored_scalar_indices. Add an ordered_index mode (off, auto; default auto) to the Rust scanner, Python scanner arguments, and Java ScanOptions. Off plans the same sort as before. Co-authored-by: Cursor <[email protected]>
|
@Xuanwo @wjones127 could one of you review this when you have time? It's O3 in #10250 and builds on #10346 and #10777, which you reviewed. CI is green, it merges cleanly with main, and O4 through O7 are stacked behind it. |
Xuanwo
left a comment
There was a problem hiding this comment.
AI-assisted review of a7a9317b
The scanner documents batch_size as the maximum number of rows per batch. On v14.0.3, projecting only the indexed ts column across three fragments with ORDER BY ts LIMIT 16 and batch_size=2 streamed eight batches of two rows, with values 0 through 15 in order.
On this head, OrderedIndexScanExec::execute emits page-sized batches without applying the execution context’s batch size. Projecting only ts avoids a take, and the downstream projection and limit can pass through a batch larger than two rows. This finding is from tracing the candidate code.
Please enforce batch_size on this path and add a regression that consumes the default ordered plan through to_batches(). Check each batch has at most two rows and that concatenating them yields 0 through 15 in order. That lets the implementation choose any batch boundaries within the documented limit.
Please also update the branch from main and resolve the Java async scanner conflict with #11482. The passing integration checks ran at bd0b959f.
Resolve the conflicts with the unordered vector and full-text search results change by keeping both scanner options: ordered_results comes first and ordered_index follows it in the Python binding's signature, its positional call, and the stub. The Java async scanner keeps main's optional batch readahead next to the ordered_index argument, and the missing-index-files test reaches the object store through table_state. Co-authored-by: Cursor <[email protected]>
The scanner documents batch_size as the most rows a batch can hold. These cases read ORDER BY ts LIMIT n through the ordered B-tree read on three fragments and check that every streamed batch has at most batch_size rows and that the batches concatenate to the first n keys in order: a key-only projection, a taken column, a limit that is not a multiple of the batch size, a filter the index answers, and a batch size larger than an index page. Python adds the key-only case through to_batches(). The ordered read emits one batch per index page today, so the cases with a page larger than batch_size fail until the next commit. Co-authored-by: Cursor <[email protected]>
OrderedIndexScanExec emitted one batch per index batch, so an ordered read with batch_size(2) streamed 16-row batches. The take, projection, and limit above it keep batch boundaries, so the scan returned them. execute now reads the batch size from the task context, which the scanner sets from batch_size, and splits longer batches into slices that share the index batch's buffers. Co-authored-by: Cursor <[email protected]>
Main added ordered_results for vector and full-text search. The ordered index read serves only plain scans, so check that it still sorts when a nearest or full-text query sets ordered_results(false), as it does with the default ordered_results(true). Co-authored-by: Cursor <[email protected]>
The order_by, scan_in_order, and ordering docs said an ordered scan reads in parallel, sorts, and must read all data before its first batch. A B-tree index that serves the ordering does none of these, so name it as the exception. Co-authored-by: Cursor <[email protected]>
|
@Xuanwo, confirmed: the ordered read returned one batch per B-tree page, so your case streamed a single 16-row batch. Nothing above it splits a batch by rows. The take that reads a projected non-key column splits only to meet a byte limit; otherwise it merges short batches up to its target and passes a larger one through whole, so that path also returned one 16-row batch.
The regression is I also merged main. The Python binding keeps #11669's |
There was a problem hiding this comment.
✅ Gate recommendation: approve.
The batch size correction restores the scanner’s maximum rows per batch for ordered index reads, including reads of additional columns. No blocking issues found; the eligibility guards preserve the existing sort fallback for other scans.
Part of #10250, which lays out the ordered index scan design and the PR sequence. This is O3 there.
Why
ORDER BY <column> LIMIT nsorts 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 afteroffset + limitlive rows. It builds on #10777, which merged and addedOrderedIndexScanExecover the B-tree ordered search from #10346.What changed
create_plan_implinscanner/plan.rsasks the newScanner::try_ordered_readfor anOrderedIndexScanExecbefore it plans a filtered read. When it gets one, the plan has noSortExec. The existing take runs on top of the node, and the limit either stays above it or folds into the node'sfetch.IndexMetadata::keyed_field(). Since feat(index): support independent covering fields #10662, a covered B-tree lists its carried columns after its key inIndexMetadata::fields, so the read compares the key the same wayOrderedIndexScanExec::try_newdoes after feat(exec): add OrderedIndexScanExec over B-tree ordered search #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.ordered_indexmode controls the read, withauto(the default) andoff. Rust hasOrderedIndexMode::{Off, Auto}andScanner::ordered_index(mode). Python takesordered_index="off"onscanner,to_table,to_pandas,to_batches, andScannerBuilder.ordered_index. Java takesScanOptions.Builder.orderedIndex(ScanOptions.OrderedIndexMode.OFF). Python passes its string and Java passestoRustString(), and Rust parses both. The parser ignores ASCII case and rejects any other name with an error that listsoff, auto.offplans the same sort as a scan without this PR. A later PR in feature: composite B-tree keys and ordered index scans #10250 addsrequired, which fails instead of sorting.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 theordered_indexmode say that an ignored index never serves the read.ordered_limitbench group inscalar_index.rstimesauto,off, and a declined query.OrderedIndexScanExecnow builds its key field from the column's Arrow field, so a projected key keeps its field metadata.OrderedIndexScanExecnow caps each batch at the task context's batch size, which the scanner sets frombatch_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'sbatch_sizewhen one is set, so it may merge slices but never pastbatch_size. Withbatch_sizeunset, the cap is DataFusion's default of 8,192 rows, which a default page of 4,096 rows never reaches, so nothing is sliced.order_by,scan_in_order, andorderingdocs name the ordered index read as the exception to reading in parallel, sorting, and reading all data before the first batch.47f14ab03. The Python binding, its stub, and the call that passes the scanner options by position keep feat(scanner): support unordered vector and full-text search results #11669'sordered_resultsnext to this PR'sordered_index. The Java async scanner keeps fix(bindings): inherit native scanner batch readahead #11482's optionalbatch_readaheadnext to theordered_indexargument. The test that removes an index's files reaches the object store throughdataset.table_state, where main moved it.Scope
requiredmode are later PRs.include_deleted_rows, nested keys, and the legacy file format. A narrower fragment list could make the walk skip most of the index.ORDER BY ... LIMIT. Follow-up: lift this decline once bug: an update from 12.x or 13.x makes a 14.x B-tree miss rows on stable-row-id tables #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 withNot found, as a filter on that column already does.ordered_index="off"(OrderedIndexMode.OFFin 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'sscanner::orderedcases. 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, andMissingIndexFilesdeletes nothing. The 5 batch-size cases write three fragments without deletions. Every decline case checks that the plan equals theoffplan and that the rows match underautoandoff. The vector and full-text search declines run withordered_resultsboth true and false, because the ordered read serves only plain scans.cargo test -p lance --lib scannerpasses 1,760 tests with 1 ignored.cargo test -p lance --libpasses 12,260 tests with 9 ignored and none failed.test_ordered_read_honors_batch_sizeis the review's case. It writes 48 rows in three fragments, indexests, and readsORDER BY ts LIMIT 16withbatch_size(2)and onlytsprojected, throughScanner::try_into_stream. It checks that the plan hasOrderedIndexScanand noSortExec, 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 takesv, one usesLIMIT 15, one filters onts >= 5, and one takesvwithbatch_size(8)from 4-row pages. With the cap reverted alone, the 4 cases whose page holds more rows thanbatch_sizefail 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_keydeclaresidas a covering column of the B-tree onts. The scan plansOrderedIndexScan: index=ts_idxwith the same rows asoff. After an overlay changesidin one of the first ten rows, it still reads in order and returns the new value. After an overlay onts, it plans the same sort asoff. With the candidate loop comparingIndexMetadata::fieldsto the order column instead ofkeyed_field(), only this test fails, becauseautoplansSortExec: TopK(fetch=10).test_ordered_read_skips_ignored_indices::case_1_order_column_indexfails, becauseautoplansOrderedIndexScan: index=ts_idxwhereoffplansSortExec: TopK(fetch=10). Withoffdropped from the decline, 23 of the 54 cases fail. Those are the cases whereautoplansOrderedIndexScan, becauseoffthen plans it too. With the parser mapping any unknown name toauto, the 3 rejection cases fail (sorted, the empty string, andauto).[10, 12, 13, 14, 15, 17, 18, 19, 20, 21]where the sort returned[3, 4, 6, 7, 8, 9, 10, 12, 13, 14].NotSupportedfallback, failed 32 tests, each one predicted. The 9 that still passed decline for structural reasons.cargo fmt --all -- --checkandcargo clippy --all --tests --benches -- -D warningsare clean.python ci/check_module_size.pypasses and adds no exception, with a warning thatpython/src/dataset.rsgrows from 5,244 to 5,249 lines.cargo test -p lance --doc orderedpasses all 4 doctests it selects: this PR's forOrderedIndexModeandScanner::ordered_index, and the existing ones forOrderedIndexScanExecandScanner::ordered_results.RUSTDOCFLAGS="-D warnings" cargo doc -p lance --no-depspasses.cargo test -p lance --bench scalar_indexruns the whole bench in test mode and reportsSuccessfor all 8 cases, including the 3ordered_limitcases.uv run make lintis clean: ruff, pyright with 0 errors,cargo fmt -- --check, andcargo clippy -- -D warnings.pytest python/tests/test_scalar_index.pypasses 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 throughto_batches()../mvnw test -Dskip.build.jni=true -Dtest=ScannerTest,AsyncScannerTest,JNITest, against aliblance_jni.sothatcargo buildbuilt from this head, passes 101 tests, includingtestOrderedIndexandtestParseOrderedIndexMode.testOrderedIndexchecks that both modes return the same rows and that onlyautoreports thepages_loadedcounter.testParseOrderedIndexModesends every Java constant andsortedthrough the Rust parser.cargo testforjava/lance-jnipasses 39 tests../mvnw spotless:check, pluscargo fmtandcargo clippy --tests -- -D warningsforjava/lance-jni, are clean.Each perf case below ran at
d4dab02fc, an earlier head of this branch, before it merged main atc36ee5445. The cases were not rerun after that merge, the merge of main at47f14ab03, or the batch-size cap. The bench readsLIMIT 100with the default batch size, so the cap never slices there, and a slice shares its buffers rather than copying them. At this head, the 3ordered_limitcases 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 filterid >= 0, which the B-tree ontscannot answer, so both modes sort.tsvalues are null,ORDER BY ts DESC LIMIT 100returns the same 100 rows underautoandoff. There the ordered read reads 811 KB, against 59 MB for the sort. On the bench's dataset shape,autop50 is 0.212 s against 1.392 s foroff, or 0.153 times. The declined query takes 1.957 s underautoagainst 2.025 s underoff, 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.release-with-debugbuild of theordered_limitbench 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.autop50 is 9.01 ms against 70.1 ms foroff, or 0.129 times. The declined query takes 84.9 ms underautoagainst 88.7 ms underoff, 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: