Skip to content

feat(index): support independent covering fields - #10662

Merged
Xuanwo merged 13 commits into
lance-format:mainfrom
Ali2Arslan:feat/support-independent-covering-fields
Nov 13, 2026
Merged

Xuanwo merged 13 commits into
lance-format:mainfrom
Ali2Arslan:feat/support-independent-covering-fields

Conversation

@Ali2Arslan

@Ali2Arslan Ali2Arslan commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Part of #10250, which tracks upstreaming composite scalar indexes and ordered index scans. This is C2 there. It builds on #10345 (C1), which made every index dependency check read both fields and covering_fields.

Why

#9159 specified feature flag 1 << 13, FLAG_INDEPENDENT_COVERING_FIELDS, and kept it masked out. Under that flag, IndexMetadata.fields lists only an index's keys and covering_fields lists its carried columns on its own, so an index can carry one of its keys. This PR turns the flag on. The format spec says a reader must pick the layout from the manifest flags before it reads any entry, so manifest decode and encode now take the manifest's layout.

What changed

  • CoveringContract names the two layouts. IndexMetadata::from_manifest_proto and to_manifest_proto decode and encode one manifest entry under the manifest's layout. The manifest reader and writer, the cached decode in Dataset::load_manifest, and the clone path use them.
  • In memory, an entry's shape names its layout. Carried fields that form a shorter tail of fields are the suffix layout, and any other covered entry is keys-only. keyed_fields, IndexSegment::keyed_field, validate_covering_fields, and the MemWAL fresh tier read the shape. declares_same_fields compares two entries by keyed and carried fields, and every check on two segments of one index uses it.
  • build_manifest sets bit 13 next to bit 7 while some index needs the keys-only layout, and the writer then stores every suffix entry as its keys. apply_feature_flags and a shallow clone keep the bit.
  • Transaction files store every index entry in the suffix layout, keys then carried fields. A release without bit 13 can then read a transaction that names a keys-only entry, such as the one that drops it. IndexMetadata::from_transaction_proto decodes each entry and refuses one outside the suffix layout, as releases do.

Scope

  • This PR changes no persisted proto and no format doc. Transaction entries keep the suffix layout that the proto already describes, so nothing under protos/ or docs/src/format/ moves, and the PR needs no format vote.
  • Compaction still skips remapping a covered index, and a column remap still refuses it, as fix(index): include covering fields in index dependency checks #10345 left it. Both checks read only whether covering_fields is empty, and no index type carries the carried values through a remap, so bit 13 does not change them.
  • Once bit 13 is set, it stays set while an entry it stored keys-only remains, even after the keys-only index that set it is dropped. The spec requires this: "Every manifest built from one that sets it keeps the bit set, unless a writer converts every entry back to the legacy contract in one atomic change of its own." Dropping the last covered index is that conversion, so bits 7 and 13 clear together.

Blast Radius

Tables without covered indices, and tables whose covered indices all use the suffix layout, write the same manifests and transactions as before, and releases without bit 13 still open them. A table that gains a keys-only index sets bit 13, and every release through 15.0.0-beta.10 refuses it until the index is dropped. Releases from 13.0.0 mark bit 13 unsupported, and older ones do not know it. A transaction read from storage returns a keys-only entry with its carried fields appended to fields.

Verification

Author-reported results below were measured on this branch's pre-integration history, before it was merged with current main.

  • cargo test -p lance-table --lib (1,002 tests) and its 17 doctests pass. They cover the transaction round trip of the tail-shaped entry keyed on [7, 11] that carries [11], and declares_same_fields on both layouts.
  • test_create_index_entry_outside_the_suffix_layout_is_refused decodes three transaction entries outside the suffix layout: [7] carrying [11], [11] carrying [11], and [7, 11] carrying [7]. Each fails from new_indices and from removed_indices with an error that names fields and covering_fields, while the same bytes decode as a manifest entry under bit 13. All three cases fail on 8d7e03e6f, and reverting either decode line fails them again.
  • The 35 lance tests whose names contain covering pass, and so does test_row_addr_index_writer_fence_survives_dataset_operations from fix(index): fence older writers from row-address indices #10352. One covering case commits a stable row ID table whose covered B-tree also stores row addresses, so bits 7, 13, and 18 hold through the commit and an unrelated delete, and all three clear when the index is dropped.
  • Before the merge with main, at f53fcf348, 1,410 lance tests passed, including 989 MemWAL tests and the conflict-resolver suite. Reverting the MemWAL key reads, the transaction encoder, the segment key rule, or any comparison site fails its new cases, and an always-true comparison fails the negative cases.
  • At 0c2419ead, cargo test -p lance --lib passes 8,764 tests with 9 ignored, including the 1,078 whose names contain mem_wal. In three of those tests, MemWAL writers on a covered B-tree and a covered full-text index open, write, flush, and filter the same rows in either layout, and a writer still flushes after another session turns bit 13 on. Each one checks that the generation carries the covered index, and at 290bf8968 all five of their cases failed that check when the flush wrote no index.
  • At b7a2babec, manifest commit and load were measured with 100 B-tree indices: commit 3.73 → 3.76 ms median (+0.84%) and load 0.698 → 0.707 ms median (+1.26%), 63 samples per side over three interleaved rounds.
  • The scalar-index compat file passes (97 passed, 2 skipped), including the row address index cases from fix(index): fence older writers from row-address indices #10352, and 13.0.0 reads the commit and drop transactions of a dropped keys-only index. test_commit_index.py passes (7 tests). Clippy, rustfmt, the Python lint, and the Java spotless:check pass.

Integrated onto main at 2320b5a6a (merge 353bba6a2, tree 18ac2f84f):

  • cargo check --workspace --tests --benches --profile ci passes.
  • cargo test -p lance-table --profile ci: 1,066 lib tests and 22 doctests pass.
  • cargo test -p lance --lib --profile ci: 10,338 pass with 9 ignored. The covering selector matches 34 passing tests, mem_wal 1,078 passing (2 ignored), and remap|lifecycle|merge|shallow_clone|declares_same_fields|conflict_resolver 1,501. cargo test -p lance --doc --profile ci: 142 pass.
  • python/tests/compat/test_scalar_indices.py --run-compat: 112 passed, 3 skipped (all three are the harness's intentional "downgrade unsupported" skips), including the new suffix and keys-only cases against pylance 13.0.0. python/tests/test_commit_index.py: 7 passed. uv run make lint passes.
  • cargo fmt --all --check; cargo clippy --profile ci --all --tests --benches -- -D warnings; Java spotless:check, compile, and the targeted index tests (3 in TransactionTest, 2 in DatasetTest) all pass.

Follow-ups

  • The carried columns format change, C3 in feature: composite B-tree keys and ordered index scans #10250, will state the rule this PR follows: every IndexMetadata in a serialized transaction uses the suffix layout, whether stored in a transaction file or inline in a manifest, and a reader refuses any other shape.
  • A merge of segments in both layouts copies the first input's declaration. The merged entry's layout, and so whether bit 13 stays set, depends on input order.
  • The derived IndexMetadata equality and Operation equality still compare raw fields. Nothing uses them to match two segments of one index today.
  • Comments in index/scalar.rs and dataset/write/seeds.rs still say that a covered index lists its carried columns in fields.

Ali2Arslan and others added 11 commits October 26, 2026 09:22
Index maintenance reads `IndexMetadata.fields` to decide whether a change
makes an index stale. Once `fields` can hold only keyed columns, those
checks would miss a change to a carried column, and the index would keep
serving old values.

Add `IndexMetadata::dependency_fields`, which returns `fields` plus each
covering field that `fields` omits, and read it in the overlay staleness
collectors, the checks in `index_maintenance.rs` and `index.rs`, the
conflict resolver, the `alter_columns` cast guard, and remap.
The check that refuses an in-place rewrite for an index with unknown
fragment coverage matched the rewritten fields against
`IndexMetadata.fields` alone. A Rust caller can commit a user index
without a fragment bitmap, so a keys-only covering index would let a
rewrite of its carried column through and keep serving old values.

Read `dependency_fields()` there, and add the check to both
covering-dependency test matrices.
Lift the mask on FLAG_INDEPENDENT_COVERING_FIELDS (1 << 13), which
upstream PR 9159 specified and reserved. Manifest decode and encode take
the covering layout from the manifest flags, and in memory each entry's
shape names its layout. A commit sets bit 13 next to bit 7 while some
index needs the keys-only layout, stores every other covered entry as
its keys, and caches the entries in the shape a fresh reader decodes.
A shallow clone keeps the bit.
A transaction file records no covering contract. Releases without bit 13
run the suffix check when they decode a transaction, so a keys-only entry
written as-is makes the transaction unreadable to them, including the one
that drops the index and clears the bit. Transaction files now store every
index entry as its keys followed by its carried fields. Reading an entry
back gives the same keys and carried fields.

IndexSegment::keyed_field now reads keys with the IndexMetadata shape
rule, through IndexMetadata::keyed_fields_of. A segment then commits under
the column that its manifest entry reads back keyed on.

Three tests used shapes that the independent contract accepts. They now
use a repeated carried field, which both contracts refuse.
A transaction file stores a keys-only entry in the suffix layout, so one
index can arrive with fields [a] or with fields [a, b], both carrying b.
Checks that compared two entries of one index by raw fields treated those
as different indices. On a table with a tagged fragment reuse history,
staged keys-only segments then failed replay across a same-name commit
that another session wrote.

IndexMetadata::declares_same_fields compares keyed fields and carried
fields. The conflict resolver, the index description, the commit and
merge checks on segments of one index, and the FTS and Hamming checks
now use it. The description and Hamming errors name both declarations.

The Java, Python, and IndexSegment docs no longer say that carried fields
are always a suffix of fields.
The MemWAL fresh tier built a maintained index's column list from raw
fields. A covered B-tree in the suffix layout, fields [a, b] carrying b,
then resolved to two columns and the writer refused it, or skipped it
when maintaining every index. The full-text resolver had the same fault.
Both now read keyed_fields(), so the suffix layout and the keys-only
layout of one index open, write, and flush alike. The flush check
compares the flushed entry's keys with the spec.

A test pins the bit 13 lifecycle: the bit stays while an entry it stored
keys-only remains, and dropping the last covered index clears bits 7
and 13 together.

Compaction does not drop a covered index it cannot remap. It keeps the
entry and skips the remap, so the two remap warnings now say that.
C1, the covering dependency checks this branch stacked on, merged
upstream as upstream PR 10345 (dcbbb1c). This branch now builds on
main at bfcc01f instead of the C1 branch head 200f22d.

The conflicts were resolved with 200f22d as the merge base, so C1's
own lines could not collide with their squash on main.
schema_evolution.rs and merge_coverage.rs take main unchanged, and
conflict_resolver.rs is main plus this branch's same_logical_index line.

apply_feature_flags keeps main's carry of bits 7, 17, and 18 across its
reset, with this branch's COVERING_FLAGS (bits 7 and 13) in place of the
bit 7 carry. Main's comment on that carry covers every index-derived
flag, so it replaces the C1 comment that this branch had reworded.
build_manifest sets bit 13 from the final index list, then calls
apply_row_addr_index_feature_flag from upstream PR 10352 for bit 18.
IndexMetadata::decode keeps main's created_at range check and its
clustering_id and metadata fields, and leaves validation to its callers,
as on this branch. The other conflicts are import lists, resolved as
unions.

Main added clustering_id and metadata to IndexMetadata, so the
declares_same_fields doctest sets both, as main's C1 doctest does.
Upstream PR 8742 gave remap_index an owned_fragments argument.
test_remap_index_drops_a_covered_index passes None, as every independent
remap does. test_covering_bits_follow_the_committed_declarations gains a
stable row ID case. Its covered B-tree also stores row addresses, so
bits 7, 13, and 18 hold through the commit and an unrelated delete, and
all three clear when the index is dropped. write_btree_table now takes
WriteParams for that case.

Co-authored-by: Cursor <[email protected]>
A transaction file stores every IndexMetadata in the suffix layout: keys,
then carried fields. Decoding a CreateIndex entry ran only the checks that
both layouts share, so an entry whose covering_fields is not a shorter
trailing slice of fields read back as keys-only. Every release from
11.0.0 through 15.0.0-beta.8 refuses such an entry, and so does upstream
main.

IndexMetadata::from_transaction_proto now decodes each new_indices and
removed_indices entry and runs the suffix checks, so it fails with the
error a release gives, naming fields and covering_fields.
TryFrom<pb::IndexMetadata> still decodes the in-memory shape for the
index metadata cache, the ANN plan proto, and the optimize serde path.
Manifest decoding does not change.

Co-authored-by: Cursor <[email protected]>
Upstream PR 10600 split rust/lance/src/index.rs into modules under
rust/lance/src/index/. This branch's changes there move with the code
they change. build_index_metadata_from_segments and
commit_existing_index_segments now live in lifecycle.rs, remap_index in
remap.rs, and IndexDescriptionImpl::try_new in statistics.rs. The edits
to existing tests and helpers move with them, into tests/merge.rs,
tests/support.rs, tests/lifecycle.rs, tests/statistics.rs, and
remap/tests.rs.

The tests this branch adds go to the module that owns their subject.
The commit, drop, retry, and shallow clone tests go to
tests/lifecycle.rs, the segment description test to tests/statistics.rs,
and the remap test to remap/tests.rs. write_btree_table,
redeclare_covering, and covering_bits serve more than one of those
files, so they move to tests/support.rs and become pub like the helpers
there. The feature flag import joins the shared list in index/tests.rs.
remap/tests.rs imports the support helpers and
FLAG_INDEPENDENT_COVERING_FIELDS itself, as the loading and provenance
tests do.

Upstream PR 10148 rewrote test_remapper_rejects_malformed_covering_fields
as cases over a legacy B-tree and a zone map. The merge keeps that form
with this branch's malformed declaration, a carried field listed twice.
Main's declaration, the fields plus one more, is a valid keys-only entry
under bit 13. The other conflict is an import list in
dataset_transactions.rs, resolved as a union with the imports of
upstream PR 10556.

A tagged-rewrite test this branch added now calls
crate::index::loading::load_all_indices, the path upstream PR 10600 gave
every other call in that file.

Co-authored-by: Cursor <[email protected]>
…ectory

Main now writes MemWAL data under `_{dir_id}_mem_wal` instead of
`_mem_wal` (upstream PRs 10489 and 10605). `flush_and_filter` still
opened `{uri}/_mem_wal/{shard}/{path}` and built its `LsmScanner`
without a dir id, so the three covered-index MemWAL tests failed with
`DatasetNotFound` before they reached their index assertion.

Read the writer's dir id before closing it, open the generation with
`sstable_uri`, and give the scanner the same dir id.

Co-authored-by: Cursor <[email protected]>
@github-actions github-actions Bot added A-python Python bindings A-java Java bindings + JNI enhancement New feature or request labels Nov 3, 2026
Two files conflicted. In rust/lance-table/src/io/manifest.rs, upstream
commit 9171e17 rewrapped the crate::format import that this branch's
CoveringContract import sits beside; the merge keeps both. In
rust/lance/src/index/tests/statistics.rs, upstream PR 9783 appended its
segment statistics tests where this branch had appended
test_index_description_reads_segments_in_either_layout; the merge keeps
main's tests in place and this branch's test after them.

Upstream PR 9438 added ManifestLocation.last_modified, so the
write_index_section test helper sets it to None, as other locations not
read from a listing do.

Co-authored-by: Cursor <[email protected]>
@Ali2Arslan
Ali2Arslan marked this pull request as ready for review November 5, 2026 15:52

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

lance-gatekeeper[bot]

This comment was marked as outdated.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 5, 2026
@lance-gatekeeper lance-gatekeeper Bot removed the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 13, 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.

The implementation follows the independent-covering contract, including manifest-wide normalization and suffix-form transactions. Local checks on the integrated head passed for mixed-layout segments, commit retries, warm/cold cache behavior, staged replay, and MemWAL flushes across a flag transition.

@lance-gatekeeper lance-gatekeeper Bot added the K-approved Latest Gatekeeper recommendation permits acceptance. label Nov 13, 2026

@Xuanwo Xuanwo left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approved on the reviewed contract: a manifest-wide CoveringContract, the keyed-versus-carried distinction with declares_same_fields across layouts, bits 7 and 13 paired in reader and writer, transaction entries in the suffix layout with other shapes explicitly refused, and the shallow-clone, cache, and MemWAL invariants. Integrated validation is green at this head, including the full workspace check, the lance and lance-table suites, the Python compat file against 13.0.0, and the Java index tests; the Arrow ordering compatibility job skipped correctly because no gating path and no Arrow, DataFusion, or half version changed. The evidence covers the exercised stable compat harness and 13.0.0, not every historical release, and the reported benchmarks were not reproduced here.

@Xuanwo
Xuanwo merged commit e13a2ee into lance-format:main Nov 13, 2026
43 checks passed
Xuanwo added a commit that referenced this pull request Nov 14, 2026
Warm-opening scalar index segments repeatedly processes the snapshot's
complete index listing, including reader/version checks and filtering.
With many segments, that repeats metadata work for each open. Refs
#10414.

Cache the complete query-visible listing by store identity, manifest
version, and ETag, and return its shared `Arc`. The internal cache key
keeps the public `DerivedIndexListingKey` value type unchanged. Listings
with incomplete best-effort legacy vector-detail inference or an
unreadable format marker retry derivation on later calls. Maintenance
paths continue to use `load_all_indices`.

A manifest without an ETag carries no generation token: a dataset
dropped and recreated at the same URI restarts its version history, so a
version-only key could alias the previous incarnation's listing.
`load_indices` therefore derives the listing for that call without
reading or publishing the shared cache entry, the same guard
`get_row_id_index` applies. Regression tests seed a stale listing under
the version-only key and check that an untagged snapshot neither serves
nor replaces it.

Extend concurrent-load coverage to check shared results, and add tests
for inference recovery and index creation/drop/historical checkout.
Update fixtures that replace metadata without committing a snapshot, and
account for the memory-only query listing in cache-count and
serialization tests. The warm remapping-plan test replaces both raw and
query listings so it still verifies that warm opens use the cached plan.

The refresh in `542336ef1` merges main `e72e57140` into the branch.
`9b1803285` is the merge commit and already carries the production
untagged-snapshot guard; `542336ef1` adds that guard's two regressions
and updates the comments that described the pre-merge behavior. Merge
resolutions keep main's independent-covering malformed fixture
(`covering_fields = vec![999, 999]`, #10662) together with this branch's
cache clear, and keep the typed query listing with its shared derivation
and retry flag instead of main's separate
`details_pending`/`unverifiable` guard, which implemented the same
retry. It also retains the explicit stable-row-ID lookup and accounts
for that optional entry alongside raw metadata and query-listing entries
in the ANN deletion test's cache count.

Validation of `e8899219a` (local)

- `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --profile
ci --locked` failed at `session/index_caches.rs:315` before the change
and passes after it. The public `DerivedIndexListingKey` comment linked
to the crate-private `QueryIndexListingKey`, so this commit turns that
one link into plain code and leaves the type private. No other files or
behavior change.
- `cargo fmt --all -- --check` passed.
- `cargo clippy --all --tests --benches -- -D warnings` passed in the
dev profile without `--profile ci --locked`. The workspace Clippy run on
`542336ef1` with `cargo --profile ci --locked` is reused for this
documentation-only delta.
- The behavior suites from `542336ef1` were not rerun: this commit
changes only one line of prose in a doc comment, so the compiled code
and tests are identical.

Validation of `542336ef1` (local, `cargo --profile ci --locked`)

- `cargo check -p lance --tests --benches` passed (5m31s).
- Focused suites: loading behaviors 14 passed (concurrent Arc reuse,
drop/create/historical isolation, inference retry, the untagged guard
and the stale-entry regression); session index-cache keys 7 passed;
remap 8 passed, including both independent-covering malformed cases;
lifecycle 76 passed; `frag_reuse_reader` 123 passed; ANN deletion
accounting 4 passed; serializing-backend prewarm 3 passed. No failures
or ignored tests.
- `cargo fmt --all` and `cargo fmt --all -- --check` are clean.
- Full workspace `cargo clippy --profile ci --locked --all --tests
--benches -- -D warnings` passed (5m58s).

The first hosted run on `542336ef1` exposed the strict-rustdoc failure
fixed in `e8899219a`; otherwise the commit's behavior matches the local
results above.

Earlier validation of `4943992c5`, before this refresh

- Rust, Python and Java CI passed on that revision. The ARM library
suite recorded 10,262 passes, zero failures and nine ignored tests,
including the concurrent-listing load, transient inference/format-marker
recovery, all four ANN-deletion variants, tagged remapping and all three
serialization-backend prewarm cases. License, typo and module-size
workflows also passed.
- `cargo fmt --all` and the archived-source formatting check passed;
full `cargo clippy --all --tests --benches -- -D warnings` passed
locally (90m09s) with all 2,756 archived source files and executable
bits matching the tested source afterward.
- Runtime tests were not completed locally on that revision; the runtime
results above come from hosted CI. A test-binary build on an earlier
merge was stopped as WSL approached its existing RAM and swap limits.
The benchmark was not repeated after that merge.

Validation of `2da95c718`, before that merge

- Rust formatting and full Clippy passed locally.
- Rust CI passed across Linux, ARM, macOS and Windows (8,859 passes,
zero failures, nine ignored in the ARM library suite, including both
vector prewarm regression cases). Python CI and Java CI passed on the
same commit.
- A local paired benchmark in WSL used `release-no-lto`, the same probe
on base `91ef50083` and patch `1d787fee5`, and nine warm trials after
one warm-up. Opening all 1,024 B-tree segments fell from a median
537.817 ms to 32.338 ms, about 16.6x faster. At 256 segments the medians
were 40.232 ms and 2.960 ms. Both probes passed their segment-count
assertions. These are measurements of those revisions, with the patched
run first; an unrelated test suite was running during the baseline
compilation and measurement.

OpenAI Codex assisted with investigation, implementation, regression
tests and validation.

---------

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-java Java bindings + JNI A-python Python bindings enhancement New feature or request K-approved Latest Gatekeeper recommendation permits acceptance.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants