From 2425a42112eb8a166f81a2dbb5d5718777575eb2 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Thu, 12 Nov 2026 14:31:17 -0800 Subject: [PATCH 01/15] feat(index)!: change Inverted (FTS) scalar index to row-address domain Stacked on #9858 (NGram/RTree/MinHash LSH), stacked on #9814 (Bitmap/LabelList), stacked on #9481 (BTree). This completes the scalar-index migration: Inverted was the last builtin scalar index type still in the row-id domain, and now stores physical row addresses (fragment_id << 32 | offset) in docs.lance's identity column (still named `_rowid`) instead of row ids. - New INVERTED_ROW_ADDR_DOMAIN_VERSION (4), orthogonal to the posting-list format axis (tracked separately via file metadata, not index_version). - index_version()/results_are_row_addrs()/can_follow_stable_row_ids() gate on it; build_scalar_index relabels a fresh build back to the legacy version on a non-stable-row-id dataset, matching every other migrated type. - append.rs/scalar/inverted.rs: old-data filters and legacy-domain-mismatch rebuild now use the segment's own domain instead of a hardcoded row-id assumption, fixing a real bug where a stale posting after an in-place update under stable row ids leaked through a merge. - FTS's own deletion/filter/overlay masks (DatasetPreFilter, IndexVisibility) are checked directly against an address-domain index's own stored addresses, before any row-id translation -- they now translate the row-id-domain conventions every other mask follows into that same domain instead of silently comparing unrelated numeric spaces. - create.rs no longer refuses creating an Inverted index under a live fragment reuse index: it applies to Inverted like every other scalar type now. - Updated or replaced tests that assumed Inverted was "the last row-id-domain index" across append.rs, create.rs, frag_reuse_with_stable_row_ids.rs, dataset/optimize/tests, dataset/write/update.rs, and index/tests/lifecycle.rs, largely via the manual legacy-segment-relabel pattern already used for the prior migrations. Added an Inverted case to a few other-type-parametrized tests confirming it now behaves like every other address-domain index. - New Python compat test InvertedRowAddressDomainIndex; format docs updated. Known gap: a latent gap in compaction's eager-remap-vs-unreadable-index path (planning.rs's `unreadable_coverage` hold-back only applies without stable row ids) was exposed by this migration removing the last index type that could dodge it, but predates this PR and affects every address-domain index type, not just Inverted -- flagged separately for follow-up. Co-Authored-By: Claude Sonnet 5 Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Y3hhWk6pkpoQgZywMu49WT --- docs/src/format/index/scalar/fts.md | 7 +- .../tests/compat/test_scalar_indices.py | 142 +++++++++++++++ rust/lance-index/benches/inverted.rs | 5 +- .../benches/inverted_request_cache.rs | 2 +- rust/lance-index/src/registry.rs | 7 +- rust/lance-index/src/scalar/inverted.rs | 93 ++++++++-- .../src/scalar/inverted/builder.rs | 88 +++++----- .../src/scalar/inverted/combined.rs | 4 +- .../src/scalar/inverted/combined/testing.rs | 2 +- .../src/scalar/inverted/index/format.rs | 11 ++ .../scalar/inverted/index/inverted_index.rs | 32 +++- .../src/scalar/inverted/index/tests.rs | 12 +- .../inverted/index/tests/flat_search.rs | 38 +++- .../index/tests/format_and_builder.rs | 2 +- .../scalar/inverted/index/tests/grouping.rs | 2 +- .../scalar/inverted/index/tests/lifecycle.rs | 44 +++-- .../inverted/index/tests/position_cache.rs | 6 +- .../inverted/index/tests/prewarm_cache.rs | 20 ++- .../src/scalar/inverted/index/tests/query.rs | 59 ++++--- .../scalar/inverted/index/tests/scoring.rs | 16 +- .../src/scalar/inverted/index/tests/stats.rs | 11 +- rust/lance-index/src/scalar/registry.rs | 4 +- rust/lance-table/src/format/index.rs | 11 +- rust/lance/src/dataset/mem_wal/index/tests.rs | 8 +- rust/lance/src/dataset/optimize/tests.rs | 16 +- .../src/dataset/optimize/tests/commit.rs | 30 ++-- .../src/dataset/optimize/tests/frag_reuse.rs | 150 +++++++++++++--- rust/lance/src/dataset/write/update.rs | 26 ++- rust/lance/src/index/append.rs | 102 ++++++++--- rust/lance/src/index/create.rs | 8 +- .../index/frag_reuse_with_stable_row_ids.rs | 118 +++++++++---- rust/lance/src/index/prefilter.rs | 70 ++++++-- rust/lance/src/index/scalar.rs | 12 ++ rust/lance/src/index/scalar/inverted.rs | 98 +++++++++-- rust/lance/src/index/tests/lifecycle.rs | 33 ++-- rust/lance/src/index/tests/statistics.rs | 8 +- rust/lance/src/io/exec/fts/boolean.rs | 4 +- rust/lance/src/io/exec/fts/combined_fields.rs | 87 ++++++--- rust/lance/src/io/exec/fts/compound.rs | 56 ++++-- rust/lance/src/io/exec/fts/document.rs | 5 +- rust/lance/src/io/exec/fts/match_query.rs | 16 +- rust/lance/src/io/exec/fts/matches.rs | 15 +- rust/lance/src/io/exec/fts/phrase.rs | 18 +- rust/lance/src/io/exec/fts/segments.rs | 105 ++++++++++- rust/lance/src/io/exec/utils.rs | 165 ++++++++++++++++++ 45 files changed, 1394 insertions(+), 374 deletions(-) diff --git a/docs/src/format/index/scalar/fts.md b/docs/src/format/index/scalar/fts.md index 4a36f4c851e..bd7ae6da5d2 100644 --- a/docs/src/format/index/scalar/fts.md +++ b/docs/src/format/index/scalar/fts.md @@ -20,7 +20,7 @@ The FTS index consists of multiple files storing the token dictionary, document An FTS index may contain multiple partitions. Each partition has its own set of token, document, and posting list files, prefixed with the partition ID (e.g. `part_0_tokens.lance`, `part_0_docs.lance`, `part_0_invert.lance`). The `metadata.lance` file lists all partition IDs in the index. At query time, every partition must be searched and the results combined to produce the final ranked output. Fewer partitions generally means better query performance, since each partition requires its own token dictionary lookup and posting list scan. The number of partitions is controlled by the training configuration -- specifically `LANCE_FTS_TARGET_SIZE` determines how large each merged partition can grow (see [Training Process](#training-process) for details). -From format version 4 onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. The current implementation supports format versions 1 through 3; format version 4 is specified here but is not yet implemented. +From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. This version is independent of the posting-list format below (tracked separately via file metadata, not `index_version`): a row-address-domain segment can pair with any posting format. ### Token Dictionary File Schema @@ -33,8 +33,7 @@ From format version 4 onward, a segment stores a physical row address (`fragment | Column | Type | Nullable | Description | |---------------|--------|----------|----------------------------------| -| `_rowid` | UInt64 | false | Document row ID (only if format version <= 3) | -| `_rowaddr` | UInt64 | false | Physical row address (`fragment_id << 32 \| offset`) of the document (only if format version >= 4) | +| `_rowid` | UInt64 | false | Document row ID (format version <= 3) or row address (format version >= 4); see above | | `_num_tokens` | UInt32 | false | Number of tokens in the document | Partitioned `docs.lance` files may include the optional schema metadata key @@ -50,7 +49,7 @@ loaded, is file corruption. | Column | Type | Nullable | Description | |------------------------|-------------------------|----------|------------------------------------------------------------------| -| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance._rowid` or `docs.lance._rowaddr`. | +| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance._rowid`. | | `_max_score` | Float32 | false | Maximum score for the token (for query optimization) | | `_length` | UInt32 | false | Number of documents containing the token | | `_compressed_position` | List> | true | Optional compressed position lists for phrase queries | diff --git a/python/python/tests/compat/test_scalar_indices.py b/python/python/tests/compat/test_scalar_indices.py index a8eabba4d6a..4b632ada25d 100644 --- a/python/python/tests/compat/test_scalar_indices.py +++ b/python/python/tests/compat/test_scalar_indices.py @@ -30,6 +30,19 @@ def _writer_supports_row_address_indices(compat_version): return Version(compat_version) >= Version("15.0.0") +def _reader_supports_inverted_row_address_index(compat_version): + """Whether this release's reader understands an Inverted index stored in + the row-address domain. + + BTREE migrated in 14.0.0 and BITMAP/LABEL_LIST/NGRAM in 15.0.0, but + Inverted was the last builtin scalar type to move, at + `INVERTED_ROW_ADDR_DOMAIN_VERSION` (index_version 4) in 16.0.0. A 15.x + build therefore handles every other row-address index and still has to + ignore this one as a format from the future. + """ + return Version(compat_version) >= Version("16.0.0") + + def _creator_rejects_json_wrapped_row_address_index(compat_version): """Whether this release's writer outright rejects creating a JSON-wrapped BTREE/BITMAP/LABEL_LIST index on a stable-row-id dataset. @@ -1385,3 +1398,132 @@ def test_keys_only_index_transactions_with_older_release(venv_factory, tmp_path) venv_factory.get_venv("13.0.0").execute_method( case, "check_commit_then_drop_transactions" ) + + +@compat_test(min_version="0.39.0") +class InvertedRowAddressDomainIndex(UpgradeDowngradeTest): + """Test Inverted (FTS) forward/backward compatibility across the + row-address-domain format change. + + min_version is 0.39.0, not FtsIndex's 0.36.0, for the same reason as + NgramRowAddressDomainIndex above: this test's whole point is an old + build correctly ignoring an index format version newer than it + understands, and that mechanism was only introduced in 0.39.0 (#4906). + + Inverted was the last builtin scalar index type still in the row-id + domain; it was changed to store physical row addresses in `docs.lance`'s + identity column instead, which bumped its index_version to 4 + (`INVERTED_ROW_ADDR_DOMAIN_VERSION`). This dataset enables stable row + ids, so the two domains genuinely differ and updating a pre-change + segment must rebuild it rather than merge new data into it. This test + checks the full story: + + - An old-format (row-id domain) Inverted index is loaded and used + correctly by the current build. + - Updating it (inserting rows, then optimizing) with the current build + keeps both old and new rows queryable. + - Stable readers that do not support the updated index must ignore it and + answer correctly via a full scan. Because this is the last type to + migrate and it moves in 16.0.0, that is every released build so far -- + including the 15.x ones that already read every other row-address + index. Stable writers without the row-address capability + (`FLAG_ROW_ADDR_INDICES`, 15.0.0) must reject inserts and unsafe + updates without changing the dataset; a 15.x writer has that capability + and so maintains the index's coverage safely while still answering its + own queries by scan. + + Without stable row ids the current build keeps writing the legacy + posting-format version, which FtsIndex above checks every build keeps + using. + """ + + def __init__(self, path: Path): + self.path = path + + def _supports_row_address_index(self) -> bool: + return not self._running_in_old_venv or ( + _reader_supports_inverted_row_address_index(self.compat_version) + ) + + def create(self): + """Create a stable-row-id dataset with an Inverted (FTS) index.""" + shutil.rmtree(self.path, ignore_errors=True) + data = pa.table( + { + "idx": pa.array(range(1000)), + "text": pa.array( + [f"document with words {i} and more text" for i in range(1000)] + ), + } + ) + dataset = lance.write_dataset( + data, + self.path, + max_rows_per_file=100, + data_storage_version=safe_data_storage_version(self.compat_version), + enable_stable_row_ids=True, + ) + dataset.create_scalar_index("text", "INVERTED") + + def _assert_queryable(self, expect_index_used: bool): + ds = lance.dataset(self.path) + match_table = ds.to_table( + full_text_query={"query": "words 7", "columns": ["text"]} + ) + assert match_table.num_rows > 0 + assert 7 in match_table.column("idx").to_pylist() + + explain = ds.scanner( + full_text_query={"query": "words 7", "columns": ["text"]} + ).explain_plan() + # "FlatMatchQuery" (the brute-force fallback) also contains + # "MatchQuery" as a substring, so check its absence too. + used_index = "MatchQuery" in explain and "FlatMatchQuery" not in explain + if expect_index_used: + assert used_index, "expected the Inverted index to be used" + else: + assert not used_index, ( + "an older build must not use an Inverted index in a format " + "it does not understand -- it should fall back to a full scan" + ) + + def check_read(self): + """Use supported index formats and safely ignore too-new ones.""" + self._assert_queryable(expect_index_used=self._supports_row_address_index()) + + def check_write(self): + """Fence old writers; verify current writes and index maintenance.""" + ds = lance.dataset(self.path) + new_key = ds.count_rows() + data = pa.table( + { + "idx": pa.array([new_key]), + "text": pa.array([f"brand new document {new_key}"]), + } + ) + if self._running_in_old_venv and not _writer_supports_row_address_indices( + self.compat_version + ): + _assert_row_address_writes_fenced(ds, data, self.compat_version) + return + ds.insert(data) + # For the current build updating a legacy row-id-domain segment, + # this must rebuild (not merge) the index -- see the class docstring. + ds.optimize.optimize_indices() + ds.optimize.compact_files() + + # A row-count match alone would still pass if the rebuild silently + # left the column unindexed (a full scan gives the same counts), so + # also check the index is used wherever the writer can read it. A 15.x + # writer reaches here -- it understands `FLAG_ROW_ADDR_INDICES` and so + # maintains coverage safely -- but still cannot read index_version 4, + # so it keeps answering by scan. + self._assert_queryable(expect_index_used=self._supports_row_address_index()) + ds = lance.dataset(self.path) + match_table = ds.to_table( + full_text_query={ + "query": f"brand new document {new_key}", + "columns": ["text"], + } + ) + assert new_key in match_table.column("idx").to_pylist() diff --git a/rust/lance-index/benches/inverted.rs b/rust/lance-index/benches/inverted.rs index e217968496d..c5575bc1056 100644 --- a/rust/lance-index/benches/inverted.rs +++ b/rust/lance-index/benches/inverted.rs @@ -14,7 +14,7 @@ use criterion::{Criterion, criterion_group, criterion_main}; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use futures::stream; use itertools::Itertools; -use lance_core::ROW_ID; +use lance_core::ROW_ADDR; use lance_core::cache::LanceCache; use lance_index::prefilter::NoFilter; use lance_index::scalar::inverted::document_tokenizer::DocType; @@ -82,7 +82,7 @@ fn bench_inverted(c: &mut Criterion) { let batch = RecordBatch::try_new( arrow_schema::Schema::new(vec![ arrow_schema::Field::new("doc", arrow_schema::DataType::LargeUtf8, false), - arrow_schema::Field::new(ROW_ID, arrow_schema::DataType::UInt64, false), + arrow_schema::Field::new(ROW_ADDR, arrow_schema::DataType::UInt64, false), ]) .into(), vec![doc_col.clone(), row_id_col], @@ -146,6 +146,7 @@ fn bench_inverted(c: &mut Criterion) { phrase_search_store, None, &LanceCache::no_cache(), + true, )) .unwrap(); diff --git a/rust/lance-index/benches/inverted_request_cache.rs b/rust/lance-index/benches/inverted_request_cache.rs index ef406072038..9edae74aa39 100644 --- a/rust/lance-index/benches/inverted_request_cache.rs +++ b/rust/lance-index/benches/inverted_request_cache.rs @@ -125,7 +125,7 @@ impl Fixture { .await .unwrap(); file_sizes.insert(file.path, file.size_bytes); - let index = InvertedIndex::load(store.clone(), None, &index_cache) + let index = InvertedIndex::load(store.clone(), None, &index_cache, true) .await .unwrap(); index.prewarm().await.unwrap(); diff --git a/rust/lance-index/src/registry.rs b/rust/lance-index/src/registry.rs index a1cf6c615f5..5247c23561b 100644 --- a/rust/lance-index/src/registry.rs +++ b/rust/lance-index/src/registry.rs @@ -17,7 +17,7 @@ use crate::{ bloomfilter::BloomFilterIndexPlugin, btree::{BTREE_ROW_ADDR_DOMAIN_VERSION, BTreeIndexPlugin}, fmindex::FMIndexPlugin, - inverted::{INVERTED_INDEX_VERSION_V3, InvertedIndexPlugin}, + inverted::{INVERTED_ROW_ADDR_DOMAIN_VERSION, InvertedIndexPlugin}, json::{JSON_ROW_ADDR_DOMAIN_VERSION, JsonIndexPlugin}, label_list::{LABEL_LIST_ROW_ADDR_DOMAIN_VERSION, LabelListIndexPlugin}, list_element::{LIST_ELEMENT_INDEX_VERSION, ListElementIndexPlugin}, @@ -65,7 +65,10 @@ const BUILTIN_SCALAR_INDICES: &[BuiltinScalarIndex] = &[ ZoneMapIndexVersion::CURRENT as u32, ), BuiltinScalarIndex::new::("bloomfilter", 0), - BuiltinScalarIndex::new::("inverted", INVERTED_INDEX_VERSION_V3), + BuiltinScalarIndex::new::( + "inverted", + INVERTED_ROW_ADDR_DOMAIN_VERSION, + ), BuiltinScalarIndex::new::("json", JSON_ROW_ADDR_DOMAIN_VERSION), BuiltinScalarIndex::new::( "listelement", diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index fdbffd3d6d9..7c9ab5213c5 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -512,8 +512,6 @@ impl InvertedIndexPlugin { }); params.validate_format_version()?; - let format_version = params.resolved_format_version(); - let is_element_document = params.get_document_granularity().is_list_element(); let details = pbold::InvertedIndexDetails::try_from(¶ms)?; let mut inverted_index = InvertedIndexBuilder::new_with_fragment_mask(params, fragment_mask) @@ -521,15 +519,52 @@ impl InvertedIndexPlugin { let files = inverted_index.update(data, index_store, None).await?; Ok(CreatedIndex { index_details: prost_types::Any::from_msg(&details).unwrap(), - index_version: if is_element_document { - INVERTED_INDEX_VERSION_V3 - } else { - format_version.index_version() - }, + // Training always scans row addresses now (see + // `InvertedIndexTrainingRequest`); `build_scalar_index` relabels + // this back to the legacy row-id-domain version (via + // `relabel_as_row_id_domain`) on a dataset without stable row + // ids, where a row id and a row address are the same value. + index_version: INVERTED_ROW_ADDR_DOMAIN_VERSION, files, }) } + /// The format-and-granularity-appropriate version for a freshly trained + /// segment on a dataset without stable row ids, where a row id and a row + /// address are the same value. + /// + /// List-element-granularity documents require the V3 reader capability + /// (element-document coordinates) regardless of the configured posting + /// format; every other segment keeps the version implied by its posting + /// format. + fn legacy_index_version(is_element_document: bool, posting_format_version: u32) -> u32 { + if is_element_document { + INVERTED_INDEX_VERSION_V3 + } else { + posting_format_version + } + } + + /// Relabel a freshly trained Inverted segment in the pre-migration + /// row-id-domain format. + /// + /// Only valid on a dataset without stable row ids, where a row address and + /// a row id are the same value, so the segment's trained data is + /// identical in either domain. Mirrors the plain BTree/Bitmap/LabelList + /// relabeling in `build_scalar_index`, and keeps the segment readable by + /// builds that predate [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]. + pub fn relabel_as_row_id_domain(created: &mut CreatedIndex) -> Result<()> { + let details = pbold::InvertedIndexDetails::decode(created.index_details.value.as_slice())?; + let is_element_document = + DocumentGranularity::try_from(details.document_granularity)?.is_list_element(); + let posting_format_version = details + .posting_format_version + .unwrap_or_else(|| default_fts_format_version().index_version()); + created.index_version = + Self::legacy_index_version(is_element_document, posting_format_version); + Ok(()) + } + /// Return true if the query can be used to speed up contains_tokens queries fn can_accelerate_queries(details: &pbold::InvertedIndexDetails) -> bool { details.base_tokenizer == Some("simple".to_string()) @@ -548,7 +583,7 @@ impl InvertedIndexTrainingRequest { pub fn new(parameters: InvertedIndexParams) -> Self { Self { parameters, - criteria: TrainingCriteria::new(TrainingOrdering::None).with_row_id(), + criteria: TrainingCriteria::new(TrainingOrdering::None).with_row_addr(), } } } @@ -644,7 +679,7 @@ impl ScalarIndexPlugin for InvertedIndexPlugin { } fn version(&self) -> u32 { - INVERTED_INDEX_VERSION_V3 + INVERTED_ROW_ADDR_DOMAIN_VERSION } fn new_query_parser( @@ -675,11 +710,18 @@ impl ScalarIndexPlugin for InvertedIndexPlugin { &self, index_store: Arc, index_details: &prost_types::Any, - _index_version: u32, + index_version: u32, frag_reuse_index: Option>, cache: &LanceCache, ) -> Result> { - let index = InvertedIndex::load(index_store, frag_reuse_index, cache).await?; + let results_are_row_addresses = index_version >= INVERTED_ROW_ADDR_DOMAIN_VERSION; + let index = InvertedIndex::load( + index_store, + frag_reuse_index, + cache, + results_are_row_addresses, + ) + .await?; let details = decode_inverted_details(index_details)?; let expected_granularity = DocumentGranularity::try_from(details.document_granularity)?; let physical_granularity = index.params().get_document_granularity(); @@ -699,12 +741,18 @@ impl ScalarIndexPlugin for InvertedIndexPlugin { &self, index_store: Arc, index_details: &prost_types::Any, - _index_version: u32, + index_version: u32, frag_reuse_index: Option>, cache: &LanceCache, ) -> Result> { - let index = - InvertedIndex::load_with_remapping(index_store, frag_reuse_index, cache).await?; + let results_are_row_addresses = index_version >= INVERTED_ROW_ADDR_DOMAIN_VERSION; + let index = InvertedIndex::load_with_remapping( + index_store, + frag_reuse_index, + cache, + results_are_row_addresses, + ) + .await?; let details = decode_inverted_details(index_details)?; let expected_granularity = DocumentGranularity::try_from(details.document_granularity)?; let physical_granularity = index.params().get_document_granularity(); @@ -916,9 +964,9 @@ mod tests { } #[test] - fn test_plugin_version_tracks_v3_capability_gate() { + fn test_plugin_version_tracks_row_addr_domain_gate() { let plugin = InvertedIndexPlugin; - assert_eq!(plugin.version(), INVERTED_INDEX_VERSION_V3); + assert_eq!(plugin.version(), INVERTED_ROW_ADDR_DOMAIN_VERSION); } fn list_documents(values: ArrayRef) -> ArrayRef { @@ -956,15 +1004,22 @@ mod tests { ] { let docs = documents(values); let rows = Arc::new(UInt64Array::from_iter_values(0..docs.len() as u64)) as ArrayRef; - let batch = RecordBatch::try_from_iter([("text", docs), (ROW_ID, rows)]).unwrap(); + let batch = + RecordBatch::try_from_iter([("text", docs.clone()), (ROW_ID, rows.clone())]) + .unwrap(); assert_eq!( flat_full_text_search(&[&batch], "text", "alpha", None).unwrap(), expected_rows, ); - let schema = batch.schema(); + // The flat path reads `ROW_ID`; training scans row addresses + // (`InvertedIndexTrainingRequest`). This fixture has no stable row + // ids, so the two are the same values under either name. + let training = RecordBatch::try_from_iter([("text", docs), (ROW_ADDR, rows)]).unwrap(); + let schema = training.schema(); let request = plugin.new_training_request("{}", schema.field(0)).unwrap(); - let input = RecordBatchStreamAdapter::new(schema, futures::stream::iter([Ok(batch)])); + let input = + RecordBatchStreamAdapter::new(schema, futures::stream::iter([Ok(training)])); let cache = Arc::new(LanceCache::no_cache()); let directory = TempDir::default(); let store = Arc::new(LanceIndexStore::new( diff --git a/rust/lance-index/src/scalar/inverted/builder.rs b/rust/lance-index/src/scalar/inverted/builder.rs index 7610114383e..d32c8a0139a 100644 --- a/rust/lance-index/src/scalar/inverted/builder.rs +++ b/rust/lance-index/src/scalar/inverted/builder.rs @@ -32,7 +32,7 @@ use lance_core::utils::tokio::{ IO_CORE_RESERVATION, capture_compute_concurrency, get_global_num_compute_intensive_cpus, get_num_compute_intensive_cpus, limit_compute_concurrency, spawn_cpu, }; -use lance_core::{Error, ROW_ID, Result}; +use lance_core::{Error, ROW_ADDR, ROW_ID, Result}; use lance_index_core::remapping::RowAddrTranslator; use lance_io::object_store::ObjectStore; use lance_select::RowSetOps; @@ -1815,7 +1815,7 @@ impl IndexWorker { async fn process_batch(&mut self, batch: RecordBatch) -> Result<()> { let doc_col = batch.column(0); - let row_id_col = batch[ROW_ID].as_primitive::(); + let row_id_col = batch[ROW_ADDR].as_primitive::(); let doc_index_columns = (0..self.coordinate_rank) .map(|rank| { let column_name = doc_index_storage_column(rank); @@ -3486,7 +3486,6 @@ mod tests { use bytes::Bytes; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use futures::stream::{self, BoxStream}; - use lance_core::ROW_ID; use lance_core::cache::LanceCache; use lance_core::utils::tempfile::TempDir; use lance_core::utils::tokio::with_compute_concurrency; @@ -3507,7 +3506,7 @@ mod tests { fn make_doc_batch(doc: &str, row_id: u64) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let docs = Arc::new(StringArray::from(vec![Some(doc)])); let row_ids = Arc::new(UInt64Array::from(vec![row_id])); @@ -3517,7 +3516,7 @@ mod tests { fn make_doc_batch_from_docs(docs: Vec>) -> RecordBatch { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let num_rows = docs.len(); let docs = Arc::new(StringArray::from(docs)); @@ -4771,7 +4770,7 @@ mod tests { ) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; assert_eq!(index.partition_count(), 1); Ok(()) @@ -4959,7 +4958,7 @@ mod tests { .write_metadata(src_store.as_ref(), &[0]) .await?; - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), true).await?; let derived_params = index.derive_index_params()?; let derived_params: InvertedIndexParams = serde_json::from_str(derived_params.params.as_deref().unwrap())?; @@ -4970,7 +4969,7 @@ mod tests { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let docs = Arc::new(StringArray::from(vec![Some("hello again")])); let row_ids = Arc::new(UInt64Array::from(vec![101u64])); @@ -4981,7 +4980,7 @@ mod tests { .await?; let updated = - InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache()).await?; + InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache(), true).await?; assert_eq!(updated.partitions.len(), 1); for partition in &updated.partitions { assert_eq!( @@ -5063,7 +5062,7 @@ mod tests { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let docs = Arc::new(StringArray::from(vec![Some("hello hello world")])); let row_ids = Arc::new(UInt64Array::from(vec![0u64])); @@ -5081,7 +5080,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(params); builder.update(stream, store.as_ref(), None).await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; assert_eq!(index.partitions.len(), 1); let partition = &index.partitions[0]; let token_id = partition.tokens.get("hello").unwrap(); @@ -5142,7 +5141,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; let (total_tokens, num_docs, token_docs) = index .bm25_stats_for_terms(&["hello".to_string()], None) .await?; @@ -5192,7 +5191,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; assert!(index.partitions.is_empty()); let statistics = index.statistics()?; assert_eq!(statistics["num_tokens"], 0); @@ -5212,7 +5211,7 @@ mod tests { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), Field::new(doc_index_storage_column(0), DataType::UInt32, false), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let batch = RecordBatch::try_new( schema, @@ -5242,7 +5241,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; let statistics = index.statistics()?; assert_eq!(statistics["num_tokens"], 0); assert_eq!(statistics["num_docs"], 5); @@ -6253,7 +6252,7 @@ mod tests { })); batches.push(arrow_array::record_batch!( ("doc", Utf8, docs), - (ROW_ID, UInt64, rows) + (ROW_ADDR, UInt64, rows) )?); } let reference_dir = TempDir::default(); @@ -6303,8 +6302,10 @@ mod tests { builder .write(pipeline_store.as_ref(), files, FinalizeOptions::default()) .await?; - let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; - let actual = InvertedIndex::load(pipeline_store, None, &LanceCache::no_cache()).await?; + let reference = + InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; + let actual = + InvertedIndex::load(pipeline_store, None, &LanceCache::no_cache(), true).await?; if all_null || docs_per_fragment == 0 { assert_eq!(actual.partition_count(), 0); } else { @@ -6500,7 +6501,7 @@ mod tests { builder .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; // The caller keeps the TempDir alive for as long as it queries the // loaded index. Ok((index_dir, index)) @@ -6528,7 +6529,7 @@ mod tests { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let batches = (0..NUM_DOCS / DOCS_PER_BATCH) .map(|batch_idx| { @@ -6886,7 +6887,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(InvertedIndexParams::default()); builder.update(stream, store.as_ref(), None).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); assert!( @@ -6931,7 +6932,7 @@ mod tests { .unwrap(); // Load it back and confirm the invalidated fragments are set - let index = InvertedIndex::load(src_store.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(src_store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert_eq!(index.deleted_fragments(), &initial_deleted); @@ -6945,9 +6946,10 @@ mod tests { .unwrap(); // Reload from dest and verify deleted fragments are preserved - let remapped_index = InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache()) - .await - .unwrap(); + let remapped_index = + InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache(), true) + .await + .unwrap(); assert_eq!( remapped_index.deleted_fragments(), &initial_deleted, @@ -6973,7 +6975,7 @@ mod tests { builder.update(stream, store.as_ref(), None).await.unwrap(); // Load the index and update it with an old_data_filter that invalidates fragments - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert!(index.deleted_fragments().is_empty()); @@ -7003,7 +7005,7 @@ mod tests { .unwrap(); let updated_index = - InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache()) + InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert_eq!( @@ -7031,7 +7033,7 @@ mod tests { builder.update(stream, store1.as_ref(), None).await.unwrap(); // First update: delete fragments 3 and 7 - let index = InvertedIndex::load(store1.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store1.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); @@ -7061,7 +7063,7 @@ mod tests { .unwrap(); // Second update: invalidate additional fragments 12 and 15 - let index2 = InvertedIndex::load(store2.clone(), None, &LanceCache::no_cache()) + let index2 = InvertedIndex::load(store2.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert_eq!( @@ -7093,7 +7095,7 @@ mod tests { .await .unwrap(); - let index3 = InvertedIndex::load(store3.clone(), None, &LanceCache::no_cache()) + let index3 = InvertedIndex::load(store3.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert_eq!( @@ -7119,7 +7121,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(InvertedIndexParams::default()); builder.update(stream, store.as_ref(), None).await.unwrap(); - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); @@ -7147,7 +7149,7 @@ mod tests { .unwrap(); let updated_index = - InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache()) + InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); assert!( @@ -7442,7 +7444,7 @@ mod tests { fn consolidation_corpus(fragments: u32, docs_per_fragment: usize) -> Vec<(u64, RecordBatch)> { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); (0..fragments) .map(|fragment| { @@ -7557,7 +7559,7 @@ mod tests { let batch = arrow_array::record_batch!( ("doc", Utf8, [text]), ( - "_rowid", + "_rowaddr", UInt64, [u64::from(RowAddress::new_from_parts(step, 0))] ) @@ -7618,7 +7620,8 @@ mod tests { .update(input, store.as_ref(), None) .await? }; - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()).await?; + let index = + InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true).await?; if let Some(source) = &previous_store { assert_eq!( source.copy_count.load(Ordering::SeqCst), @@ -7660,7 +7663,8 @@ mod tests { InvertedIndexBuilder::new(params) .update(input, reference_store.as_ref(), None) .await?; - let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; + let reference = + InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; assert_eq!( consolidation_search(previous.as_ref().unwrap(), &["common"], Operator::Or, false) .await, @@ -7709,7 +7713,8 @@ mod tests { assert!(sizes[0].stored_bytes >= ceiling); assert!(sizes[1].stored_bytes < ceiling); - let index = InvertedIndex::load(source.clone(), None, &LanceCache::no_cache()).await?; + let index = + InvertedIndex::load(source.clone(), None, &LanceCache::no_cache(), true).await?; let batch = make_doc_batch("common text", RowAddress::new_from_parts(2, 0).into()); let input = Box::pin(RecordBatchStreamAdapter::new( batch.schema(), @@ -7728,7 +7733,8 @@ mod tests { .with_format_version(builder.format_version) .update(input, dest.as_ref(), None) .await?; - let updated = InvertedIndex::load(dest.clone(), None, &LanceCache::no_cache()).await?; + let updated = + InvertedIndex::load(dest.clone(), None, &LanceCache::no_cache(), true).await?; assert_eq!( updated.partition_count(), 2, @@ -7814,7 +7820,8 @@ mod tests { .await?; (staged_store, files) }; - let index = InvertedIndex::load(output.clone(), None, &LanceCache::no_cache()).await?; + let index = + InvertedIndex::load(output.clone(), None, &LanceCache::no_cache(), true).await?; assert_eq!( index.partition_count(), 1, @@ -7885,7 +7892,8 @@ mod tests { reference_builder .update(Box::pin(stream), reference_store.as_ref(), None) .await?; - let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; + let reference = + InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; for (tokens, operator, phrase) in [ (vec!["common"], Operator::Or, false), diff --git a/rust/lance-index/src/scalar/inverted/combined.rs b/rust/lance-index/src/scalar/inverted/combined.rs index 15e390d9a02..eeefd8deed5 100644 --- a/rust/lance-index/src/scalar/inverted/combined.rs +++ b/rust/lance-index/src/scalar/inverted/combined.rs @@ -59,7 +59,9 @@ pub struct CombinedFieldColumn { pub weight: f32, /// Opened inverted-index segments for this column. pub indices: Vec>, - /// Rows an overlay made stale, in the row-id domain index results use. + /// Rows an overlay made stale, in the domain `indices` store their + /// identifiers in (row addresses from + /// `INVERTED_ROW_ADDR_DOMAIN_VERSION` onward, row ids before it). /// /// The flat scan folds their current values into the corpus, so their old /// values are subtracted from `indices` to avoid counting them twice. diff --git a/rust/lance-index/src/scalar/inverted/combined/testing.rs b/rust/lance-index/src/scalar/inverted/combined/testing.rs index b1ad17b2950..f4cf2196685 100644 --- a/rust/lance-index/src/scalar/inverted/combined/testing.rs +++ b/rust/lance-index/src/scalar/inverted/combined/testing.rs @@ -387,7 +387,7 @@ pub(super) async fn element_document_index( .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); (index, tmpdir) diff --git a/rust/lance-index/src/scalar/inverted/index/format.rs b/rust/lance-index/src/scalar/inverted/index/format.rs index 80691269b71..fa382932503 100644 --- a/rust/lance-index/src/scalar/inverted/index/format.rs +++ b/rust/lance-index/src/scalar/inverted/index/format.rs @@ -8,9 +8,20 @@ use super::*; // Version 2: Fst TokenSetFormat with shared posting-list position streams. // Version 3: Reader capability for configurable posting blocks, analyzer // metadata, and element-document coordinates. +// Version 4: `docs.lance`'s identity column holds physical row addresses +// instead of row ids. Independent of the posting-list format above (still +// read from file metadata, not from this version): a V4 segment can pair +// with any posting format, since training always scans row addresses now +// and this version is only overridden back to one of V1-V3 on a dataset +// without stable row ids, where a row id and a row address are the same +// value. See `ngram_index_version`/`BTREE_ROW_ADDR_DOMAIN_VERSION` for the +// same pattern on other scalar index types. pub const INVERTED_INDEX_VERSION_V1: u32 = 1; pub const INVERTED_INDEX_VERSION_V2: u32 = 2; pub const INVERTED_INDEX_VERSION_V3: u32 = 3; +/// A freshly trained segment stores physical row addresses (`_rowaddr`-domain +/// values) in `docs.lance`'s identity column instead of row ids. +pub const INVERTED_ROW_ADDR_DOMAIN_VERSION: u32 = 4; pub const TOKENS_FILE: &str = "tokens.lance"; pub const INVERT_LIST_FILE: &str = "invert.lance"; pub const DOCS_FILE: &str = "docs.lance"; diff --git a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs index 12346783e7c..d8b4c7996d4 100644 --- a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs +++ b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs @@ -38,6 +38,11 @@ pub struct InvertedIndex { /// Rows this segment may report, intersected into every mask it searches with. /// See [`Self::with_allowed_rows`]. pub(super) allowed_rows: Option>, + /// Whether `docs.lance`'s identity column holds physical row addresses + /// (`true`) or row ids directly (`false`, a segment persisted before + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]). See + /// [`ScalarIndex::results_are_row_addresses`]. + pub(super) results_are_row_addresses: bool, } impl Debug for InvertedIndex { @@ -64,6 +69,9 @@ impl InvertedIndex { } pub(super) fn index_version(&self) -> u32 { + if self.results_are_row_addresses { + return INVERTED_ROW_ADDR_DOMAIN_VERSION; + } if self.params.get_document_granularity().is_list_element() { return INVERTED_INDEX_VERSION_V3; } @@ -214,6 +222,13 @@ impl InvertedIndex { .to_string(), )); } + if segment.results_are_row_addresses != first.results_are_row_addresses { + return Err(Error::index( + "cannot merge inverted index segments that disagree on whether they store \ + row ids or row addresses -- rebuild them into one segment first" + .to_string(), + )); + } } let can_update = match (segments, old_data_filters, first.partitions.as_slice()) { @@ -325,6 +340,7 @@ impl InvertedIndex { document_projections_resident: self.document_projections_resident.clone(), deleted_fragments: self.deleted_fragments.clone(), allowed_rows: self.allowed_rows.clone(), + results_are_row_addresses: self.results_are_row_addresses, })) } @@ -393,6 +409,9 @@ impl InvertedIndex { document_projections_resident: Arc::new(AtomicBool::new(false)), deleted_fragments: RoaringBitmap::new(), allowed_rows: None, + // This ancient (pre-partitioned, no `metadata.lance`) format + // predates the row-address-domain migration entirely. + results_are_row_addresses: false, })) } @@ -463,6 +482,9 @@ impl InvertedIndex { document_projections_resident: Arc::new(AtomicBool::new(false)), deleted_fragments: RoaringBitmap::new(), allowed_rows: None, + // This ancient (pre-partitioned, no `metadata.lance`) format + // predates the row-address-domain migration entirely. + results_are_row_addresses: false, })) } @@ -574,6 +596,7 @@ impl InvertedIndex { store: Arc, frag_reuse_index: Option>, index_cache: &LanceCache, + results_are_row_addresses: bool, ) -> Result> where Self: Sized, @@ -674,6 +697,7 @@ impl InvertedIndex { document_projections_resident: Arc::new(AtomicBool::new(false)), deleted_fragments, allowed_rows: None, + results_are_row_addresses, })) } Err(_) => { @@ -689,6 +713,7 @@ impl InvertedIndex { store: Arc, remapping: Option>, index_cache: &LanceCache, + results_are_row_addresses: bool, ) -> Result> { lance_index_core::remapping::check_batch_remapping_entry()?; // for new index format, there is a metadata file and multiple partitions, @@ -787,6 +812,7 @@ impl InvertedIndex { document_projections_resident: Arc::new(AtomicBool::new(false)), deleted_fragments, allowed_rows: None, + results_are_row_addresses, })) } Err(_) => { @@ -1190,7 +1216,7 @@ impl ScalarIndex for InvertedIndex { } fn update_criteria(&self) -> UpdateCriteria { - let criteria = TrainingCriteria::new(TrainingOrdering::None).with_row_id(); + let criteria = TrainingCriteria::new(TrainingOrdering::None).with_row_addr(); if self.is_legacy() { UpdateCriteria::requires_old_data(criteria) } else { @@ -1201,4 +1227,8 @@ impl ScalarIndex for InvertedIndex { fn derive_index_params(&self) -> Result { Self::params_for_training(self.params.clone(), self.format_version()) } + + fn results_are_row_addresses(&self) -> bool { + self.results_are_row_addresses + } } diff --git a/rust/lance-index/src/scalar/inverted/index/tests.rs b/rust/lance-index/src/scalar/inverted/index/tests.rs index d6db1373bea..8733764c2e1 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests.rs @@ -4,6 +4,7 @@ use crate::scalar::inverted::document_tokenizer::DocType; use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use futures::stream; +use lance_core::ROW_ADDR; use lance_core::cache::{LanceCache, QuickCacheBackend}; use lance_core::utils::tempfile::TempObjDir; use lance_io::object_store::ObjectStore; @@ -48,6 +49,7 @@ async fn write_single_partition_index( token_set_format: TokenSetFormat, token: &str, row_id: u64, + results_are_row_addresses: bool, ) -> Result> { let block_size = params.posting_block_size(); let format_version = params.resolved_format_version(); @@ -94,13 +96,19 @@ async fn write_single_partition_index( .await?; writer.finish_with_metadata(metadata).await?; - InvertedIndex::load(store, None, &LanceCache::no_cache()).await + InvertedIndex::load( + store, + None, + &LanceCache::no_cache(), + results_are_row_addresses, + ) + .await } fn empty_doc_stream() -> SendableRecordBatchStream { let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); Box::pin(RecordBatchStreamAdapter::new( schema, diff --git a/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs b/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs index 9b61ab82fc0..b05a62ccc28 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs @@ -2,6 +2,23 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors use super::*; +use lance_core::ROW_ADDR; + +/// Training always scans row addresses now; relabel a hand-built `_rowid` +/// fixture (shared with the flat/brute-force reference search below, whose +/// own contract is an arbitrary caller-supplied batch literally named +/// `_rowid`) before feeding it to the real indexed builder. +fn as_row_addr_training_input(batch: &RecordBatch) -> RecordBatch { + let schema = batch.schema(); + let row_id_idx = schema.index_of(ROW_ID).unwrap(); + let mut fields = schema.fields().to_vec(); + fields[row_id_idx] = Arc::new(Field::new( + ROW_ADDR, + DataType::UInt64, + fields[row_id_idx].is_nullable(), + )); + RecordBatch::try_new(Arc::new(Schema::new(fields)), batch.columns().to_vec()).unwrap() +} #[rstest::rstest] #[case::or(Operator::Or, None, vec![0, 1, 2])] @@ -184,18 +201,19 @@ async fn test_ngram_phrase_preserves_positions_indexed_and_flat( tmpdir.clone(), Arc::new(LanceCache::no_cache()), )); + let training_batch = as_row_addr_training_input(&batch); InvertedIndexBuilder::new(params.clone()) .update( Box::pin(RecordBatchStreamAdapter::new( - batch.schema(), - stream::iter(vec![Ok(batch.clone())]), + training_batch.schema(), + stream::iter(vec![Ok(training_batch.clone())]), )), store.as_ref(), None, ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); let tokens = try_collect_query_tokens("abcd", &mut params.build().unwrap()).unwrap(); @@ -318,18 +336,19 @@ async fn test_ngram_match_requires_all_terms_indexed_and_flat( tmpdir.clone(), Arc::new(LanceCache::no_cache()), )); + let training_batch = as_row_addr_training_input(&batch); InvertedIndexBuilder::new(params.clone()) .update( Box::pin(RecordBatchStreamAdapter::new( - batch.schema(), - stream::iter(vec![Ok(batch.clone())]), + training_batch.schema(), + stream::iter(vec![Ok(training_batch.clone())]), )), store.as_ref(), None, ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); for (operator, expected) in [(Operator::And, expected_and), (Operator::Or, expected_or)] { @@ -517,18 +536,19 @@ async fn test_document_lengths_indexed_and_flat( )); let mut builder = InvertedIndexBuilder::new(params.clone().with_position(with_position).num_workers(1)); + let training_batch = as_row_addr_training_input(&batch); builder .update( Box::pin(RecordBatchStreamAdapter::new( - batch.schema(), - stream::iter(vec![Ok(batch.clone())]), + training_batch.schema(), + stream::iter(vec![Ok(training_batch.clone())]), )), store.as_ref(), None, ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); let (tokens, num_docs, _) = index.bm25_stats_for_terms(&[], None).await.unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs b/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs index 13eb61c101b..e2b2b8f936e 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs @@ -979,7 +979,7 @@ async fn test_build_search_uses_configured_posting_block_size() { write_test_metadata(&store, vec![0], params).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); assert_eq!(index.partitions[0].inverted_list.block_size(), block_size); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs b/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs index 4c900f4c66a..6b959a46258 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs @@ -564,7 +564,7 @@ async fn test_grouped_bm25_search_correct_and_cache_stable() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs index 45617b0935b..889b13905fa 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors use super::*; +use lance_core::ROW_ADDR; use crate::Index; @@ -24,6 +25,7 @@ async fn test_calculate_included_frags_is_unsupported() -> Result<()> { TokenSetFormat::default(), "hello", 100, + true, ) .await?; @@ -89,7 +91,7 @@ async fn build_multi_partition_index( // Keep the cache alive and return it: the partition readers hold only a // WeakLanceCache, so the prewarmed entries vanish if this Arc is dropped. let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); (index, cache) @@ -209,13 +211,13 @@ async fn test_update_preserves_v2_format_version() -> Result<()> { .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(index.format_version(), format_version); assert_eq!(index.index_version(), INVERTED_INDEX_VERSION_V2); let schema = Arc::new(Schema::new(vec![ Field::new("doc", DataType::Utf8, true), - Field::new(ROW_ID, DataType::UInt64, false), + Field::new(ROW_ADDR, DataType::UInt64, false), ])); let docs = Arc::new(StringArray::from(vec![Some("hello again")])); let row_ids = Arc::new(UInt64Array::from(vec![101u64])); @@ -227,7 +229,7 @@ async fn test_update_preserves_v2_format_version() -> Result<()> { assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V2); - let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(updated.format_version(), format_version); assert_eq!(updated.index_version(), INVERTED_INDEX_VERSION_V2); // Consolidating the two tiny partitions must preserve their V2 format. @@ -281,7 +283,7 @@ async fn test_block_size_256_writes_v3_metadata_and_index_version() -> Result<() write_test_metadata(&src_store, vec![0], params).await; - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(index.format_version(), InvertedListFormatVersion::V3); assert_eq!(index.index_version(), INVERTED_INDEX_VERSION_V3); @@ -290,7 +292,7 @@ async fn test_block_size_256_writes_v3_metadata_and_index_version() -> Result<() .await?; assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V3); - let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(updated.format_version(), InvertedListFormatVersion::V3); assert_eq!(updated.index_version(), INVERTED_INDEX_VERSION_V3); @@ -318,6 +320,7 @@ async fn test_merge_segments_preserves_arrow_token_set_format() -> Result<()> { TokenSetFormat::Arrow, "hello", 100, + false, ) .await?; assert_eq!(index.index_version(), 0); @@ -331,7 +334,7 @@ async fn test_merge_segments_preserves_arrow_token_set_format() -> Result<()> { .await?; assert_eq!(created.index_version, 0); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(merged.index_version(), 0); assert_eq!(merged.token_set_format, TokenSetFormat::Arrow); @@ -374,7 +377,8 @@ async fn test_merge_segments_preserves_format_version( .format_version(format_version); let index = - write_single_partition_index(src_store, params, TokenSetFormat::Fst, "hello", 100).await?; + write_single_partition_index(src_store, params, TokenSetFormat::Fst, "hello", 100, false) + .await?; assert_eq!(index.format_version(), format_version); let created = InvertedIndex::merge_segments( @@ -387,7 +391,7 @@ async fn test_merge_segments_preserves_format_version( .await?; assert_eq!(created.index_version, format_version.index_version()); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(merged.format_version(), format_version); assert_eq!(merged.index_version(), format_version.index_version()); @@ -420,7 +424,7 @@ async fn test_merge_v1_segments_with_empty_segment(#[case] is_empty_first: bool) let params = InvertedIndexParams::default().format_version(InvertedListFormatVersion::V1); write_test_metadata(&empty_store, Vec::new(), params.clone()).await; - let empty = InvertedIndex::load(empty_store, None, &LanceCache::no_cache()).await?; + let empty = InvertedIndex::load(empty_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(empty.partition_count(), 0); assert_eq!(empty.format_version(), InvertedListFormatVersion::V1); @@ -430,6 +434,7 @@ async fn test_merge_v1_segments_with_empty_segment(#[case] is_empty_first: bool) TokenSetFormat::default(), "hello", 100, + false, ) .await?; let segments = if is_empty_first { @@ -448,7 +453,7 @@ async fn test_merge_v1_segments_with_empty_segment(#[case] is_empty_first: bool) .await?; assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V1); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; assert_eq!(merged.format_version(), InvertedListFormatVersion::V1); assert_eq!(merged.index_version(), INVERTED_INDEX_VERSION_V1); @@ -492,11 +497,18 @@ async fn test_merge_segments_uses_memory_limit_for_old_partitions() -> Result<() TokenSetFormat::default(), "alpha", 100, + true, + ) + .await?; + let second = write_single_partition_index( + src_store_2, + params, + TokenSetFormat::default(), + "beta", + 200, + true, ) .await?; - let second = - write_single_partition_index(src_store_2, params, TokenSetFormat::default(), "beta", 200) - .await?; let mut builder = InvertedIndexBuilder::new(InvertedIndexParams::default().memory_limit_mb(0)) .with_token_set_format(TokenSetFormat::default()); @@ -509,7 +521,7 @@ async fn test_merge_segments_uses_memory_limit_for_old_partitions() -> Result<() ) .await?; - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), true).await?; assert_eq!(merged.partitions.len(), 2); let mut partition_ids = merged .partitions @@ -563,7 +575,7 @@ async fn test_modern_index_without_deleted_col_has_empty_bitmap() { .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) .await .unwrap(); assert!( diff --git a/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs b/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs index c4929b35408..64fa7e1cb37 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs @@ -136,7 +136,7 @@ async fn test_prewarm_with_positions_populates_separate_position_cache() { let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(4096), ))); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -257,7 +257,7 @@ async fn test_best_effort_prewarm_reports_missing_requested_positions() { let cache = Arc::new(LanceCache::with_backend(Arc::new( RejectPositionsCacheBackend::new(1 << 20), ))); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); @@ -342,7 +342,7 @@ async fn test_prewarm_with_v2_positions_preserves_shared_stream_codec() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); index diff --git a/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs b/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs index c16877be24c..4775f3247f5 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs @@ -323,8 +323,10 @@ async fn cached_fts_versions_release_posting_readers( None, &version_cache, Box::pin(async move { - Ok(InvertedIndex::load(load_store, None, &load_cache).await? - as Arc) + Ok( + InvertedIndex::load(load_store, None, &load_cache, true).await? + as Arc, + ) }), ) .await @@ -510,7 +512,7 @@ async fn test_posting_cache_conflict_across_partitions() { // Load the inverted index let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -631,7 +633,7 @@ async fn test_modern_prewarm_packs_group_with_shared_posting_buffer() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -932,7 +934,7 @@ async fn test_prewarm_streams_in_chunks_preserves_content( writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -1081,7 +1083,7 @@ async fn test_prewarm_streams_in_chunks_with_positions( let cache = Arc::new(LanceCache::with_backend(Arc::new( CacheWithoutResidentProbe(QuickCacheBackend::with_capacity(1 << 20)), ))); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -1178,7 +1180,7 @@ async fn test_prewarm_streams_in_chunks_with_positions( let probe_cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(1 << 20), ))); - let probe_index = InvertedIndex::load(store, None, probe_cache.as_ref()) + let probe_index = InvertedIndex::load(store, None, probe_cache.as_ref(), true) .await .unwrap(); let probe_inverted_list = &probe_index.partitions[0].inverted_list; @@ -1259,7 +1261,7 @@ async fn test_prewarm_restores_metadata_after_persistent_posting_pressure( ..Default::default() }); let cache = Arc::new(LanceCache::with_backend(backend.clone())); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); let options = FtsPrewarmOptions { @@ -1334,7 +1336,7 @@ async fn test_strict_modern_prewarm_fails_when_index_cache_cannot_hold_all_parti let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(8 * 1024), ))); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/query.rs b/rust/lance-index/src/scalar/inverted/index/tests/query.rs index 0b2f839259e..f62c26144ce 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/query.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/query.rs @@ -93,7 +93,7 @@ async fn test_prefilter_skips_excluded_partition_postings( let remapper = translated.then(|| Arc::new(OffsetBatchRemapper::default()) as Arc); let reference = - InvertedIndex::load_with_remapping(store, remapper.clone(), &LanceCache::no_cache()) + InvertedIndex::load_with_remapping(store, remapper.clone(), &LanceCache::no_cache(), true) .await .unwrap(); let tokens = Tokens::new(vec!["alpha".to_owned(), "beta".to_owned()], DocType::Text); @@ -145,7 +145,7 @@ async fn test_prefilter_skips_excluded_partition_postings( posting_file: posting_file_path(1), counter: counter.clone(), }); - let index = InvertedIndex::load_with_remapping(store, remapper, &LanceCache::no_cache()) + let index = InvertedIndex::load_with_remapping(store, remapper, &LanceCache::no_cache(), true) .await .unwrap(); // Statistics still cover both partitions. Only candidate posting reads may be skipped. @@ -221,12 +221,13 @@ async fn test_single_partition_merge_preserves_remapping_and_filtering( TokenSetFormat::default(), "hit", 100, + true, ) .await?; let remapper = translated.then(|| Arc::new(OffsetBatchRemapper::default()) as Arc); let index = - InvertedIndex::load_with_remapping(source, remapper, &LanceCache::no_cache()).await?; + InvertedIndex::load_with_remapping(source, remapper, &LanceCache::no_cache(), true).await?; let old_row = if translated { 1100 } else { 100 }; let filter = keep_old.map(|keep| { crate::scalar::OldIndexDataFilter::RowIds(if keep { @@ -235,7 +236,7 @@ async fn test_single_partition_merge_preserves_remapping_and_filtering( RowAddrTreeMap::new() }) }); - let batch = arrow_array::record_batch!(("doc", Utf8, ["hit"]), ("_rowid", UInt64, [200]))?; + let batch = arrow_array::record_batch!(("doc", Utf8, ["hit"]), ("_rowaddr", UInt64, [200]))?; let input = Box::pin(RecordBatchStreamAdapter::new( batch.schema(), stream::iter([Ok(batch)]), @@ -250,7 +251,7 @@ async fn test_single_partition_merge_preserves_remapping_and_filtering( .await?; // Reload without any translator: maintenance must have persisted the // current old address, while leaving the newly appended address alone. - let updated = InvertedIndex::load(dest, None, &LanceCache::no_cache()).await?; + let updated = InvertedIndex::load(dest, None, &LanceCache::no_cache(), true).await?; let (mut row_ids, _) = updated .bm25_search( Arc::new(Tokens::new(vec!["hit".to_owned()], DocType::Text)), @@ -287,6 +288,7 @@ async fn translated_fts_snapshot_rebinds_current_store_and_releases_request_reso TokenSetFormat::default(), "hit", 100, + true, ) .await .unwrap(); @@ -294,7 +296,7 @@ async fn translated_fts_snapshot_rebinds_current_store_and_releases_request_reso let remapper = Arc::new(OffsetBatchRemapper::default()); let remapper_weak = Arc::downgrade(&remapper); let cache = LanceCache::with_capacity(1 << 20); - let index = InvertedIndex::load_with_remapping(store, Some(remapper.clone()), &cache) + let index = InvertedIndex::load_with_remapping(store, Some(remapper.clone()), &cache, true) .await .unwrap(); index.prewarm().await.unwrap(); @@ -410,8 +412,10 @@ async fn test_request_wrappers_preserve_prewarmed_index_state() { None, &cache, async move { - Ok(InvertedIndex::load(load_store, None, &load_cache).await? - as Arc) + Ok( + InvertedIndex::load(load_store, None, &load_cache, true).await? + as Arc, + ) } .boxed(), ) @@ -452,7 +456,9 @@ async fn test_request_wrappers_preserve_prewarmed_index_state() { Some((4, 2, vec![2, 1])) ); } - let independently_loaded = InvertedIndex::load(store, None, &cache).await.unwrap(); + let independently_loaded = InvertedIndex::load(store, None, &cache, true) + .await + .unwrap(); assert!( !first .unwrap() @@ -583,7 +589,7 @@ async fn test_write_many_posting_list_batches_preserves_all_batches() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -642,7 +648,7 @@ async fn test_and_query_skips_partition_missing_required_term() { write_test_metadata(&store, vec![0, 1], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -696,7 +702,7 @@ async fn test_fuzzy_and_groups_expansions_by_original_position() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); let params = Arc::new( @@ -791,7 +797,7 @@ async fn test_fuzzy_expansion_cap_applies_to_whole_query( write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); let partition = index.partitions[0].clone(); @@ -906,7 +912,7 @@ async fn load_test_index( partition_ids: Vec, ) -> Arc { write_test_metadata(&store, partition_ids, InvertedIndexParams::default()).await; - InvertedIndex::load(store, None, &LanceCache::with_capacity(4096)) + InvertedIndex::load(store, None, &LanceCache::with_capacity(4096), true) .await .unwrap() } @@ -960,7 +966,7 @@ async fn test_sync_df_requires_all_segments_and_preserves_scorer_bits() { .await; write_test_metadata(&first_store, vec![0], InvertedIndexParams::default()).await; let first_cache = Arc::new(LanceCache::with_capacity(4096)); - let first = InvertedIndex::load(first_store, None, first_cache.as_ref()) + let first = InvertedIndex::load(first_store, None, first_cache.as_ref(), true) .await .unwrap(); @@ -973,7 +979,7 @@ async fn test_sync_df_requires_all_segments_and_preserves_scorer_bits() { write_pair_partition(&second_store, 0, &[("alpha", "beta", 200)]).await; write_test_metadata(&second_store, vec![0], InvertedIndexParams::default()).await; let second_cache = Arc::new(LanceCache::with_capacity(4096)); - let second = InvertedIndex::load(second_store, None, second_cache.as_ref()) + let second = InvertedIndex::load(second_store, None, second_cache.as_ref(), true) .await .unwrap(); @@ -1135,7 +1141,9 @@ async fn load_prewarmed_index( ) -> (Arc, LanceCache) { write_test_metadata(&store, partition_ids, params).await; let cache = LanceCache::with_capacity(1 << 20); - let index = InvertedIndex::load(store, None, &cache).await.unwrap(); + let index = InvertedIndex::load(store, None, &cache, true) + .await + .unwrap(); index .prewarm_with_options(&FtsPrewarmOptions::default()) .await @@ -1688,7 +1696,7 @@ async fn test_fuzzy_expansion_cap_is_global_across_partitions() { write_variant_partition(&store, 1, &["alphc", "alphd"], &[102, 103]).await; write_test_metadata(&store, vec![0, 1], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -1811,7 +1819,9 @@ async fn test_fuzzy_results_independent_of_partition_shape() { let mut results = Vec::new(); for store in [single_store, split_store] { let cache = LanceCache::with_capacity(4096); - let index = InvertedIndex::load(store, None, &cache).await.unwrap(); + let index = InvertedIndex::load(store, None, &cache, true) + .await + .unwrap(); let tokens = Arc::new(Tokens::new(vec!["alphx".to_owned()], DocType::Text)); let (row_ids, scores) = index .bm25_search( @@ -1877,7 +1887,7 @@ async fn test_fuzzy_and_scores_grouped_expansions_by_matched_token() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -1936,7 +1946,7 @@ async fn test_grouped_scoring_keeps_exact_winner_outside_proxy_window(#[case] op write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -1997,7 +2007,7 @@ async fn test_fuzzy_and_grouped_rescore_keeps_wand_limit_bounded() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -2093,7 +2103,7 @@ async fn test_phrase_query_reads_legacy_per_doc_positions() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -2146,7 +2156,7 @@ async fn test_exact_single_term_phrase_uses_frequencies_without_positions( partition.write(store.as_ref()).await.unwrap(); write_test_metadata(&store, vec![0], params).await; - let index = InvertedIndex::load(store, None, &LanceCache::with_capacity(1 << 20)) + let index = InvertedIndex::load(store, None, &LanceCache::with_capacity(1 << 20), true) .await .unwrap(); let tokens = Arc::new(Tokens::with_positions( @@ -2205,6 +2215,7 @@ async fn test_exact_single_term_phrase_still_requires_positional_index() { TokenSetFormat::default(), "hit", 100, + true, ) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs index ae105343081..6c99b7c3e84 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs @@ -56,7 +56,7 @@ async fn test_bm25_search_uses_global_idf() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -183,7 +183,7 @@ async fn load_test_index( } write_test_metadata(&store, partition_ids, InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); (tmpdir, cache, index) @@ -246,7 +246,7 @@ async fn load_global_scoring_test_index( let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(64 * 1024), ))); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); (tmpdir, cache, index) @@ -543,7 +543,7 @@ async fn test_chunked_modern_search_preserves_cold_and_prewarmed_results() { ) .await; let cache = Arc::new(LanceCache::with_capacity(64 * 1024 * 1024)); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); let tokens = Arc::new(Tokens::new(vec!["pipeline".to_owned()], DocType::Text)); @@ -879,7 +879,7 @@ async fn load_no_impact_bulk_conjunction_test_index( let params = InvertedIndexParams::default().with_position(with_positions); write_test_metadata(&store, vec![0, 1], params).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); (tmpdir, cache, index) @@ -1192,7 +1192,7 @@ async fn test_and_query_returns_empty_when_exact_term_missing() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) .await .unwrap(); @@ -1261,7 +1261,7 @@ async fn test_and_query_accepts_same_position_alternatives() { builder.write(store.as_ref()).await.unwrap(); write_test_metadata(&store, vec![0], InvertedIndexParams::code()).await; - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); @@ -1332,7 +1332,7 @@ async fn test_phrase_query_accepts_same_position_alternatives() { InvertedIndexParams::code().with_position(true), ) .await; - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/stats.rs b/rust/lance-index/src/scalar/inverted/index/tests/stats.rs index 84a2f7d4fd4..d85acb3baea 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/stats.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/stats.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors use super::*; +use lance_core::ROW_ADDR; use lance_core::cache::{ CacheBackend, CacheCodec, CacheEntry, InternalCacheKey, QuickCacheBackend, }; @@ -280,7 +281,7 @@ async fn load_counted_v2_index_with_counter( posting_file: posting_file_path(0), counter: counter.clone(), }); - let index = InvertedIndex::load(counting_store, None, &cache) + let index = InvertedIndex::load(counting_store, None, &cache, true) .await .unwrap(); (index, counter, tmpdir) @@ -351,7 +352,7 @@ async fn load_counted_v3_index( Utf8, ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"] ), - (ROW_ID, UInt64, [0, 1, 2, 3, 4, 5, 6, 7]) + (ROW_ADDR, UInt64, [0, 1, 2, 3, 4, 5, 6, 7]) ) .unwrap(); let params = InvertedIndexParams::default() @@ -381,7 +382,9 @@ async fn load_counted_v3_index( posting_file: posting_file_path(partitions[0]), counter: counter.clone(), }); - let index = InvertedIndex::load(store, None, &cache).await.unwrap(); + let index = InvertedIndex::load(store, None, &cache, true) + .await + .unwrap(); assert_eq!(index.format_version(), InvertedListFormatVersion::V3); (index, counter, tmpdir) } @@ -1413,7 +1416,7 @@ async fn load_v2_index_with_grouped_postings( // The inverted list keeps only a `WeakLanceCache`, so the caller must // hold this `Arc` alive for the cache to stay usable. let cache = Arc::new(LanceCache::with_capacity(1 << 30)); - let index = InvertedIndex::load(store, None, cache.as_ref()) + let index = InvertedIndex::load(store, None, cache.as_ref(), true) .await .unwrap(); (index, cache) diff --git a/rust/lance-index/src/scalar/registry.rs b/rust/lance-index/src/scalar/registry.rs index a4e2d31ea62..d622c690bcf 100644 --- a/rust/lance-index/src/scalar/registry.rs +++ b/rust/lance-index/src/scalar/registry.rs @@ -1031,10 +1031,10 @@ mod tests { .await .unwrap(); let index_cache = LanceCache::no_cache(); - let index_a = InvertedIndex::load(store_a.clone(), None, &index_cache) + let index_a = InvertedIndex::load(store_a.clone(), None, &index_cache, true) .await .unwrap(); - let index_b = InvertedIndex::load(store_b.clone(), None, &index_cache) + let index_b = InvertedIndex::load(store_b.clone(), None, &index_cache, true) .await .unwrap(); [(store_a, index_a), (store_b, index_b)] diff --git a/rust/lance-table/src/format/index.rs b/rust/lance-table/src/format/index.rs index 25da7180ef6..a727454c30d 100644 --- a/rust/lance-table/src/format/index.rs +++ b/rust/lance-table/src/format/index.rs @@ -203,7 +203,11 @@ impl IndexDetailsType { ZoneMap | BloomFilter | Fm | ListElement => Some(0), BTree | Bitmap | NGram | RTree | MinHashLsh | Json => Some(1), LabelList => Some(2), - Inverted | Vector => None, + // Inverted's versions 1-3 are posting-list format capability + // bumps unrelated to domain; see + // `lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION`. + Inverted => Some(4), + Vector => None, } } } @@ -382,7 +386,7 @@ impl IndexMetadata { /// fragments, rather than just losing coverage of them until rebuilt. /// /// Of the address-domain types, BTree, Bitmap, LabelList, ListElement, NGram, - /// RTree and MinHash LSH's indexes support this today + /// RTree, MinHash LSH and Inverted's indexes support this today /// (`ScalarIndexPlugin::can_remap`); ZoneMap, BloomFilter and FM cannot remap. This gate recognizes the /// supported built-in address-domain formats without opening index files. pub fn supports_eager_remap(&self) -> bool { @@ -398,6 +402,7 @@ impl IndexMetadata { | IndexDetailsType::NGram | IndexDetailsType::RTree | IndexDetailsType::MinHashLsh + | IndexDetailsType::Inverted ) ) && kind .and_then(IndexDetailsType::row_address_version) @@ -1497,7 +1502,6 @@ mod tests { #[case::bitmap_alias("type.googleapis.com/LANCE.INDEX.PB.BITMAPINDEXDETAILS", false, true)] #[case::label_list("type.googleapis.com/lance.table.LabelListIndexDetails", false, true)] #[case::ngram("type.googleapis.com/lance.table.NGramIndexDetails", false, true)] - #[case::inverted("type.googleapis.com/lance.table.InvertedIndexDetails", false, true)] #[case::vector("type.googleapis.com/lance.index.pb.VectorIndexDetails", false, true)] #[case::vector_legacy("type.googleapis.com/lance.index.VectorIndexDetails", false, true)] #[case::json_without_target( @@ -1541,6 +1545,7 @@ mod tests { #[case::minhash_lsh("type.googleapis.com/lance.index.pb.MinHashLshIndexDetails", 1, true)] #[case::bitmap("type.googleapis.com/lance.table.BitmapIndexDetails", 1, true)] #[case::label_list("type.googleapis.com/lance.table.LabelListIndexDetails", 2, true)] + #[case::inverted("type.googleapis.com/lance.table.InvertedIndexDetails", 4, true)] fn test_results_are_row_addrs_is_version_gated( #[case] type_url: &str, #[case] addr_domain_version: i32, diff --git a/rust/lance/src/dataset/mem_wal/index/tests.rs b/rust/lance/src/dataset/mem_wal/index/tests.rs index 05d721607a2..072e771435d 100644 --- a/rust/lance/src/dataset/mem_wal/index/tests.rs +++ b/rust/lance/src/dataset/mem_wal/index/tests.rs @@ -760,6 +760,9 @@ fn fts_from_metadata_preserves_format_version() { (1, InvertedListFormatVersion::V1), (2, InvertedListFormatVersion::V2), (3, InvertedListFormatVersion::V3), + // INVERTED_ROW_ADDR_DOMAIN_VERSION: orthogonal to the posting-list + // format, which defaults to V3 for it just as it does for V3 itself. + (4, InvertedListFormatVersion::V3), ] { let config = FtsMemIndexPlugin::resolve_from_metadata( "fts_idx", @@ -781,10 +784,11 @@ fn fts_from_metadata_rejects_unsupported_format_version() { let arrow_schema = create_test_schema(); let schema = LanceSchema::try_from(arrow_schema.as_ref()).unwrap(); - let err = FtsMemIndexPlugin::resolve_from_metadata("fts_idx", &schema, &fts_index_metadata(4)) + // 4 (INVERTED_ROW_ADDR_DOMAIN_VERSION) is supported now; 5 is not. + let err = FtsMemIndexPlugin::resolve_from_metadata("fts_idx", &schema, &fts_index_metadata(5)) .unwrap_err(); assert!( - err.to_string().contains("unsupported index_version 4"), + err.to_string().contains("unsupported index_version 5"), "{err}" ); } diff --git a/rust/lance/src/dataset/optimize/tests.rs b/rust/lance/src/dataset/optimize/tests.rs index a89d35de763..42c34650fab 100644 --- a/rust/lance/src/dataset/optimize/tests.rs +++ b/rust/lance/src/dataset/optimize/tests.rs @@ -344,10 +344,10 @@ enum IndexPresence { } /// `cat` is a Utf8 column alongside the numeric `i` one so a test can build -/// a row-id-domain index (e.g. NGram) over it -- every remaining -/// row-id-domain scalar index type requires a text column, unlike BTree, -/// Bitmap, and LabelList, which moved to row-address domain and no longer -/// serve as that fixture. +/// a text-column scalar index (e.g. Inverted) over it. No scalar index type +/// is row-id-domain anymore (Inverted's migration to +/// `INVERTED_ROW_ADDR_DOMAIN_VERSION` was the last one), so this is purely +/// about needing a text column, not about domain. async fn stable_row_id_dataset(uri: &str, num_fragments: u32) -> Dataset { lance_datagen::gen_batch() .col("i", lance_datagen::array::step::()) @@ -1025,10 +1025,10 @@ async fn assert_id_idx_answers_every_row(dataset: &Dataset, index_name: &str) { /// 12 rows over 3 fragments with a zone map on `value`, stable row ids on. /// /// `cat` is a Utf8 column alongside the numeric `id`/`value` ones so a test -/// can build a row-id-domain index (e.g. NGram) over it -- every remaining -/// row-id-domain scalar index type requires a text column, unlike BTree and -/// Bitmap, which moved to row-address domain and no longer serve as that -/// fixture. +/// can build a text-column scalar index (e.g. Inverted) over it. No scalar +/// index type is row-id-domain anymore (Inverted's migration to +/// `INVERTED_ROW_ADDR_DOMAIN_VERSION` was the last one), so this is purely +/// about needing a text column, not about domain. async fn zonemap_stable_row_id_dataset(uri: &str) -> Dataset { let batch = arrow_array::record_batch!( ("id", Int32, (0..12).collect::>()), diff --git a/rust/lance/src/dataset/optimize/tests/commit.rs b/rust/lance/src/dataset/optimize/tests/commit.rs index 1c191cfff13..b5b9f66cf13 100644 --- a/rust/lance/src/dataset/optimize/tests/commit.rs +++ b/rust/lance/src/dataset/optimize/tests/commit.rs @@ -563,18 +563,28 @@ async fn test_commit_refuses_recording_mismatch_before_reserving_fragments( ); } if matches!(mismatch, RecordingMismatch::IncompatibleIndexCreated) { - // Inverted: the other scalar index types now always create an + // Every scalar index type, Inverted included, now always creates an // address-domain segment on a stable-row-id dataset (safe alongside - // the recorded moves by construction), so none of them can illustrate - // this mismatch. Inverted still stores row ids directly here. + // the recorded moves by construction), so illustrating this mismatch + // needs a row-id-domain segment simulated by relabeling a freshly + // built one's `index_version` down -- the same trick + // `results_are_row_addrs` itself relies on to tell the two apart. + let segment = CreateIndexBuilder::new( + &mut dataset, + &["cat"], + IndexType::Inverted, + &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), + ) + .name("i_idx".to_string()) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; dataset - .create_index( - &["cat"], - IndexType::Inverted, - Some("i_idx".into()), - &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), - false, - ) + .commit_existing_index_segments("i_idx", "cat", vec![legacy_segment]) .await .unwrap(); } diff --git a/rust/lance/src/dataset/optimize/tests/frag_reuse.rs b/rust/lance/src/dataset/optimize/tests/frag_reuse.rs index 8c785c1b17a..12e8278c00b 100644 --- a/rust/lance/src/dataset/optimize/tests/frag_reuse.rs +++ b/rust/lance/src/dataset/optimize/tests/frag_reuse.rs @@ -2870,14 +2870,23 @@ async fn test_compact_ngram_with_stable_row_ids(#[values(false, true)] defer_ind #[tokio::test] async fn test_defer_index_remap_rejected_while_row_id_index_present() { let mut dataset = zonemap_stable_row_id_dataset("memory://").await; + // A fresh Inverted index always trains in row-address domain, so a + // row-id-domain one (as every segment predating + // `INVERTED_ROW_ADDR_DOMAIN_VERSION` is) has to be simulated by relabeling + // a freshly built segment's `index_version` down -- the same trick + // `results_are_row_addrs` itself relies on to tell the two apart. + let params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); + let segment = CreateIndexBuilder::new(&mut dataset, &["cat"], IndexType::Inverted, ¶ms) + .name("id_idx".into()) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; dataset - .create_index( - &["cat"], - IndexType::Inverted, - Some("id_idx".into()), - &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), - false, - ) + .commit_existing_index_segments("id_idx", "cat", vec![legacy_segment]) .await .unwrap(); @@ -2956,7 +2965,9 @@ async fn test_defer_index_remap_allows_a_repack_only_plan() { ); } /// The mirror image: once an FRI is live, a row-id-domain index cannot be -/// added, because the FRI would be applied to it on load. +/// added, because the FRI would be applied to it on load. Vector indices are +/// the only kind that still is: every scalar index type, Inverted included, +/// now trains in row-address domain. #[tokio::test] async fn test_create_row_id_domain_index_rejected_under_frag_reuse() { let mut dataset = zonemap_stable_row_id_dataset("memory://").await; @@ -2979,7 +2990,9 @@ async fn test_create_row_id_domain_index_rejected_under_frag_reuse() { .is_some() ); - let err = dataset + // Address-domain indices are allowed: the FRI repairs them. Inverted + // included now -- it no longer trains in row-id domain. + dataset .create_index( &["cat"], IndexType::Inverted, @@ -2988,12 +3001,7 @@ async fn test_create_row_id_domain_index_rejected_under_frag_reuse() { false, ) .await - .unwrap_err(); - assert!(matches!(err, Error::InvalidInput { .. })); - let msg = err.to_string(); - assert!(msg.contains("fragment reuse index"), "{msg}"); - - // Address-domain indices are still allowed: the FRI repairs them. + .unwrap(); dataset .create_index( &["id"], @@ -3017,6 +3025,72 @@ async fn test_create_row_id_domain_index_rejected_under_frag_reuse() { assert_zonemap_answers_match_scan(&dataset).await; assert_id_idx_answers_every_row(&dataset, "id_btree").await; } + +/// Vector indices still train in row-id domain, so they are still refused +/// while an FRI is live -- the scalar-only half of the story above. +#[tokio::test] +async fn test_create_vector_index_rejected_under_frag_reuse() { + const DIM: u32 = 16; + let mut dataset = lance_datagen::gen_batch() + .col("id", lance_datagen::array::step::()) + .col( + "vec", + lance_datagen::array::rand_vec::(Dimension::from(DIM)), + ) + .into_dataset_with_params( + "memory://", + FragmentCount::from(3), + FragmentRowCount::from(4), + Some(WriteParams { + enable_stable_row_ids: true, + max_rows_per_file: 4, + ..Default::default() + }), + ) + .await + .unwrap(); + compact_files( + &mut dataset, + CompactionOptions { + target_rows_per_fragment: 512, + defer_index_remap: true, + ..Default::default() + }, + None, + ) + .await + .unwrap(); + assert!( + dataset + .load_index_by_name(FRAG_REUSE_INDEX_NAME) + .await + .unwrap() + .is_some() + ); + + let centroids = FixedSizeListArray::try_new_from_values( + Float32Array::from_iter_values(std::iter::repeat_n(0.0, DIM as usize)), + DIM as i32, + ) + .unwrap(); + let params = VectorIndexParams::with_ivf_flat_params( + DistanceType::L2, + IvfBuildParams::try_with_centroids(1, Arc::new(centroids)).unwrap(), + ); + let err = dataset + .create_index( + &["vec"], + IndexType::Vector, + Some("vec_idx".into()), + ¶ms, + false, + ) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. })); + let msg = err.to_string(); + assert!(msg.contains("fragment reuse index"), "{msg}"); +} /// Index creation and a deferred compaction race, and each one's guard looks /// at a snapshot taken before the other committed. /// @@ -3050,16 +3124,23 @@ async fn test_defer_index_remap_racing_row_id_index_creation() { let completed = execute_compaction_plan(&dataset, &options).await; // A concurrent writer adds one and commits first. No FRI exists yet, so - // nothing refuses it. + // nothing refuses it. A fresh Inverted index always trains in + // row-address domain, so a row-id-domain one is simulated the same way + // `test_defer_index_remap_rejected_while_row_id_index_present` does: relabel a + // freshly built segment's `index_version` down. let mut concurrent = Dataset::open(test_uri).await.unwrap(); + let params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); + let segment = CreateIndexBuilder::new(&mut concurrent, &["cat"], IndexType::Inverted, ¶ms) + .name("id_idx".into()) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; concurrent - .create_index( - &["cat"], - IndexType::Inverted, - Some("id_idx".into()), - &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), - false, - ) + .commit_existing_index_segments("id_idx", "cat", vec![legacy_segment]) .await .unwrap(); assert!(concurrent.manifest.version > dataset.manifest.version); @@ -3228,9 +3309,10 @@ async fn test_row_id_index_creation_racing_defer_index_remap_disjoint_coverage() #[rstest] #[tokio::test] async fn test_index_creation_racing_deferred_compaction_with_stable_row_ids( - // Inverted: every other scalar index type now always creates an + // Inverted: every scalar index type now always creates an // address-domain segment on a stable-row-id dataset (safe alongside an - // FRI by construction), so only Inverted still illustrates this race. + // FRI by construction) -- `create_index` below relabels a freshly built + // Inverted segment back to row-id domain to keep illustrating this race. #[values(IndexType::Inverted, IndexType::ZoneMap)] index_type: IndexType, #[values(false, true)] index_commits_first: bool, #[values(false, true)] is_disjoint: bool, @@ -3278,11 +3360,25 @@ async fn test_index_creation_racing_deferred_compaction_with_stable_row_ids( }; let create_index = async |dataset: &mut Dataset| { let columns = [index_column]; - let builder = dataset + let mut builder = dataset .create_index_builder(&columns, index_type, ¶ms) .name("i_idx".into()); if is_disjoint { - builder.fragments(vec![2]).await.map(|_| ()) + builder = builder.fragments(vec![2]); + } + if index_type == IndexType::Inverted { + // A fresh Inverted index always trains in row-address domain; + // relabel it to simulate the pre-migration (row-id-domain) + // segment this race specifically exercises (same trick as + // `test_defer_index_remap_racing_row_id_index_creation`). + let segment = builder.execute_uncommitted().await?; + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; + dataset + .commit_existing_index_segments("i_idx", index_column, vec![legacy_segment]) + .await } else { builder.await.map(|_| ()) } diff --git a/rust/lance/src/dataset/write/update.rs b/rust/lance/src/dataset/write/update.rs index c43d09af10d..94301496d3a 100644 --- a/rust/lance/src/dataset/write/update.rs +++ b/rust/lance/src/dataset/write/update.rs @@ -998,6 +998,7 @@ mod tests { read_spilled_row_ids, read_spilled_versions, }; use crate::dataset::{NewColumnTransform, WriteDestination, WriteMode}; + use crate::index::CreateIndexBuilder; use crate::index::DatasetIndexExt; use crate::index::vector::VectorIndexParams; use crate::utils::test::{DatagenExt, FailingProxyStore, FragmentCount, FragmentRowCount}; @@ -1025,7 +1026,7 @@ mod tests { use lance_io::object_store::ObjectStoreParams; use lance_linalg::distance::MetricType; use lance_table::feature_flags::FLAG_MIXED_DATA_FILE_VERSIONS; - use lance_table::format::ROW_CREATED_AT_VERSION_FIELD_ID; + use lance_table::format::{IndexMetadata, ROW_CREATED_AT_VERSION_FIELD_ID}; use object_store::throttle::ThrottleConfig; use rstest::rstest; use tokio::sync::Barrier; @@ -1886,16 +1887,23 @@ mod tests { .await .unwrap(); - // Need to use a row-id-domain index (while we still have one) + // A fresh Inverted index always trains in row-address domain, so a + // row-id-domain one is simulated by relabeling a freshly built + // segment's `index_version` down -- the same trick + // `results_are_row_addrs` itself relies on to tell the two apart. let scalar_params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); + let segment = + CreateIndexBuilder::new(&mut dataset, &["str"], IndexType::Inverted, &scalar_params) + .name("str_idx".to_string()) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; dataset - .create_index( - &["str"], - IndexType::Inverted, - Some("str_idx".to_string()), - &scalar_params, - true, - ) + .commit_existing_index_segments("str_idx", "str", vec![legacy_segment]) .await .unwrap(); diff --git a/rust/lance/src/index/append.rs b/rust/lance/src/index/append.rs index 4eba2591319..051ebfd7f76 100644 --- a/rust/lance/src/index/append.rs +++ b/rust/lance/src/index/append.rs @@ -1466,9 +1466,12 @@ async fn merge_scalar_indices<'a>( /// domain store row ids, so a stable-row-id dataset must rebuild rather than /// merge them with newly scanned (address-domain) data. fn has_legacy_row_id_domain(index_type: IndexType) -> bool { - // MinHash LSH moved too, but it never writes its row-id-domain layout, so - // it has no `row_id_domain_version` to relabel a new segment with. - index_type == IndexType::MinHashLsh + // MinHash LSH and Inverted moved too, but neither has a single constant + // `row_id_domain_version` to relabel a new segment with: MinHash LSH + // never writes its row-id-domain layout at all, and Inverted's legacy + // version depends on posting format and document granularity (see + // `InvertedIndexPlugin::relabel_as_row_id_domain`). + matches!(index_type, IndexType::MinHashLsh | IndexType::Inverted) || super::scalar::row_id_domain_version(&index_type.to_string()).is_some() } @@ -2201,6 +2204,15 @@ pub async fn merge_indices_with_unindexed_frags<'a>( && old_indices .iter() .all(|idx| super::segment::segment_has_inverted_details(idx)) + // A segment persisted before `INVERTED_ROW_ADDR_DOMAIN_VERSION` + // stores row ids. On a stable-row-id dataset those differ from the + // addresses a fresh scan yields, so an appended delta would leave + // one named index holding both domains. Leave such an index to the + // `legacy_domain_mismatch` rebuild below instead. + && !(dataset.manifest.uses_stable_row_ids() + && old_indices + .iter() + .any(|idx| !idx.results_are_row_addrs())) && let Some(reference) = old_indices.last() && reference .files @@ -2216,7 +2228,10 @@ pub async fn merge_indices_with_unindexed_frags<'a>( } let params = super::scalar::load_scalar_segment_params(&dataset, reference).await?; let fts_params = serde_json::from_str(params.params.as_deref().unwrap_or("{}"))?; - let criteria = TrainingCriteria::new(TrainingOrdering::None).with_row_id(); + // Every Inverted build now trains on row addresses; without + // stable row ids `build_scalar_index` relabels the result to a + // legacy version, where the two domains coincide anyway. + let criteria = TrainingCriteria::new(TrainingOrdering::None).with_row_addr(); let data = load_fts_training_data( &dataset, resolved, @@ -2301,7 +2316,21 @@ pub async fn merge_indices_with_unindexed_frags<'a>( .ok_or_else(|| { Error::index("expected inverted index training parameters") })?; - if update_criteria.requires_old_data { + // A segment persisted before `INVERTED_ROW_ADDR_DOMAIN_VERSION` + // stores row ids directly. On a stable-row-id dataset those + // differ from the row addresses a fresh scan now yields, so + // such a segment cannot be merged with (or sit alongside) one + // that stores addresses -- checked across every segment of + // this named index, not just the ones `select_segments_to_merge` + // selected, so a stray legacy segment outside that window still + // forces the full rebuild below instead of silently coexisting + // with the fresh segment it produces. Harmless without stable + // row ids, where the two domains coincide. + let legacy_domain_mismatch = dataset.manifest.uses_stable_row_ids() + && old_indices + .iter() + .any(|segment| !segment.results_are_row_addrs()); + if update_criteria.requires_old_data || legacy_domain_mismatch { let params = reference_index.derive_index_params()?; let resolved = resolved_fts.as_ref().ok_or_else(|| { Error::internal( @@ -2411,10 +2440,15 @@ pub async fn merge_indices_with_unindexed_frags<'a>( let mut frag_bitmap = base_unindexed_bitmap; let mut selected_indices = Vec::with_capacity(selected_old_indices.len()); // Each segment keeps only its old rows still stored in the - // fragments it covers. Under stable row ids a rewritten row - // keeps its row id while it moves into a fragment a sibling - // covers, so a filter over the union of all coverage would - // keep the old segment's stale posting for it. + // fragments it covers. A row-id-domain segment (legacy, + // predating `INVERTED_ROW_ADDR_DOMAIN_VERSION`) needs this: + // under stable row ids a rewritten row keeps its row id + // while it moves into a fragment a sibling covers, so a + // filter over the union of all coverage would keep the old + // segment's stale posting for it. An address-domain + // segment's own stored addresses already stop being live + // when a row moves, so its filter is fragment/deletion + // based instead (see `build_old_data_filter`). let mut old_data_filters = Vec::with_capacity(selected_old_indices.len()); // On a tagged table a selected segment's old data is the // coverage the reader derives for it (translated, live) @@ -2438,15 +2472,14 @@ pub async fn merge_indices_with_unindexed_frags<'a>( effective } }; - old_data_filters.push( - build_old_data_filter( - dataset.as_ref(), - &effective_old_frags, - &RoaringBitmap::new(), - false, - ) - .await?, - ); + let filter = build_old_data_filter( + dataset.as_ref(), + &effective_old_frags, + &RoaringBitmap::new(), + idx.results_are_row_addrs(), + ) + .await?; + old_data_filters.push(filter); let scalar_index = dataset .open_scalar_index_for_maintenance( &field_path, @@ -6847,16 +6880,41 @@ mod tests { // Exercise the stable-row-id allow-list and address-domain deletion // filtering paths. Both must propagate unreadable deletion vectors. - dataset - .create_index( + if index_type == IndexType::Inverted { + // A fresh Inverted index always trains in row-address domain, so + // the row-id-domain allow-list path is simulated by relabeling a + // freshly built segment's `index_version` down -- the same trick + // `results_are_row_addrs` itself relies on to tell the two apart. + let segment = CreateIndexBuilder::new( + &mut dataset, &["cat"], index_type, - None, &ScalarIndexParams::for_builtin(builtin), - true, ) + .execute_uncommitted() .await .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; + let name = legacy_segment.name.clone(); + dataset + .commit_existing_index_segments(&name, "cat", vec![legacy_segment]) + .await + .unwrap(); + } else { + dataset + .create_index( + &["cat"], + index_type, + None, + &ScalarIndexParams::for_builtin(builtin), + true, + ) + .await + .unwrap(); + } // Update rewrites the first 25 rows under the same stable row ids, // leaving a deletion vector on the original fragment. Changes the diff --git a/rust/lance/src/index/create.rs b/rust/lance/src/index/create.rs index 9e6df31a419..90855a61fbd 100644 --- a/rust/lance/src/index/create.rs +++ b/rust/lance/src/index/create.rs @@ -244,11 +244,13 @@ impl<'a> CreateIndexBuilder<'a> { // manifest carries: one this build cannot read still owns its name, and // handing that name out again commits two indices under it. let indices = load_all_indices(self.dataset).await?; - // These always store row ids, so refuse them before training. + // Vector indices always store row ids, so refuse them before training. + // Inverted used to as well, but it now trains in row-address domain + // like every other scalar index type (see + // `INVERTED_ROW_ADDR_DOMAIN_VERSION`), so it is no longer refused + // here. let index_kind = if self.index_type.is_vector() { Some("vector") - } else if self.index_type == IndexType::Inverted || scalar_fts_request { - Some("full-text") } else { None }; diff --git a/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs b/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs index 2bef929b73b..8e830d36b1f 100644 --- a/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs +++ b/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs @@ -256,7 +256,7 @@ mod tests { use lance_index::frag_reuse::FRAG_REUSE_INDEX_NAME; use lance_index::metrics::NoOpMetricsCollector; use lance_index::scalar::btree::BTREE_INDEX_VERSION; - use lance_index::scalar::{BuiltinIndexType, InvertedIndexParams, ScalarIndexParams}; + use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams}; use lance_index::{IndexType, pb, pbold}; use lance_linalg::distance::MetricType; use lance_table::feature_flags::{FLAG_FRAGMENT_REUSE_INDEX, FLAG_STABLE_ROW_IDS}; @@ -358,6 +358,7 @@ mod tests { #[case::rtree(details(&pb::RTreeIndexDetails::default()), 0, false)] #[case::rtree_address_domain(details(&pb::RTreeIndexDetails::default()), 1, true)] #[case::inverted(details(&pbold::InvertedIndexDetails::default()), 0, false)] + #[case::inverted_address_domain(details(&pbold::InvertedIndexDetails::default()), 4, true)] #[case::vector(details(&pb::VectorIndexDetails::default()), 0, false)] #[case::fm(details(&pb::FmIndexDetails::default()), 0, false)] #[case::min_hash(details(&pb::MinHashLshIndexDetails::default()), 0, false)] @@ -755,7 +756,12 @@ mod tests { #[tokio::test] async fn test_publication_rejects_an_incompatible_index(#[case] publication: Publication) { let mut dataset = stable_row_id_dataset("memory://").await; - dataset + // A fresh Inverted index always trains in row-address domain, so a + // row-id-domain one (the incompatible case this test exercises) is + // simulated by relabeling a freshly built segment's `index_version` + // down -- the same trick `results_are_row_addrs` itself relies on to + // tell the two apart. + let segment = dataset .create_index_builder( &["category"], IndexType::Inverted, @@ -763,6 +769,15 @@ mod tests { ) .name("category_idx".to_string()) .train(false) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; + dataset + .commit_existing_index_segments("category_idx", "category", vec![legacy_segment]) .await .unwrap(); let version = dataset.version().version; @@ -828,6 +843,14 @@ mod tests { // NGram also stores row addresses now; it needs a text column, hence the // different column here. #[case::typed_ngram("category", IndexType::NGram, ScalarIndexParams::default(), None)] + // Inverted also always stores row addresses now, so it is no longer + // rejected here either -- see the generic_default_btree case above. + #[case::typed_inverted( + "category", + IndexType::Inverted, + ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), + None + )] // MinHash LSH stores row addresses but does not apply the fragment reuse // index when it is loaded. #[case::typed_minhash_lsh( @@ -866,14 +889,11 @@ mod tests { } } - fn generic_full_text_params() -> ScalarIndexParams { - ScalarIndexParams { - index_type: "inverted".to_string(), - ..Default::default() - } - } - - /// Only the refusal before training names the index kind. + /// Only the refusal before training names the index kind. Vector is the + /// only kind still refused this way: every scalar index type, Inverted + /// included, now trains in row-address domain (see + /// `INVERTED_ROW_ADDR_DOMAIN_VERSION`), so none of them can be known to + /// be incompatible before training runs. #[rstest] #[case::vector( "vec", @@ -881,18 +901,6 @@ mod tests { Box::new(VectorIndexParams::ivf_flat(1, MetricType::L2)), "Cannot create a vector index on column `vec`" )] - #[case::full_text( - "category", - IndexType::Inverted, - Box::new(InvertedIndexParams::default()), - "Cannot create a full-text index on column `category`" - )] - #[case::generic_full_text( - "category", - IndexType::Scalar, - Box::new(generic_full_text_params()), - "Cannot create a full-text index on column `category`" - )] #[tokio::test] async fn test_row_id_index_kinds_are_refused_before_training( #[case] column: &str, @@ -939,7 +947,12 @@ mod tests { let dir = TempStrDir::default(); let uri = format!("{}/source", dir.as_str()); let mut dataset = stable_row_id_dataset(&uri).await; - dataset + // A fresh Inverted index always trains in row-address domain, so a + // row-id-domain one (the incompatible case this test plants) is + // simulated by relabeling a freshly built segment's `index_version` + // down -- the same trick `results_are_row_addrs` itself relies on to + // tell the two apart. + let segment = dataset .create_index_builder( &["category"], IndexType::Inverted, @@ -947,6 +960,15 @@ mod tests { ) .name("category_idx".to_string()) .train(false) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; + dataset + .commit_existing_index_segments("category_idx", "category", vec![legacy_segment]) .await .unwrap(); let mut indices = load_all_indices(&dataset).await.unwrap().as_ref().clone(); @@ -1044,14 +1066,28 @@ mod tests { #[tokio::test] async fn test_incompatible_indices_are_hidden_from_readers() { let mut dataset = stable_row_id_dataset("memory://").await; - create_index( - &mut dataset, - "category", - IndexType::Inverted, - &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), - ) - .await - .unwrap(); + // A fresh Inverted index always trains in row-address domain, so the + // collision this test demonstrates is simulated by relabeling a + // freshly built segment's `index_version` down -- the same trick + // `results_are_row_addrs` itself relies on to tell the two apart. + let segment = dataset + .create_index_builder( + &["category"], + IndexType::Inverted, + &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), + ) + .execute_uncommitted() + .await + .unwrap(); + let legacy_segment = IndexMetadata { + index_version: 0, + ..segment + }; + let name = legacy_segment.name.clone(); + dataset + .commit_existing_index_segments(&name, "category", vec![legacy_segment]) + .await + .unwrap(); create_index( &mut dataset, "vec", @@ -1239,15 +1275,18 @@ mod tests { addresses ); + // Vector is the only kind still refused this way: every scalar index + // type, Inverted included, now trains in row-address domain (see + // `INVERTED_ROW_ADDR_DOMAIN_VERSION`). assert_rejected( create_index( &mut dataset, - "category", - IndexType::Inverted, - &ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted), + "vec", + IndexType::IvfFlat, + &VectorIndexParams::ivf_flat(1, MetricType::L2), ) .await, - "Cannot create a full-text index on column `category`", + "Cannot create a vector index on column `vec`", ); let bitmap = index_with( "category_idx", @@ -1277,6 +1316,11 @@ mod tests { let mut dataset = stable_row_id_dataset(dir.as_str()).await; let mut other = Dataset::open(dir.as_str()).await.unwrap(); let frag_reuse = empty_frag_reuse_index(&dataset, RoaringBitmap::new()).await; + // A fresh Inverted index always trains in row-address domain, so the + // race this test exercises (a row-id-domain index and an FRI racing + // each other) is simulated by relabeling a freshly built segment's + // `index_version` down -- the same trick `results_are_row_addrs` + // itself relies on to tell the two apart. let inverted_index = other .create_index_builder( &["category"], @@ -1288,6 +1332,10 @@ mod tests { .execute_uncommitted() .await .unwrap(); + let inverted_index = IndexMetadata { + index_version: 0, + ..inverted_index + }; let result = if frag_reuse_first { commit_new_indices(&mut dataset, vec![frag_reuse]) diff --git a/rust/lance/src/index/prefilter.rs b/rust/lance/src/index/prefilter.rs index aff488c8134..c860fb17523 100644 --- a/rust/lance/src/index/prefilter.rs +++ b/rust/lance/src/index/prefilter.rs @@ -278,6 +278,32 @@ impl DatasetPreFilter { dataset: Arc, indices: &[IndexMetadata], filter: Option>>>, + ) -> Self { + Self::new_with_filter_future_in_domain(dataset, indices, filter, false) + } + + /// Like [`Self::new_with_filter_future`], but `force_address_domain` lets + /// the caller request a deletion mask keyed by physical row address even + /// on a stable-row-id dataset, instead of the stable-row-id allow-list + /// [`Self::new_with_filter_future`] would otherwise build. + /// + /// Most consumers want the stable-row-id mask: it is what + /// `ScalarIndexExec` et al. translate an address-domain index's own + /// result into before intersecting (see `row_addr_result_to_row_ids`), + /// so the two agree. FTS instead pushes this mask straight into its + /// index's own search as a live [`PreFilter`], consulted per physical + /// posting before any row-id translation happens -- so for an + /// address-domain FTS segment (the only kind a fresh build produces; see + /// `INVERTED_ROW_ADDR_DOMAIN_VERSION`) it needs the mask in that same + /// domain, or a row whose stable id coincidentally collides with another + /// row's physical address (or vice versa) is wrongly admitted or + /// excluded. A legacy row-id-domain segment still wants the stable-row-id + /// mask, which is exactly what its own stored values already are. + pub(crate) fn new_with_filter_future_in_domain( + dataset: Arc, + indices: &[IndexMetadata], + filter: Option>>>, + force_address_domain: bool, ) -> Self { let mut fragments = RoaringBitmap::new(); let all_have_bitmaps = indices.iter().all(|idx| idx.fragment_bitmap.is_some()); @@ -291,9 +317,9 @@ impl DatasetPreFilter { }); } let deleted_ids = if all_have_bitmaps { - Self::create_restricted_deletion_mask(dataset, fragments) + Self::create_deletion_mask_impl(dataset, fragments, true, force_address_domain) } else { - Self::create_deletion_mask(dataset, fragments) + Self::create_deletion_mask_impl(dataset, fragments, false, force_address_domain) } .map(SharedPrerequisite::spawn); let filtered_ids = filter.map(SharedPrerequisite::spawn); @@ -323,8 +349,21 @@ impl DatasetPreFilter { fragments: RoaringBitmap, filter: Option>>>, ) -> Self { - let deleted_ids = Self::create_restricted_deletion_mask(dataset, fragments) - .map(SharedPrerequisite::spawn); + Self::new_restricted_to_fragments_in_domain(dataset, fragments, filter, false) + } + + /// Like [`Self::new_restricted_to_fragments`], with the same + /// `force_address_domain` meaning as + /// [`Self::new_with_filter_future_in_domain`]. + pub(crate) fn new_restricted_to_fragments_in_domain( + dataset: Arc, + fragments: RoaringBitmap, + filter: Option>>>, + force_address_domain: bool, + ) -> Self { + let deleted_ids = + Self::create_deletion_mask_impl(dataset, fragments, true, force_address_domain) + .map(SharedPrerequisite::spawn); let filtered_ids = filter.map(SharedPrerequisite::spawn); Self { deleted_ids, @@ -542,7 +581,7 @@ impl DatasetPreFilter { dataset: Arc, fragments: RoaringBitmap, ) -> Option>>> { - Self::create_deletion_mask_impl(dataset, fragments, false) + Self::create_deletion_mask_impl(dataset, fragments, false, false) } /// Like [`Self::create_deletion_mask`] but also restricts results to the given @@ -551,13 +590,15 @@ impl DatasetPreFilter { dataset: Arc, fragments: RoaringBitmap, ) -> Option>>> { - Self::create_deletion_mask_impl(dataset, fragments, true) + Self::create_deletion_mask_impl(dataset, fragments, true, false) } + /// `force_address_domain`: see [`Self::new_with_filter_future_in_domain`]. fn create_deletion_mask_impl( dataset: Arc, fragments: RoaringBitmap, restrict_to_fragments: bool, + force_address_domain: bool, ) -> Option>>> { let mut missing_frags = Vec::new(); let mut frags_with_deletion_files = Vec::new(); @@ -591,7 +632,7 @@ impl DatasetPreFilter { } if missing_frags.is_empty() && frags_with_deletion_files.is_empty() && !needs_restriction { None - } else if dataset.manifest.uses_stable_row_ids() { + } else if dataset.manifest.uses_stable_row_ids() && !force_address_domain { let restrict_to = if restrict_to_fragments { Some(fragments) } else { @@ -1610,6 +1651,7 @@ mod test { dataset.clone(), covered.clone(), restrict_to_fragments, + false, ) .expect("deletion mask") }; @@ -1653,11 +1695,15 @@ mod test { let mut other_generation = (*dataset).clone(); other_generation.table_state.manifest_location.e_tag = Some("second-generation".to_string()); - let other_generation_mask = - DatasetPreFilter::create_deletion_mask_impl(Arc::new(other_generation), covered, false) - .expect("deletion mask") - .await - .unwrap(); + let other_generation_mask = DatasetPreFilter::create_deletion_mask_impl( + Arc::new(other_generation), + covered, + false, + false, + ) + .expect("deletion mask") + .await + .unwrap(); assert!(!Arc::ptr_eq(&other_generation_mask, &cached[0])); assert!(other_generation_mask.selected(0)); diff --git a/rust/lance/src/index/scalar.rs b/rust/lance/src/index/scalar.rs index 660b8f27e2d..a8ed9b33c24 100644 --- a/rust/lance/src/index/scalar.rs +++ b/rust/lance/src/index/scalar.rs @@ -695,6 +695,18 @@ pub(super) async fn build_scalar_index( // plugin would, so the same relabeling applies to a wrapped BTree, // Bitmap, or LabelList. lance_index::scalar::json::relabel_as_row_id_domain(&mut created_index)?; + } else if params + .index_type + .eq_ignore_ascii_case(BuiltinIndexType::Inverted.as_str()) + || params.index_type.eq_ignore_ascii_case("fts") + { + // Inverted always trains on physical row addresses too, but its + // pre-migration version varies with the chosen posting format + // (and document granularity), unlike the single fixed constant + // `row_id_domain_version` returns for the other types above. + lance_index::scalar::inverted::InvertedIndexPlugin::relabel_as_row_id_domain( + &mut created_index, + )?; } } diff --git a/rust/lance/src/index/scalar/inverted.rs b/rust/lance/src/index/scalar/inverted.rs index 6634ba6cab4..0d1ee01aaff 100644 --- a/rust/lance/src/index/scalar/inverted.rs +++ b/rust/lance/src/index/scalar/inverted.rs @@ -16,7 +16,7 @@ use datafusion::execution::SendableRecordBatchStream; use datafusion::physical_plan::stream::RecordBatchStreamAdapter; use futures::StreamExt; use lance_core::{ - ROW_ID, + ROW_ADDR, ROW_ID, datatypes::{Field, LogicalType, Schema, format_field_path, parse_field_path}, }; use lance_index::pbold::InvertedIndexDetails; @@ -726,10 +726,15 @@ pub(crate) async fn validate_combined_fields_target_column( Ok(()) } -pub(crate) fn fts_document_schema(coordinate_rank: usize) -> Arc { +/// `row_id_col` is `ROW_ADDR` when training/updating an index (the scan +/// behind it always yields physical row addresses now) and `ROW_ID` for the +/// flat/residual query-time path (`FtsDocumentExec`), which must keep +/// emitting genuine row ids. [`transform_fts_document_stream`] detects which +/// one its input actually carries and passes it straight through. +pub(crate) fn fts_document_schema(coordinate_rank: usize, row_id_col: &str) -> Arc { let mut fields = vec![ ArrowField::new(VALUE_COLUMN_NAME, DataType::Utf8, false), - ArrowField::new(ROW_ID, DataType::UInt64, false), + ArrowField::new(row_id_col, DataType::UInt64, false), ]; fields.extend( (0..coordinate_rank) @@ -808,17 +813,30 @@ pub(crate) fn transform_fts_document_stream( resolved: ResolvedFtsField, ) -> Result { let input_schema = input.schema(); - if (input_schema + if input_schema .column_with_name(&resolved.root_column) .is_none() - && input_schema.column_with_name(VALUE_COLUMN_NAME).is_none()) - || input_schema.column_with_name(ROW_ID).is_none() + && input_schema.column_with_name(VALUE_COLUMN_NAME).is_none() { return Err(Error::internal( - "FTS document input must contain the root source column and _rowid".to_string(), + "FTS document input must contain the root source column".to_string(), )); } - let output_schema = fts_document_schema(resolved.coordinate_rank()); + // Index training/update scans always yield row addresses now; the + // flat/residual query-time path (`FtsDocumentExec`) still scans row ids. + // Whichever the input carries, the output keeps the same column so each + // consumer gets the domain it needs without this shared transform having + // to know which one called it. + let row_id_col = if input_schema.column_with_name(ROW_ADDR).is_some() { + ROW_ADDR + } else if input_schema.column_with_name(ROW_ID).is_some() { + ROW_ID + } else { + return Err(Error::internal( + "FTS document input must contain _rowid or _rowaddr".to_string(), + )); + }; + let output_schema = fts_document_schema(resolved.coordinate_rank(), row_id_col); let stream_schema = output_schema.clone(); let stream = input.map(move |batch| { let batch = batch?; @@ -829,7 +847,7 @@ pub(crate) fn transform_fts_document_stream( let mut documents = resolved .documents_from_array(source, batch.num_rows()) .map_err(DataFusionError::from)?; - let input_row_ids = batch[ROW_ID].as_primitive::(); + let input_row_ids = batch[row_id_col].as_primitive::(); // The row-ID validity bitmap can carry the scan's selection vector. if input_row_ids.null_count() > 0 { documents.retain(|document| input_row_ids.is_valid(document.row_index)); @@ -857,13 +875,19 @@ pub(crate) fn transform_fts_document_stream( /// Fill legacy posting-format metadata while leaving protobuf-default row /// document granularity untouched. +/// +/// `index_version` 4 ([`lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION`]) +/// marks row-address-domain segments; it is independent of the posting-list +/// format, which every such segment already carries explicitly in +/// `details.posting_format_version` (see `InvertedIndexPlugin::train_inverted_index`), +/// so the fallback below never needs to synthesize one for it. pub(crate) fn normalize_inverted_details( index: &IndexMetadata, mut details: InvertedIndexDetails, ) -> Result { - if !matches!(index.index_version, 0..=3) { + if !matches!(index.index_version, 0..=4) { return Err(Error::invalid_input(format!( - "FTS index '{}' has unsupported index_version {}; expected 0, 1, 2, or 3", + "FTS index '{}' has unsupported index_version {}; expected 0, 1, 2, 3, or 4", index.name, index.index_version ))); } @@ -871,7 +895,7 @@ pub(crate) fn normalize_inverted_details( let posting_format_version = match index.index_version { 0 | 1 => 1, 2 => 2, - 3 => 3, + 3 | 4 => 3, _ => unreachable!("index version was validated above"), }; details.posting_format_version = Some(posting_format_version); @@ -883,7 +907,8 @@ pub(crate) fn normalize_inverted_details( /// /// `InvertedIndex::merge_segments` is shaped as "merge old segments plus new /// rows", so even a pure segment merge needs a stream with the document column -/// and `_rowid` fields. The stream intentionally contains no batches. +/// and `_rowaddr` fields (training always scans row addresses now). The +/// stream intentionally contains no batches. fn empty_inverted_update_stream( dataset: &Dataset, resolved: &ResolvedFtsField, @@ -898,11 +923,11 @@ fn empty_inverted_update_stream( )) })?; let schema = if resolved.has_lists() { - fts_document_schema(resolved.coordinate_rank()) + fts_document_schema(resolved.coordinate_rank(), ROW_ADDR) } else { Arc::new(ArrowSchema::new(vec![ ArrowField::new(VALUE_COLUMN_NAME, field.data_type(), true), - ArrowField::new(ROW_ID, arrow_schema::DataType::UInt64, false), + ArrowField::new(ROW_ADDR, arrow_schema::DataType::UInt64, false), ])) }; Ok(Box::pin(RecordBatchStreamAdapter::new( @@ -1130,8 +1155,18 @@ pub(crate) async fn merge_segments( // Like the BTree merge, each source keeps only its rows still stored in the // fragments it covers, so a stale posting for a row that moved into another - // source's fragment is not carried into the merged segment. - let (_, old_data_filters) = merge.per_segment_filters(dataset, staged, false).await?; + // source's fragment is not carried into the merged segment. The filters are + // built in whichever domain the sources actually store, rather than assumed + // to be row ids: `shared_segment_domain` resolves the one every segment of + // this named index agrees on and refuses a set that disagrees, the same + // check NGram's merge makes. (`append.rs`'s `legacy_domain_mismatch` already + // forces a rebuild rather than reaching here with a mixed set, so the error + // is a backstop.) + let segment_refs = segments.iter().collect::>(); + let address_domain = super::shared_segment_domain(dataset, "Inverted", &segment_refs)?; + let (_, old_data_filters) = merge + .per_segment_filters(dataset, staged, address_domain) + .await?; let (new_uuid, new_store) = merge.new_store(dataset)?; let created_index = InvertedIndex::merge_segments( @@ -1573,7 +1608,7 @@ mod tests { } #[test] - fn normalize_rejects_unreleased_v4_metadata() { + fn normalize_keeps_v4_row_addr_domain_metadata() { let metadata = IndexMetadata { uuid: Uuid::new_v4(), fields: vec![1], @@ -1590,10 +1625,35 @@ mod tests { metadata: Default::default(), }; let details = InvertedIndexDetails::try_from(&InvertedIndexParams::default()).unwrap(); + let posting_format_version = details.posting_format_version; + + let details = normalize_inverted_details(&metadata, details).unwrap(); + + assert_eq!(details.posting_format_version, posting_format_version); + } + + #[test] + fn normalize_rejects_unsupported_metadata() { + let metadata = IndexMetadata { + uuid: Uuid::new_v4(), + fields: vec![1], + covering_fields: vec![], + name: "tags_idx".to_string(), + dataset_version: 1, + fragment_bitmap: None, + index_details: None, + index_version: 5, + created_at: None, + base_id: None, + files: None, + clustering_id: None, + metadata: Default::default(), + }; + let details = InvertedIndexDetails::try_from(&InvertedIndexParams::default()).unwrap(); let err = normalize_inverted_details(&metadata, details).unwrap_err(); - assert!(err.to_string().contains("unsupported index_version 4")); + assert!(err.to_string().contains("unsupported index_version 5")); } #[test] diff --git a/rust/lance/src/index/tests/lifecycle.rs b/rust/lance/src/index/tests/lifecycle.rs index 0c423f2d5ca..e3b3c3698de 100644 --- a/rust/lance/src/index/tests/lifecycle.rs +++ b/rust/lance/src/index/tests/lifecycle.rs @@ -2898,15 +2898,24 @@ async fn test_a_detached_commit_does_not_erase_an_unsupported_index() { /// Both sides therefore have to count the same indices: planning from the /// filtered view while the commit carries the complete one makes compaction /// fail outright on a dataset holding an index from a newer build. +/// +/// Every scalar index type is now address-domain (Inverted's migration to +/// `INVERTED_ROW_ADDR_DOMAIN_VERSION` was the last one), so none of them can +/// "just follow" a stable-row-id rewrite the way a row-id-domain index once +/// could: an unreadable instance cannot be opened to remap it, and this +/// build cannot tell that from metadata alone (its type still reports +/// `supports_eager_remap`), so the covered group rewrites anyway and the +/// commit drops the index's coverage of it instead of claiming rows it can +/// no longer resolve (see `drop_rewritten_fragments`) -- the scanner falls +/// back to a full scan for those rows rather than compaction being blocked. #[tokio::test] -async fn test_compaction_survives_an_unsupported_index() { +async fn test_compaction_drops_coverage_of_an_unsupported_index_it_rewrites() { let test_dir = tempfile::tempdir().unwrap(); let test_uri = test_dir.path().to_str().unwrap(); - // A text column alongside `two_column_reader`'s numeric ones: the only - // remaining row-id-domain scalar index type (Inverted) requires text; - // the others moved to row-address domain and no longer exercise this - // test. + // A text column alongside `two_column_reader`'s numeric ones: Inverted + // requires text, and every other scalar index type exercises this same + // drop-coverage path too now that all of them are address-domain. fn three_column_reader() -> impl arrow_array::RecordBatchReader + Send + 'static { lance_datagen::gen_batch() .col("id", array::step::()) @@ -2925,10 +2934,6 @@ async fn test_compaction_survives_an_unsupported_index() { .unwrap(); assert_eq!(dataset.get_fragments().len(), 2); - // Row-id-domain: its coverage is recalculated (not dropped) across a - // rewrite under stable row ids, which is exactly the property this test - // checks. The other scalar index types moved to row-address domain and - // no longer exercise it. let inverted_params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); dataset .create_index_builder(&["text"], IndexType::Inverted, &inverted_params) @@ -2956,8 +2961,9 @@ async fn test_compaction_survives_an_unsupported_index() { .await .unwrap(); - // Without a real rewrite the assertions below hold vacuously: an empty - // plan commits nothing and re-reads the manifest it started from. + // Both the covered fragments and the uncovered ones rewrite, in separate + // groups (coverage was never split): compaction is not blocked by the + // unreadable index. assert_eq!(metrics.fragments_removed, 4); assert_eq!(dataset.get_fragments().len(), 2); @@ -2970,8 +2976,9 @@ async fn test_compaction_survives_an_unsupported_index() { .map(|f| f.id() as u32) .collect::(); assert!( - !after.fragment_bitmap.unwrap().is_disjoint(&live), - "the surviving index covers only fragments the rewrite deleted" + after.fragment_bitmap.unwrap().is_disjoint(&live), + "an unreadable address-domain index cannot be remapped eagerly, so its coverage of the \ + rewritten fragments should have been dropped rather than claimed" ); } diff --git a/rust/lance/src/index/tests/statistics.rs b/rust/lance/src/index/tests/statistics.rs index 41226785467..4fcec0b2b09 100644 --- a/rust/lance/src/index/tests/statistics.rs +++ b/rust/lance/src/index/tests/statistics.rs @@ -3387,8 +3387,10 @@ async fn test_index_scan_statistics_unsupported_scalar_version() { ..prototype.clone() }; let supported = segment("future_fts", 0, 3, 3, 123); - let future = segment("future_fts", 1, 4, 4, 456); - let future_decodable = segment("future_decodable", 1, 4, 3, 456); + // 4 is `INVERTED_ROW_ADDR_DOMAIN_VERSION`, which this build supports, so + // a segment from the future has to claim 5. + let future = segment("future_fts", 1, 5, 4, 456); + let future_decodable = segment("future_decodable", 1, 5, 3, 456); let mut malformed = segment("malformed_fts", 1, 3, 3, 456); Arc::make_mut(malformed.index_details.as_mut().unwrap()).value = vec![0xff]; persist_fixture( @@ -3423,7 +3425,7 @@ async fn test_index_scan_statistics_unsupported_scalar_version() { assert!(stats.segments[0].details.is_some()); assert_eq!(stats.segments[0].covered_fragment_live_rows, Some(4)); assert_eq!(stats.segments[1].uuid, future.uuid); - assert_eq!(stats.segments[1].index_version, 4); + assert_eq!(stats.segments[1].index_version, 5); assert_eq!(stats.segments[1].size_bytes, Some(456)); assert!(stats.segments[1].details.is_none()); assert!(stats.segments[1].covered_fragment_ids.is_none()); diff --git a/rust/lance/src/io/exec/fts/boolean.rs b/rust/lance/src/io/exec/fts/boolean.rs index 38588b6a789..73909fd039d 100644 --- a/rust/lance/src/io/exec/fts/boolean.rs +++ b/rust/lance/src/io/exec/fts/boolean.rs @@ -200,7 +200,7 @@ impl ExecutionPlan for BoostQueryExec { .collect::>(); metrics.baseline_metrics.record_output(documents.len()); - let batch = document_key_scores_batch(schema, documents)?; + let batch = document_key_scores_batch(schema, documents, None)?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( @@ -549,7 +549,7 @@ impl ExecutionPlan for BooleanQueryExec { .take(params.limit.unwrap_or(usize::MAX)) .collect::>(); metrics.baseline_metrics.record_output(documents.len()); - let batch = document_key_scores_batch(schema, documents)?; + let batch = document_key_scores_batch(schema, documents, None)?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( diff --git a/rust/lance/src/io/exec/fts/combined_fields.rs b/rust/lance/src/io/exec/fts/combined_fields.rs index 92364d90107..c251a646233 100644 --- a/rust/lance/src/io/exec/fts/combined_fields.rs +++ b/rust/lance/src/io/exec/fts/combined_fields.rs @@ -26,9 +26,10 @@ use crate::index::frag_reuse::resolve_query_segment_coverages; use crate::index::scalar::inverted::{load_segment_details, load_segment_params, load_segments}; use crate::io::exec::PreFilterSource; use crate::io::exec::utils::{ - PreFilterMasks, build_prefilter, build_prefilter_restricted_to_fragments, + PreFilterMasks, build_prefilter_in_domain, build_prefilter_restricted_to_fragments_in_domain, }; use lance_index::prefilter::PreFilter; +use lance_index::scalar::ScalarIndex; use lance_index::scalar::inverted::document_tokenizer::LanceTokenizer; use lance_index::scalar::inverted::query::{ CombinedFieldsQuery, FtsSearchParams, Tokens, try_collect_query_tokens, @@ -42,7 +43,10 @@ use tracing::instrument; use super::corpus::SharedFtsScorer; use super::query_tokens::{TokenizedQuery, fmt_tokenized_query, record_tokenized_query}; -use super::segments::{combined_columns_the_prefilter_may_match, open_fts_segments}; +use super::segments::{ + combined_columns_the_prefilter_may_match, fts_row_addr_to_row_id, + fts_segments_are_address_domain, open_fts_segments, translate_row_ids_and_scores, +}; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; /// Cross-field BM25F full-text search (`combined_fields`). @@ -439,14 +443,31 @@ pub(super) async fn open_combined_fields_scan( } } + // `stale_rows` is built by the scanner in row-id domain (the + // convention every prefilter source and external mask follows), but + // it is checked here against this column's own index directly -- + // `bm25_row_stats_for_terms` compares it to the index's stored + // identifiers, physical addresses for the address-domain index every + // fresh build now produces (see `INVERTED_ROW_ADDR_DOMAIN_VERSION`). + let column_stale_rows = match stale_rows.get(slot).filter(|rows| !rows.is_empty()) { + Some(rows) + if !dataset.manifest.uses_stable_row_ids() + || indices + .first() + .is_some_and(|index| index.results_are_row_addresses()) => + { + Some(Arc::new( + crate::io::exec::utils::translate_treemap_to_row_addr_domain(dataset, rows) + .await?, + )) + } + other => other.cloned(), + }; columns.push(CombinedFieldColumn { column: column.to_string(), weight, indices, - stale_rows: stale_rows - .get(slot) - .filter(|rows| !rows.is_empty()) - .cloned(), + stale_rows: column_stale_rows, }); } metrics.record_parts_searched( @@ -561,7 +582,6 @@ impl ExecutionPlan for CombinedFieldsQueryExec { let metrics = Arc::new(FtsIndexMetrics::new(&self.metrics, partition)); let stream = stream::once(async move { let _timer = metrics.baseline_metrics.elapsed_compute().timer(); - let address_domain = !ds.manifest.uses_stable_row_ids(); let ds_for_scope = ds.clone(); let selected_fragments = if preset_base_scorer.is_some() { @@ -587,6 +607,13 @@ impl ExecutionPlan for CombinedFieldsQueryExec { metrics.as_ref(), ) .await?; + let representative_index = columns + .iter() + .flat_map(|column| column.indices.first()) + .next(); + let row_addr_to_row_id = + fts_row_addr_to_row_id(&ds_for_scope, representative_index).await?; + let address_domain = fts_segments_are_address_domain(&ds_for_scope, &all_segments); if preset_base_scorer.is_some() && covered_fragments @@ -601,24 +628,32 @@ impl ExecutionPlan for CombinedFieldsQueryExec { // rest go to the flat sibling. Otherwise the prefilter spans the union // of the target columns' segments. let mut pre_filter = match covered_fragments { - Some(covered) => build_prefilter_restricted_to_fragments( - context.clone(), - partition, - &prefilter_source, - ds, - covered, - masks, - &exec_metrics, - )?, - None => build_prefilter( - context.clone(), - partition, - &prefilter_source, - ds, - &all_segments, - masks, - &exec_metrics, - )?, + Some(covered) => { + build_prefilter_restricted_to_fragments_in_domain( + context.clone(), + partition, + &prefilter_source, + ds, + covered, + masks, + &exec_metrics, + address_domain, + ) + .await? + } + None => { + build_prefilter_in_domain( + context.clone(), + partition, + &prefilter_source, + ds, + &all_segments, + masks, + &exec_metrics, + address_domain, + ) + .await? + } }; let deleted_fragments = columns.iter().flat_map(|column| &column.indices).fold( roaring::RoaringBitmap::new(), @@ -676,6 +711,8 @@ impl ExecutionPlan for CombinedFieldsQueryExec { metrics.as_ref(), ) .await?; + let (doc_ids, scores) = + translate_row_ids_and_scores(doc_ids, scores, row_addr_to_row_id.as_deref()); metrics.baseline_metrics.record_output(doc_ids.len()); let batch = RecordBatch::try_new( diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index 9fa3aedebc8..6ff48ebb6e1 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -37,7 +37,7 @@ use crate::Dataset; use crate::dataset::mem_wal::index::{QueryLocalFtsIndex, QueryLocalFtsStats}; use crate::index::scalar::inverted::load_segment_details; use crate::io::exec::PreFilterSource; -use crate::io::exec::utils::{PreFilterMasks, build_prefilter}; +use crate::io::exec::utils::{PreFilterMasks, build_prefilter_in_domain}; use lance_index::prefilter::PreFilter; use lance_index::scalar::inverted::builder::ScoredDoc; use lance_index::scalar::inverted::query::{ @@ -63,7 +63,8 @@ use super::query_tokens::{ tokenize_cross_column_compound_query, tokenizer_for_match_query, }; use super::segments::{ - open_fts_segments, search_prepared_segments, segments_the_prefilter_may_match, + fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, + search_prepared_segments, segments_the_prefilter_may_match, translate_row_ids_and_scores, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -753,6 +754,8 @@ impl ExecutionPlan for HybridCompoundQueryExec { let indices = open_fts_segments(&dataset, &column, segments_to_open, &metrics.index_metrics) .await?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, indices.first()).await?; + let address_domain = fts_segments_are_address_domain(&dataset, segments_to_open); let first_index = indices.first().ok_or_else(|| { DataFusionError::Execution(format!( "FTS index for column {column} has no committed segments" @@ -770,7 +773,8 @@ impl ExecutionPlan for HybridCompoundQueryExec { let terms = residual_seed.exact_query_terms(&query)?; if terms.is_empty() { metrics.baseline_metrics.record_output(0); - return scored_documents_batch(schema, Vec::new()).map_err(DataFusionError::from); + return scored_documents_batch(schema, Vec::new(), None) + .map_err(DataFusionError::from); } let allowed_terms = Arc::new(terms.iter().cloned().collect::>()); let query_tokens = Tokens::new(terms.clone(), doc_type); @@ -814,7 +818,7 @@ impl ExecutionPlan for HybridCompoundQueryExec { let stream = input.execute(0, context.clone())?; return collect_bounded_fts_input(stream, limit).await; } - let prefilter = build_prefilter( + let prefilter = build_prefilter_in_domain( context, partition, &PreFilterSource::None, @@ -825,8 +829,10 @@ impl ExecutionPlan for HybridCompoundQueryExec { external_mask: None, }, &metrics_set, - )?; - compound_search_with_base_scorer( + address_domain, + ) + .await?; + let (row_ids, scores) = compound_search_with_base_scorer( &indices, &query, ¶ms, @@ -835,7 +841,12 @@ impl ExecutionPlan for HybridCompoundQueryExec { committed_scorer, ) .await - .map_err(DataFusionError::from) + .map_err(DataFusionError::from)?; + DataFusionResult::Ok(translate_row_ids_and_scores( + row_ids, + scores, + row_addr_to_row_id.as_deref(), + )) }; let residual_query = query.clone(); let residual_search = async move { @@ -869,7 +880,7 @@ impl ExecutionPlan for HybridCompoundQueryExec { }); documents.truncate(limit); metrics.baseline_metrics.record_output(documents.len()); - scored_documents_batch(schema, documents).map_err(DataFusionError::from) + scored_documents_batch(schema, documents, None).map_err(DataFusionError::from) }); Ok(Box::pin(RecordBatchStreamAdapter::new( self.schema(), @@ -1155,15 +1166,17 @@ impl ExecutionPlan for CompoundQueryExec { true }; let _details = load_segment_details(&dataset, column, &segments).await?; - let address_domain = !dataset.manifest.uses_stable_row_ids(); let dataset_for_scope = dataset.clone(); let indices = open_fts_segments(&dataset, column, &segments, &metrics.index_metrics).await?; + let row_addr_to_row_id = + fts_row_addr_to_row_id(&dataset_for_scope, indices.first()).await?; + let address_domain = fts_segments_are_address_domain(&dataset_for_scope, &segments); if let Some(first_index) = indices.first() { let snapshot = tokenize_compound_query(&query, first_index.as_ref())?; tokenized_query.get_or_init(|| snapshot); } - let mut prefilter = build_prefilter( + let mut prefilter = build_prefilter_in_domain( context, partition, &prefilter_source, @@ -1174,7 +1187,9 @@ impl ExecutionPlan for CompoundQueryExec { external_mask, }, &metrics_set, - )?; + address_domain, + ) + .await?; let deleted_fragments = indices .iter() @@ -1465,6 +1480,8 @@ impl ExecutionPlan for CompoundQueryExec { } } }; + let (row_ids, scores) = + translate_row_ids_and_scores(row_ids, scores, row_addr_to_row_id.as_deref()); metrics.baseline_metrics.record_output(row_ids.len()); Ok::<_, DataFusionError>(RecordBatch::try_new( FTS_SCHEMA.clone(), @@ -1780,10 +1797,11 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { .iter() .flat_map(|selection| selection.segments.iter().cloned()) .collect::>(); + let address_domain = fts_segments_are_address_domain(&dataset, &selected_segments); // DatasetPreFilter starts its deletion and filter prerequisites in // the background. Construct it before opening index segments so // both I/O paths can make progress concurrently. - let mut prefilter = build_prefilter( + let mut prefilter = build_prefilter_in_domain( context, partition, &prefilter_source, @@ -1794,7 +1812,9 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { external_mask, }, &metrics_set, - )?; + address_domain, + ) + .await?; let opened_columns = try_join_all(columns.iter().cloned().map(|selection| { let dataset = dataset.clone(); let metrics = metrics.clone(); @@ -1818,6 +1838,14 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { } })) .await?; + let row_addr_to_row_id = fts_row_addr_to_row_id( + &dataset, + opened_columns + .iter() + .flat_map(|(_, indices)| indices.first()) + .next(), + ) + .await?; let mut tokenizer_indices = HashMap::with_capacity(opened_columns.len()); let mut partition_counts = HashMap::with_capacity(opened_columns.len()); @@ -1880,6 +1908,8 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { metrics.clone(), ) .await?; + let (row_ids, scores) = + translate_row_ids_and_scores(row_ids, scores, row_addr_to_row_id.as_deref()); metrics.baseline_metrics.record_output(row_ids.len()); Ok::<_, DataFusionError>(RecordBatch::try_new( FTS_SCHEMA.clone(), diff --git a/rust/lance/src/io/exec/fts/document.rs b/rust/lance/src/io/exec/fts/document.rs index 1123ca0bc91..bdd332cfbfa 100644 --- a/rust/lance/src/io/exec/fts/document.rs +++ b/rust/lance/src/io/exec/fts/document.rs @@ -108,7 +108,10 @@ impl FtsDocumentExec { } pub(crate) fn new(input: Arc, resolved: ResolvedFtsField) -> Self { - let schema = fts_document_schema(resolved.coordinate_rank()); + // This node is only used on the flat/residual query-time path + // (`dataset::scanner::fts`), which always scans and must keep + // emitting genuine row ids -- never row addresses. + let schema = fts_document_schema(resolved.coordinate_rank(), ROW_ID); let properties = Arc::new(PlanProperties::new( EquivalenceProperties::new(schema), input.output_partitioning().clone(), diff --git a/rust/lance/src/io/exec/fts/match_query.rs b/rust/lance/src/io/exec/fts/match_query.rs index 9dbc1a76f7f..ad55ee73eef 100644 --- a/rust/lance/src/io/exec/fts/match_query.rs +++ b/rust/lance/src/io/exec/fts/match_query.rs @@ -22,7 +22,7 @@ use lance_table::format::IndexMetadata; use crate::Dataset; use crate::io::exec::PreFilterSource; -use crate::io::exec::utils::{PreFilterMasks, build_prefilter}; +use crate::io::exec::utils::{PreFilterMasks, build_prefilter_in_domain}; use lance_index::prefilter::PreFilter; use lance_index::scalar::inverted::query::{ FtsSearchParams, MatchQuery, try_collect_query_tokens, uses_fuzzy_expansion, @@ -39,7 +39,8 @@ use super::query_tokens::{ TokenizedQuery, fmt_tokenized_query, record_tokenized_query, tokenizer_for_match_query, }; use super::segments::{ - open_fts_segments, search_prepared_segments, segments_the_prefilter_may_match, + fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, + search_prepared_segments, segments_the_prefilter_may_match, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -668,12 +669,12 @@ impl ExecutionPlan for MatchQueryExec { } else { true }; - let address_domain = !ds.manifest.uses_stable_row_ids(); + let address_domain = fts_segments_are_address_domain(&ds, &segments); let ds_for_scope = ds.clone(); let indices = open_fts_segments(&ds, &column, &segments, &metrics.index_metrics).await?; - let mut pre_filter = build_prefilter( + let mut pre_filter = build_prefilter_in_domain( context.clone(), partition, &prefilter_source, @@ -684,7 +685,9 @@ impl ExecutionPlan for MatchQueryExec { external_mask, }, &metrics_set, - )?; + address_domain, + ) + .await?; let deleted_fragments = indices .iter() @@ -765,6 +768,7 @@ impl ExecutionPlan for MatchQueryExec { &metrics, ) .await; + let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, indices.first()).await?; let mut documents = search_prepared_segments( &indices, prepared, @@ -779,7 +783,7 @@ impl ExecutionPlan for MatchQueryExec { }); metrics.baseline_metrics.record_output(documents.len()); - let batch = scored_documents_batch(schema, documents)?; + let batch = scored_documents_batch(schema, documents, row_addr_to_row_id.as_deref())?; Ok::<_, DataFusionError>(batch) }); diff --git a/rust/lance/src/io/exec/fts/matches.rs b/rust/lance/src/io/exec/fts/matches.rs index b36fc9c3da1..98ad2e60ba3 100644 --- a/rust/lance/src/io/exec/fts/matches.rs +++ b/rust/lance/src/io/exec/fts/matches.rs @@ -19,6 +19,7 @@ use lance_index::scalar::inverted::{ DOC_INDEX_COL, InvertedIndex, MemBM25Scorer, PreparedBm25Query, SCORE_COL, prepare_bm25_query, }; +use super::segments::RowAddrToRowId; use super::selection::FtsIndexMetrics; #[derive(Clone)] @@ -50,8 +51,18 @@ impl PreparedMatch { pub(super) fn scored_documents_batch( schema: SchemaRef, - documents: Vec, + mut documents: Vec, + row_addr_to_row_id: Option<&RowAddrToRowId>, ) -> Result { + if let Some(translate) = row_addr_to_row_id { + documents.retain_mut(|document| match translate(document.row_id) { + Some(row_id) => { + document.row_id = row_id; + true + } + None => false, + }); + } let row_ids = UInt64Array::from_iter_values(documents.iter().map(|document| document.row_id)); let scores = Float32Array::from_iter_values(documents.iter().map(|document| document.score.0)); let mut columns = vec![Arc::new(row_ids) as Arc]; @@ -151,6 +162,7 @@ pub(super) fn batch_scored_document_keys_sum_scores( pub(super) fn document_key_scores_batch( schema: SchemaRef, values: impl IntoIterator, + row_addr_to_row_id: Option<&RowAddrToRowId>, ) -> Result { scored_documents_batch( schema, @@ -158,6 +170,7 @@ pub(super) fn document_key_scores_batch( .into_iter() .map(|(key, score)| ScoredDoc::with_doc_index(key.row_id, key.doc_index, score)) .collect(), + row_addr_to_row_id, ) } diff --git a/rust/lance/src/io/exec/fts/phrase.rs b/rust/lance/src/io/exec/fts/phrase.rs index b573db9d8e7..76a7d681914 100644 --- a/rust/lance/src/io/exec/fts/phrase.rs +++ b/rust/lance/src/io/exec/fts/phrase.rs @@ -22,7 +22,7 @@ use lance_table::format::IndexMetadata; use crate::Dataset; use crate::io::exec::PreFilterSource; -use crate::io::exec::utils::{PreFilterMasks, build_prefilter}; +use crate::io::exec::utils::{PreFilterMasks, build_prefilter_in_domain}; use lance_index::prefilter::PreFilter; use lance_index::scalar::inverted::query::{ FtsSearchParams, PhraseQuery, try_collect_query_tokens, @@ -36,7 +36,10 @@ use uuid::Uuid; use super::corpus::SharedFtsScorer; use super::matches::scored_documents_batch; use super::query_tokens::{TokenizedQuery, fmt_tokenized_query, record_tokenized_query}; -use super::segments::{open_fts_segments, search_segments, segments_the_prefilter_may_match}; +use super::segments::{ + fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, search_segments, + segments_the_prefilter_may_match, +}; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; /// Indexed phrase search with an explicit document boundary and candidate scope. @@ -531,12 +534,12 @@ impl ExecutionPlan for PhraseQueryExec { &metrics.segment_bind_duration, ) .await?; - let address_domain = !ds.manifest.uses_stable_row_ids(); + let address_domain = fts_segments_are_address_domain(&ds, &segments); let ds_for_scope = ds.clone(); let indices = open_fts_segments(&ds, &column, &segments, &metrics.index_metrics).await?; - let mut pre_filter = build_prefilter( + let mut pre_filter = build_prefilter_in_domain( context.clone(), partition, &prefilter_source, @@ -547,7 +550,9 @@ impl ExecutionPlan for PhraseQueryExec { external_mask, }, &metrics_set, - )?; + address_domain, + ) + .await?; let deleted_fragments = indices .iter() @@ -602,6 +607,7 @@ impl ExecutionPlan for PhraseQueryExec { .await; let tokens = Arc::new(tokens); let params = Arc::new(params); + let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, indices.first()).await?; let documents = search_segments( &indices, tokens, @@ -614,7 +620,7 @@ impl ExecutionPlan for PhraseQueryExec { ) .await?; metrics.baseline_metrics.record_output(documents.len()); - let batch = scored_documents_batch(schema, documents)?; + let batch = scored_documents_batch(schema, documents, row_addr_to_row_id.as_deref())?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index d812d72e978..52f9a04014d 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -15,6 +15,7 @@ use lance_core::utils::tokio::get_num_compute_intensive_cpus; use lance_core::{Error, Result}; use lance_index::metrics::MetricsCollector; use lance_index::prefilter::PreFilter; +use lance_index::scalar::ScalarIndex; use lance_index::scalar::inverted::builder::ScoredDoc; use lance_index::scalar::inverted::query::{FtsSearchParams, Operator, Tokens}; use lance_index::scalar::inverted::{CombinedFieldColumn, InvertedIndex, MemBM25Scorer}; @@ -23,10 +24,42 @@ use lance_table::format::IndexMetadata; use super::matches::PreparedMatch; use super::selection::FtsIndexMetrics; use crate::Dataset; +use crate::dataset::rowids::live_row_addr_to_row_id_lookup; use crate::index::loading::DatasetIndexInternalExt; use crate::index::prefilter::prefilter_may_match_segment; use crate::index::segment_coverage::{SegmentCoverage, SegmentRowDomain}; +/// The translation from a stored physical row address to its row id. +pub(super) type RowAddrToRowId = dyn Fn(u64) -> Option + Send + Sync; + +/// Whether `segments`' own stored identifiers are physical row addresses, for +/// code that must pick between an address-domain and a row-id-domain +/// representation of the same restriction (a `PreFilter` mask, a prefilter's +/// per-segment coverage check -- see `fts_row_addr_to_row_id`'s doc for why +/// FTS cannot just translate its result afterward the way `ScalarIndexExec` +/// does). +/// +/// True whenever the two domains coincide regardless of what a segment's own +/// `results_are_row_addrs()` reports: without stable row ids a row id and a +/// row address are the same value, and `build_scalar_index` relabels a fresh +/// build's segment to a pre-`INVERTED_ROW_ADDR_DOMAIN_VERSION` version in +/// that case specifically so an old reader still understands it -- not +/// because its stored values differ in kind. With stable row ids the two +/// domains genuinely can differ, and then this defers to the first segment's +/// own `results_are_row_addrs()` (uniform across a committed named index; see +/// `append.rs`'s `legacy_domain_mismatch`), true unless it is a legacy +/// segment predating that version. +pub(super) fn fts_segments_are_address_domain( + dataset: &Dataset, + segments: &[IndexMetadata], +) -> bool { + !dataset.manifest.uses_stable_row_ids() + || segments + .first() + .map(|segment| segment.results_are_row_addrs()) + .unwrap_or(true) +} + /// Open one FTS segment as an [`InvertedIndex`]. /// /// With `coverage` the segment may only report live rows currently stored in the fragments @@ -60,10 +93,11 @@ pub(super) async fn open_fts_segment( } }; let (inverted, allowed_rows) = futures::try_join!(open, allowed_rows)?; - Ok(Arc::new(match allowed_rows { + let result = Arc::new(match allowed_rows { Some(allowed_rows) => inverted.with_allowed_rows(allowed_rows), None => inverted, - })) + }); + Ok(result) } /// Open all committed FTS segments for a column. @@ -82,8 +116,17 @@ pub(super) async fn open_fts_segments( metrics: &dyn MetricsCollector, ) -> Result>> { let segment_refs = segments.iter().collect::>(); - let coverage = - SegmentCoverage::resolve(dataset, &segment_refs, SegmentRowDomain::RowId).await?; + // A segment persisted before `INVERTED_ROW_ADDR_DOMAIN_VERSION` stores row + // ids, which can remain live in a sibling segment after a stable-row-id + // row moves; a segment built since stores row addresses, which do not + // (see `SegmentRowDomain`). `results_are_row_addrs` is uniform across a + // named index's segments (`append.rs` rebuilds rather than mixes them), + // so the first segment's domain speaks for all of them. + let row_domain = match segments.first() { + Some(first) if first.results_are_row_addrs() => SegmentRowDomain::RowAddress, + _ => SegmentRowDomain::RowId, + }; + let coverage = SegmentCoverage::resolve(dataset, &segment_refs, row_domain).await?; try_join_all(segments.iter().enumerate().map(|(index, segment)| { let coverage = coverage.as_ref().map(|coverage| (coverage, index)); open_fts_segment(dataset, column, segment, coverage, metrics) @@ -91,6 +134,60 @@ pub(super) async fn open_fts_segments( .await } +/// Build the row-address-to-row-id translation this query's final output +/// needs, from `representative`'s domain -- every segment of a committed +/// named index shares one domain (`append.rs`'s `legacy_domain_mismatch` +/// forces a rebuild rather than letting them disagree). +/// +/// `None` (a no-op) when the two coincide: no stable row ids, or a +/// row-id-domain segment. The latter is a transient state right after a +/// dataset turns stable row ids on, before its existing segments are next +/// rebuilt or merged -- that does not happen eagerly, so a query can still +/// land here with a row-id-domain segment under stable row ids, and the +/// segment's own values are already row ids needing no translation. +/// +/// Unlike MinHash's per-segment lookup (`live_row_addr_to_row_id_lookup` +/// scoped to one segment's own fragments), FTS merges per-segment top-k hits +/// into one global ranking before this can run, so it must already cover +/// every fragment any segment of the index could answer from; this uses the +/// dataset's whole current fragment set rather than tracking each query's +/// narrower per-segment union. +pub(super) async fn fts_row_addr_to_row_id( + dataset: &Dataset, + representative: Option<&Arc>, +) -> Result>> { + if !dataset.manifest.uses_stable_row_ids() + || !representative.is_some_and(|index| index.results_are_row_addresses()) + { + return Ok(None); + } + let fragment_ids = dataset + .manifest + .fragments + .iter() + .map(|fragment| fragment.id as u32) + .collect::>(); + let lookup = live_row_addr_to_row_id_lookup(dataset, fragment_ids).await?; + Ok(Some(Arc::new(lookup))) +} + +/// Translate and drop unresolvable rows from a final `(row_ids, scores)` +/// result pair, keeping the two aligned. A `None` translator is a no-op. +pub(super) fn translate_row_ids_and_scores( + row_ids: Vec, + scores: Vec, + row_addr_to_row_id: Option<&RowAddrToRowId>, +) -> (Vec, Vec) { + let Some(translate) = row_addr_to_row_id else { + return (row_ids, scores); + }; + row_ids + .into_iter() + .zip(scores) + .filter_map(|(row_id, score)| translate(row_id).map(|row_id| (row_id, score))) + .unzip() +} + /// Open all committed FTS segments without resolving live-row coverage. /// /// Global statistics describe the committed corpus rather than the rows currently stored diff --git a/rust/lance/src/io/exec/utils.rs b/rust/lance/src/io/exec/utils.rs index 9dcff3c9535..376d999ee76 100644 --- a/rust/lance/src/io/exec/utils.rs +++ b/rust/lance/src/io/exec/utils.rs @@ -52,6 +52,7 @@ use tracing::Instrument; use super::row_addr_mask::MaskAndLoader; use super::scalar_index::{ScalarIndexExec, prefilter_upper_to_row_ids}; use crate::Dataset; +use crate::dataset::rowids::row_ids_to_row_addrs; use crate::index::prefilter::DatasetPreFilter; /// Open fragments on cancellation-safe tasks while preserving the stream's @@ -513,6 +514,134 @@ pub(crate) fn build_prefilter( Ok(Arc::new(prefilter)) } +/// Translates one treemap's entries from row-id domain to row-address +/// domain. A "whole fragment" entry can't be enumerated one id at a time; it +/// is vanishingly unlikely to appear in a row-id-domain mask (it would +/// require 2^32 contiguous ids), so it is left untranslated rather than +/// failing the query. +pub(crate) async fn translate_treemap_to_row_addr_domain( + dataset: &Dataset, + treemap: &RowAddrTreeMap, +) -> Result { + let Some(row_ids) = treemap.row_addrs() else { + return Ok(treemap.clone()); + }; + let row_ids: Vec = row_ids.map(u64::from).collect(); + let addrs = row_ids_to_row_addrs(dataset, &row_ids).await?; + Ok(addrs.into_iter().flatten().collect()) +} + +/// Translates a row-id-domain mask into row-address domain. Every prefilter +/// mask reaching a `PreFilter` is expressed in row-id domain by convention: an +/// external mask is built that way, and a scalar-index source is finalized to +/// it by [`SelectionVectorToPrefilter`] (vector and PQ indices are keyed by +/// stable row id). The deletion mask FTS ANDs it against, however, is forced +/// to physical addresses by `build_prefilter_in_domain`/ +/// `build_prefilter_restricted_to_fragments_in_domain`. Combining the two +/// without this translation compares unrelated numeric domains wherever a +/// row's address differs from its id (e.g. any fragment beyond the first, +/// under stable row ids). +/// +/// FTS therefore pays a round trip (address -> id in +/// [`SelectionVectorToPrefilter`], id -> address here) for a scalar-index +/// prefilter source. Teaching that conversion to stop at the domain its +/// consumer wants is a follow-up, not a correctness concern. +async fn row_id_mask_to_row_addr_domain( + dataset: &Dataset, + mask: Arc, +) -> Result> { + let translated = match mask.as_ref() { + RowAddrMask::AllowList(allow) => { + RowAddrMask::AllowList(translate_treemap_to_row_addr_domain(dataset, allow).await?) + } + RowAddrMask::BlockList(block) => { + RowAddrMask::BlockList(translate_treemap_to_row_addr_domain(dataset, block).await?) + } + }; + Ok(Arc::new(translated)) +} + +/// Wraps `filter` to translate its resolved mask into row-address domain +/// (see [`row_id_mask_to_row_addr_domain`]) whenever `address_domain` is set. +fn translate_filter_in_domain( + filter: Option>>>, + ds: Arc, + address_domain: bool, +) -> Option>>> { + if !address_domain { + return filter; + } + filter.map(|filter| { + async move { + let mask = filter.await?; + row_id_mask_to_row_addr_domain(&ds, mask).await + } + .boxed() + }) +} + +/// Translates `overlay_block` into row-address domain (see +/// [`row_id_mask_to_row_addr_domain`]) whenever `address_domain` is set. The +/// overlay block follows the same row-id-domain convention as any prefilter +/// source and external mask, so it needs the same translation those get via +/// `translate_filter_in_domain` before it is combined (logical AND) into an +/// address-domain-forced deletion mask. +async fn translate_overlay_block_in_domain( + overlay_block: Option, + ds: &Dataset, + address_domain: bool, +) -> Result> { + let Some(overlay_block) = overlay_block else { + return Ok(None); + }; + if !address_domain { + return Ok(Some(overlay_block)); + } + let translated = row_id_mask_to_row_addr_domain(ds, Arc::new(overlay_block)).await?; + Ok(Some(translated.as_ref().clone())) +} + +/// Like [`build_prefilter`], but the deletion mask is kept in physical row +/// address domain even on a stable-row-id dataset -- see +/// [`DatasetPreFilter::new_with_filter_future_in_domain`]. FTS needs this: it +/// consults the prefilter mask directly against its own stored addresses +/// while scoring, before any row-id translation happens, so the mask must +/// already be in that same domain whenever the segments it is built for are +/// address-domain (an address-domain segment is the only kind a fresh build +/// now produces; see `INVERTED_ROW_ADDR_DOMAIN_VERSION`). The externally +/// supplied `filter` (any prefilter source and external mask, row-id domain +/// by convention) is translated into the same address domain so ANDing it +/// into the deletion mask compares like with like, and so is `overlay_block`. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn build_prefilter_in_domain( + context: Arc, + partition: usize, + prefilter_source: &PreFilterSource, + ds: Arc, + index_meta: &[IndexMetadata], + masks: PreFilterMasks, + metrics: &ExecutionPlanMetricsSet, + address_domain: bool, +) -> Result> { + let filter = prefilter_mask_future( + context, + partition, + prefilter_source, + masks.external_mask, + metrics, + ds.clone(), + )?; + let filter = translate_filter_in_domain(filter, ds.clone(), address_domain); + let overlay_block = + translate_overlay_block_in_domain(masks.overlay_block, &ds, address_domain).await?; + let mut prefilter = + DatasetPreFilter::new_with_filter_future_in_domain(ds, index_meta, filter, address_domain); + if let Some(overlay_block) = overlay_block { + prefilter = prefilter.with_overlay_block(overlay_block); + } + Ok(Arc::new(prefilter)) +} + /// Build a prefilter restricted to `fragments` rather than to the union of /// `index_meta`'s fragment bitmaps. See /// [`DatasetPreFilter::new_restricted_to_fragments`]. @@ -540,6 +669,42 @@ pub(crate) fn build_prefilter_restricted_to_fragments( Ok(Arc::new(prefilter)) } +/// Like [`build_prefilter_restricted_to_fragments`], with the same +/// `address_domain` meaning as [`build_prefilter_in_domain`]. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn build_prefilter_restricted_to_fragments_in_domain( + context: Arc, + partition: usize, + prefilter_source: &PreFilterSource, + ds: Arc, + fragments: RoaringBitmap, + masks: PreFilterMasks, + metrics: &ExecutionPlanMetricsSet, + address_domain: bool, +) -> Result> { + let filter = prefilter_mask_future( + context, + partition, + prefilter_source, + masks.external_mask, + metrics, + ds.clone(), + )?; + let filter = translate_filter_in_domain(filter, ds.clone(), address_domain); + let overlay_block = + translate_overlay_block_in_domain(masks.overlay_block, &ds, address_domain).await?; + let mut prefilter = DatasetPreFilter::new_restricted_to_fragments_in_domain( + ds, + fragments, + filter, + address_domain, + ); + if let Some(overlay_block) = overlay_block { + prefilter = prefilter.with_overlay_block(overlay_block); + } + Ok(Arc::new(prefilter)) +} + struct RowIdPrefilterMetrics { loads: Count, input_rows: Count, From 2f38c36e9c358eaca7a357884c5c289d8a20e2a3 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 15:10:18 -0800 Subject: [PATCH 02/15] fix(fts): reject index segments that disagree on the identity domain A multi-column FTS query (`combined_fields`, a cross-column compound) merges several *named indexes*' postings on the stored identifier alone. Since Inverted moved to the row-address domain, that identifier only means the same thing in every column if every column's index was built since the migration. Rebuilding one column's index after an upgrade leaves its sibling on the older domain, and then one column's row id `2` and the other's row address `1 << 32` for the same row score as two unrelated documents: an AND query silently returns nothing. `fts_segments_are_address_domain` took the first segment's domain as the whole query's, so nothing noticed. It now resolves the one domain every segment agrees on and errors naming both offenders otherwise. The callers already pass every segment the query reads -- `all_segments` and `selected_segments` span all target columns -- so the same check covers the cross-column case and the within-index one. `open_fts_segments` applies it too, the chokepoint every indexed FTS path funnels through. `fts_row_addr_to_row_id` now takes that resolved domain instead of re-deriving one from a representative index, so the domain the results are translated out of cannot drift from the one the postings and masks were read in. Within one named index this mix is already refused at write time (`manifest_build`'s per-name check, and `optimize_indices`' `legacy_domain_mismatch`); the read-side check covers a manifest written by another implementation. Across named indexes nothing refuses it at write time and nothing could -- rebuilding one column is a legitimate commit on its own, and only a query spanning both makes the pair wrong -- so rejecting it at read time is the only place it can be caught. No check runs without stable row ids, where a row id and a row address are the same number and `build_scalar_index` deliberately relabels fresh builds down to a legacy version. Co-Authored-By: Claude Opus 5 --- .../tests/dataset_fts_combined_fields.rs | 175 ++++++++++++++++ rust/lance/src/io/exec/fts/combined_fields.rs | 12 +- rust/lance/src/io/exec/fts/compound.rs | 21 +- rust/lance/src/io/exec/fts/match_query.rs | 4 +- rust/lance/src/io/exec/fts/phrase.rs | 4 +- rust/lance/src/io/exec/fts/segments.rs | 191 ++++++++++++++++-- 6 files changed, 361 insertions(+), 46 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index 7c2c39ceabd..aac0f104519 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -2746,3 +2746,178 @@ async fn test_fts_combined_fields_nested_columns() { ); } } + +/// Rebuild `index_name`'s single committed segment the way a pre- +/// `INVERTED_ROW_ADDR_DOMAIN_VERSION` writer would have written it: its stored +/// identities are remapped from row addresses back to row ids, and its +/// `index_version` is relabeled down to match. `addr_to_row_id` supplies that +/// remapping for every row whose address differs from its id. +/// +/// Unlike the relabel-only pattern the migration guard tests use, the returned +/// segment's contents really are row-id domain, so a query reading it is +/// reading the same bytes an index written before the migration holds. +async fn legacy_row_id_segment( + ds: &Dataset, + index_name: &str, + column: &str, + addr_to_row_id: HashMap>, +) -> lance_table::format::IndexMetadata { + use crate::dataset::index::LanceIndexStoreExt; + use crate::index::DatasetIndexInternalExt; + use lance_core::utils::row_addr_remap::RowAddrRemap; + use lance_index::metrics::NoOpMetricsCollector; + use lance_index::scalar::index_files_to_table; + use lance_index::scalar::lance_format::LanceIndexStore; + + let meta = ds.load_index_by_name(index_name).await.unwrap().unwrap(); + let index = ds + .open_scalar_index(column, &meta.uuid, &NoOpMetricsCollector) + .await + .unwrap(); + let uuid = uuid::Uuid::new_v4(); + let store = LanceIndexStore::from_dataset_for_new(ds, &uuid).unwrap(); + let created = index + .remap(&RowAddrRemap::direct(addr_to_row_id), &store) + .await + .unwrap(); + lance_table::format::IndexMetadata { + uuid, + index_version: 3, + index_details: Some(Arc::new(created.index_details)), + files: Some(index_files_to_table(created.files)), + ..meta + } +} + +/// Two fragments of two rows each under stable row ids, both text columns +/// indexed. Row id 2 lives at the head of fragment 1, so its row address +/// (`1 << 32`) differs from its row id -- the gap the identity domain has to +/// agree about. +async fn two_fragment_domain_fixture(dir: &TempStrDir) -> Dataset { + let mut ds = write_fts_dataset( + dir, + combined_fields_batch( + vec![0, 1, 2, 3], + vec!["other", "other", "alpha", "other"], + vec!["other", "other", "beta", "other"], + ), + Some(WriteParams { + enable_stable_row_ids: true, + max_rows_per_file: 2, + ..Default::default() + }), + ) + .await; + create_inverted_indices(&mut ds, &["title", "body"], &combined_fields_test_params()).await; + ds +} + +/// The second fragment's address -> row id remapping for the fixture above. +fn second_fragment_addr_to_row_id() -> HashMap> { + HashMap::from([(1u64 << 32, Some(2)), ((1u64 << 32) | 1, Some(3))]) +} + +async fn fts_query_error(ds: &Dataset, query: FtsQuery) -> String { + let result = ds + .scan() + .project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query(query)) + .unwrap() + .limit(Some(10), None) + .unwrap() + .try_into_batch() + .await; + match result { + Ok(batch) => panic!( + "expected a mixed-domain query to be rejected, got {} rows", + batch.num_rows() + ), + Err(err) => err.to_string(), + } +} + +/// Rebuilding one column's FTS index after the row-address migration leaves +/// its sibling column on the older domain. A multi-column query merges the two +/// columns' postings on the stored identifier alone, so row id `2` from one +/// index and row address `1 << 32` from the other would score as two unrelated +/// documents and an AND query would silently return nothing. Both query shapes +/// that span columns have to reject the mix instead. +#[rstest] +#[case::combined_fields(false)] +#[case::cross_column_compound(true)] +#[tokio::test] +async fn test_fts_mixed_domain_across_columns_is_rejected(#[case] compound: bool) { + let dir = TempStrDir::default(); + let mut ds = two_fragment_domain_fixture(&dir).await; + let legacy = + legacy_row_id_segment(&ds, "title_idx", "title", second_fragment_addr_to_row_id()).await; + ds.commit_existing_index_segments("title_idx", "title", vec![legacy]) + .await + .unwrap(); + + let query = if compound { + use lance_index::scalar::inverted::query::{BooleanQuery, Occur}; + BooleanQuery::new([ + ( + Occur::Must, + MatchQuery::new("alpha".into()) + .with_column(Some("title".into())) + .into(), + ), + ( + Occur::Must, + MatchQuery::new("beta".into()) + .with_column(Some("body".into())) + .into(), + ), + ]) + .into() + } else { + combined_query("alpha beta", Operator::And) + }; + + let err = fts_query_error(&ds, query).await; + assert!( + err.contains("disagree on the identity domain"), + "unexpected error: {err}" + ); + assert!( + err.contains("title_idx") && err.contains("body_idx"), + "error should name both disagreeing indexes: {err}" + ); +} + +/// `optimize_indices` refuses to merge segments whose domains disagree. This +/// pins the other half: publishing one named index that holds both is refused +/// at commit time too, so a mixed *within-index* set is not a state Lance's +/// own writer can leave behind for a reader to puzzle over. +#[tokio::test] +async fn test_fts_mixed_domain_within_one_index_is_rejected_at_commit() { + let dir = TempStrDir::default(); + let ds = two_fragment_domain_fixture(&dir).await; + let current = ds.load_index_by_name("title_idx").await.unwrap().unwrap(); + let legacy = + legacy_row_id_segment(&ds, "title_idx", "title", second_fragment_addr_to_row_id()).await; + + // Segments in one index must cover disjoint fragments, so split the + // fixture's two fragments between the address-domain original and the + // row-id-domain copy. + let address_segment = lance_table::format::IndexMetadata { + fragment_bitmap: Some(roaring::RoaringBitmap::from_iter([0u32])), + ..current + }; + let row_id_segment = lance_table::format::IndexMetadata { + fragment_bitmap: Some(roaring::RoaringBitmap::from_iter([1u32])), + ..legacy + }; + let mut ds = ds; + let error = ds + .commit_existing_index_segments("title_idx", "title", vec![address_segment, row_id_segment]) + .await + .expect_err("a mixed-domain index should not be committable"); + assert!( + error.to_string().contains("mixes row-ID and row-address"), + "unexpected error: {error}" + ); +} diff --git a/rust/lance/src/io/exec/fts/combined_fields.rs b/rust/lance/src/io/exec/fts/combined_fields.rs index c251a646233..d074a851b75 100644 --- a/rust/lance/src/io/exec/fts/combined_fields.rs +++ b/rust/lance/src/io/exec/fts/combined_fields.rs @@ -607,13 +607,11 @@ impl ExecutionPlan for CombinedFieldsQueryExec { metrics.as_ref(), ) .await?; - let representative_index = columns - .iter() - .flat_map(|column| column.indices.first()) - .next(); - let row_addr_to_row_id = - fts_row_addr_to_row_id(&ds_for_scope, representative_index).await?; - let address_domain = fts_segments_are_address_domain(&ds_for_scope, &all_segments); + // `all_segments` spans every target column, so this is also what + // rejects two columns' indexes that disagree on the domain: their + // postings are merged on the stored identifier alone. + let address_domain = fts_segments_are_address_domain(&ds_for_scope, &all_segments)?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, address_domain).await?; if preset_base_scorer.is_some() && covered_fragments diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index 6ff48ebb6e1..1c6373b54eb 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -754,8 +754,8 @@ impl ExecutionPlan for HybridCompoundQueryExec { let indices = open_fts_segments(&dataset, &column, segments_to_open, &metrics.index_metrics) .await?; - let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, indices.first()).await?; - let address_domain = fts_segments_are_address_domain(&dataset, segments_to_open); + let address_domain = fts_segments_are_address_domain(&dataset, segments_to_open)?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, address_domain).await?; let first_index = indices.first().ok_or_else(|| { DataFusionError::Execution(format!( "FTS index for column {column} has no committed segments" @@ -1169,9 +1169,9 @@ impl ExecutionPlan for CompoundQueryExec { let dataset_for_scope = dataset.clone(); let indices = open_fts_segments(&dataset, column, &segments, &metrics.index_metrics).await?; + let address_domain = fts_segments_are_address_domain(&dataset_for_scope, &segments)?; let row_addr_to_row_id = - fts_row_addr_to_row_id(&dataset_for_scope, indices.first()).await?; - let address_domain = fts_segments_are_address_domain(&dataset_for_scope, &segments); + fts_row_addr_to_row_id(&dataset_for_scope, address_domain).await?; if let Some(first_index) = indices.first() { let snapshot = tokenize_compound_query(&query, first_index.as_ref())?; tokenized_query.get_or_init(|| snapshot); @@ -1797,7 +1797,9 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { .iter() .flat_map(|selection| selection.segments.iter().cloned()) .collect::>(); - let address_domain = fts_segments_are_address_domain(&dataset, &selected_segments); + // `selected_segments` spans every target column of a cross-column + // query, so this also rejects columns whose indexes disagree. + let address_domain = fts_segments_are_address_domain(&dataset, &selected_segments)?; // DatasetPreFilter starts its deletion and filter prerequisites in // the background. Construct it before opening index segments so // both I/O paths can make progress concurrently. @@ -1838,14 +1840,7 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { } })) .await?; - let row_addr_to_row_id = fts_row_addr_to_row_id( - &dataset, - opened_columns - .iter() - .flat_map(|(_, indices)| indices.first()) - .next(), - ) - .await?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, address_domain).await?; let mut tokenizer_indices = HashMap::with_capacity(opened_columns.len()); let mut partition_counts = HashMap::with_capacity(opened_columns.len()); diff --git a/rust/lance/src/io/exec/fts/match_query.rs b/rust/lance/src/io/exec/fts/match_query.rs index ad55ee73eef..77735ea1172 100644 --- a/rust/lance/src/io/exec/fts/match_query.rs +++ b/rust/lance/src/io/exec/fts/match_query.rs @@ -669,7 +669,7 @@ impl ExecutionPlan for MatchQueryExec { } else { true }; - let address_domain = fts_segments_are_address_domain(&ds, &segments); + let address_domain = fts_segments_are_address_domain(&ds, &segments)?; let ds_for_scope = ds.clone(); let indices = open_fts_segments(&ds, &column, &segments, &metrics.index_metrics).await?; @@ -768,7 +768,7 @@ impl ExecutionPlan for MatchQueryExec { &metrics, ) .await; - let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, indices.first()).await?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, address_domain).await?; let mut documents = search_prepared_segments( &indices, prepared, diff --git a/rust/lance/src/io/exec/fts/phrase.rs b/rust/lance/src/io/exec/fts/phrase.rs index 76a7d681914..688e89cec63 100644 --- a/rust/lance/src/io/exec/fts/phrase.rs +++ b/rust/lance/src/io/exec/fts/phrase.rs @@ -534,7 +534,7 @@ impl ExecutionPlan for PhraseQueryExec { &metrics.segment_bind_duration, ) .await?; - let address_domain = fts_segments_are_address_domain(&ds, &segments); + let address_domain = fts_segments_are_address_domain(&ds, &segments)?; let ds_for_scope = ds.clone(); let indices = open_fts_segments(&ds, &column, &segments, &metrics.index_metrics).await?; @@ -607,7 +607,7 @@ impl ExecutionPlan for PhraseQueryExec { .await; let tokens = Arc::new(tokens); let params = Arc::new(params); - let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, indices.first()).await?; + let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, address_domain).await?; let documents = search_segments( &indices, tokens, diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index 52f9a04014d..5565fd70b46 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -15,7 +15,6 @@ use lance_core::utils::tokio::get_num_compute_intensive_cpus; use lance_core::{Error, Result}; use lance_index::metrics::MetricsCollector; use lance_index::prefilter::PreFilter; -use lance_index::scalar::ScalarIndex; use lance_index::scalar::inverted::builder::ScoredDoc; use lance_index::scalar::inverted::query::{FtsSearchParams, Operator, Tokens}; use lance_index::scalar::inverted::{CombinedFieldColumn, InvertedIndex, MemBM25Scorer}; @@ -44,20 +43,75 @@ pub(super) type RowAddrToRowId = dyn Fn(u64) -> Option + Send + Sync; /// row address are the same value, and `build_scalar_index` relabels a fresh /// build's segment to a pre-`INVERTED_ROW_ADDR_DOMAIN_VERSION` version in /// that case specifically so an old reader still understands it -- not -/// because its stored values differ in kind. With stable row ids the two -/// domains genuinely can differ, and then this defers to the first segment's -/// own `results_are_row_addrs()` (uniform across a committed named index; see -/// `append.rs`'s `legacy_domain_mismatch`), true unless it is a legacy -/// segment predating that version. +/// because its stored values differ in kind. Mixed labels are therefore both +/// expected and harmless on such a dataset, and are not checked. +/// +/// With stable row ids the two domains genuinely differ, and every segment +/// reaching one query has to agree on which one it stores. A caller passes +/// every segment the query will read, which for a multi-column query +/// (`combined_fields`, a cross-column compound) spans *several named +/// indexes*: their postings are merged on the stored identifier alone, so +/// one column's row id `2` and another's row address `1 << 32` for the same +/// row would be scored as two unrelated documents. Within a single named +/// index that mix is already refused at write time -- `optimize_indices`' +/// `legacy_domain_mismatch` rebuilds rather than merging across domains, and +/// `manifest_build` rejects a commit that would publish one -- but nothing +/// couples two columns' indexes, and nothing could: rebuilding one column's +/// index is a legitimate commit on its own, and only a query spanning both +/// makes the pair wrong. Disagreement is therefore rejected here, at the one +/// point that sees every index a query reads. pub(super) fn fts_segments_are_address_domain( dataset: &Dataset, segments: &[IndexMetadata], -) -> bool { - !dataset.manifest.uses_stable_row_ids() - || segments - .first() - .map(|segment| segment.results_are_row_addrs()) - .unwrap_or(true) +) -> Result { + if !dataset.manifest.uses_stable_row_ids() { + return Ok(true); + } + shared_segment_domain(segments) +} + +/// The one domain every segment in `segments` agrees on, or an error naming +/// the two that disagree. `true` for an empty set, which has nothing to +/// contradict. +/// +/// Within one named index a mixed set is already refused when it is committed +/// (`manifest_build`'s per-name check), so reaching this with one is a sign of +/// a manifest written by something other than that path. Across named indexes +/// -- the columns of one multi-column query -- nothing refuses it at write +/// time and nothing could: rebuilding one column's index is a legitimate +/// commit on its own, and only a query spanning both makes the pair wrong. +fn shared_segment_domain(segments: &[IndexMetadata]) -> Result { + let Some(first) = segments.first() else { + return Ok(true); + }; + let first_is_row_addrs = first.results_are_row_addrs(); + if let Some(other) = segments + .iter() + .find(|segment| segment.results_are_row_addrs() != first_is_row_addrs) + { + let describe = |segment: &IndexMetadata| { + format!( + "'{}' ({}, index_version {}) stores row {}", + segment.name, + segment.uuid, + segment.index_version, + if segment.results_are_row_addrs() { + "addresses" + } else { + "ids" + }, + ) + }; + return Err(Error::invalid_input(format!( + "FTS index segments disagree on the identity domain they store: segment {} \ + while segment {}. A query merges their postings on that identifier alone and \ + cannot combine the two domains. Rebuild the older index with \ + create_index(..., replace: true).", + describe(first), + describe(other), + ))); + } + Ok(first_is_row_addrs) } /// Open one FTS segment as an [`InvertedIndex`]. @@ -119,9 +173,11 @@ pub(super) async fn open_fts_segments( // A segment persisted before `INVERTED_ROW_ADDR_DOMAIN_VERSION` stores row // ids, which can remain live in a sibling segment after a stable-row-id // row moves; a segment built since stores row addresses, which do not - // (see `SegmentRowDomain`). `results_are_row_addrs` is uniform across a - // named index's segments (`append.rs` rebuilds rather than mixes them), - // so the first segment's domain speaks for all of them. + // (see `SegmentRowDomain`). Opening is the chokepoint every indexed FTS + // path funnels through, so this is where a committed index whose segments + // disagree fails loudly rather than answering from two numbering systems + // at once. + fts_segments_are_address_domain(dataset, segments)?; let row_domain = match segments.first() { Some(first) if first.results_are_row_addrs() => SegmentRowDomain::RowAddress, _ => SegmentRowDomain::RowId, @@ -135,9 +191,11 @@ pub(super) async fn open_fts_segments( } /// Build the row-address-to-row-id translation this query's final output -/// needs, from `representative`'s domain -- every segment of a committed -/// named index shares one domain (`append.rs`'s `legacy_domain_mismatch` -/// forces a rebuild rather than letting them disagree). +/// needs, for a query whose segments resolved to `address_domain` via +/// [`fts_segments_are_address_domain`]. Taking the resolved domain rather +/// than re-deriving one from a representative index keeps the translation of +/// the results and the domain the postings and masks were read in from +/// drifting apart -- on a multi-column query they are not the same index. /// /// `None` (a no-op) when the two coincide: no stable row ids, or a /// row-id-domain segment. The latter is a transient state right after a @@ -154,11 +212,9 @@ pub(super) async fn open_fts_segments( /// narrower per-segment union. pub(super) async fn fts_row_addr_to_row_id( dataset: &Dataset, - representative: Option<&Arc>, + address_domain: bool, ) -> Result>> { - if !dataset.manifest.uses_stable_row_ids() - || !representative.is_some_and(|index| index.results_are_row_addresses()) - { + if !dataset.manifest.uses_stable_row_ids() || !address_domain { return Ok(None); } let fragment_ids = dataset @@ -433,3 +489,94 @@ pub(super) async fn search_segments( .map(|std::cmp::Reverse(document)| document) .collect()) } + +#[cfg(test)] +mod tests { + use super::*; + use lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION; + + fn segment(name: &str, index_version: i32) -> IndexMetadata { + IndexMetadata { + uuid: uuid::Uuid::new_v4(), + fields: vec![0], + covering_fields: Vec::new(), + name: name.to_string(), + dataset_version: 1, + fragment_bitmap: None, + // `results_are_row_addrs` reads the details' type alongside the + // version, so the stub has to carry an FTS identity. + index_details: Some(Arc::new(prost_types::Any { + type_url: "type.googleapis.com/lance.table.InvertedIndexDetails".to_string(), + value: Vec::new(), + })), + index_version, + created_at: None, + base_id: None, + files: None, + clustering_id: None, + metadata: Default::default(), + } + } + + const ADDR_VERSION: i32 = INVERTED_ROW_ADDR_DOMAIN_VERSION as i32; + const LEGACY_VERSION: i32 = ADDR_VERSION - 1; + + #[test] + fn empty_and_uniform_segment_sets_resolve_to_one_domain() { + assert!(shared_segment_domain(&[]).unwrap()); + assert!( + shared_segment_domain(&[ + segment("title_idx", ADDR_VERSION), + segment("title_idx", ADDR_VERSION), + ]) + .unwrap() + ); + assert!( + !shared_segment_domain(&[ + segment("title_idx", LEGACY_VERSION), + segment("title_idx", LEGACY_VERSION), + ]) + .unwrap() + ); + } + + /// A manifest written outside `manifest_build`'s commit-time check can + /// still pair the two domains, and a multi-column query pairs two named + /// indexes that nothing checks together at all. Either way the read side + /// has to refuse rather than let one segment's domain speak for the rest. + #[test] + fn disagreeing_segments_are_rejected_and_both_are_named() { + for (left, right) in [("title_idx", "body_idx"), ("title_idx", "title_idx")] { + let error = shared_segment_domain(&[ + segment(left, ADDR_VERSION), + segment(right, LEGACY_VERSION), + ]) + .expect_err("disagreeing segments should be rejected"); + let message = error.to_string(); + assert!( + message.contains("disagree on the identity domain"), + "unexpected error: {message}" + ); + assert!( + message.contains("stores row addresses") && message.contains("stores row ids"), + "error should say what each segment stores: {message}" + ); + assert!( + message.contains(left) && message.contains(right), + "error should name both segments: {message}" + ); + } + } + + /// Order must not decide the outcome: the disagreement is symmetric. + #[test] + fn a_legacy_segment_first_is_rejected_too() { + assert!( + shared_segment_domain(&[ + segment("title_idx", LEGACY_VERSION), + segment("body_idx", ADDR_VERSION), + ]) + .is_err() + ); + } +} From a3b946754c77485bb93236492efc026bc9040ea1 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 15:40:02 -0800 Subject: [PATCH 03/15] fix(fts): apply row-address segment coverage as a whole-fragment mask Opening a multi-segment FTS index under stable row ids failed outright with "segment coverage of row-address hits has no live row ids". `SegmentCoverage::resolve` gives a row-address-domain index `Restriction::Fragments` -- a hit must lie in a fragment the segment still covers -- while a row-id-domain one gets `Restriction::LiveRowIds`. `open_fts_segment` asked for the latter unconditionally via `live_rows`, which errors for anything else. The filtering paths (`restrict`, `restrict_lookup`) already handled both through `AllowedRows`; only FTS, which hands the restriction to the segment's own search to apply while it scores, was still row-id only. `allowed_row_mask` now serves that shape for both restrictions, allowing each covered fragment whole for row-address hits. A fragment is one entry with no per-row bitmap, so a coverage spanning the whole table costs one small entry per fragment rather than one per row -- the reason the per-row path walks hits instead of coverage does not apply to building the mask. This only surfaced once Inverted moved to the row-address domain, since before that every FTS segment resolved to `LiveRowIds`. It accounted for 97 of the 98 failures `cargo test -p lance --lib` showed on this branch; the suite is now at parity with the base commit (11408 passed, 1 pre-existing unrelated RTree failure). Co-Authored-By: Claude Opus 5 --- rust/lance/src/index/segment_coverage.rs | 80 ++++++++++++++++++++++++ rust/lance/src/io/exec/fts/segments.rs | 2 +- 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/rust/lance/src/index/segment_coverage.rs b/rust/lance/src/index/segment_coverage.rs index c8978c47ce3..19cac08bdec 100644 --- a/rust/lance/src/index/segment_coverage.rs +++ b/rust/lance/src/index/segment_coverage.rs @@ -150,6 +150,34 @@ impl SegmentCoverage { .await } + /// The rows segment `index` may report, as a mask over its own stored + /// identifiers. + /// + /// [`Self::restrict`] and [`Self::restrict_lookup`] filter hits a segment + /// has already produced, so they can test one row at a time against + /// [`AllowedRows`]. FTS instead hands the restriction to the segment's own + /// search to apply while it scores (see + /// [`InvertedIndex::with_allowed_rows`](lance_index::scalar::inverted::InvertedIndex::with_allowed_rows)), + /// which needs it up front as a mask. + /// + /// For row-address hits that mask allows the segment's covered fragments + /// whole, which is what `AllowedRows::Fragments` tests one row at a time. + /// Each fragment is one entry carrying no per-row bitmap, so a coverage + /// spanning the whole table costs one small entry per fragment rather than + /// one per row. + pub(crate) async fn allowed_row_mask(&self, index: usize) -> Result> { + match &self.restriction { + Restriction::LiveRowIds(_) => self.live_rows(index).await, + Restriction::Fragments => { + let mut allowed = RowAddrTreeMap::new(); + for fragment in self.coverage(index)? { + allowed.insert_fragment(fragment); + } + Ok(Arc::new(RowAddrMask::from_allowed(allowed))) + } + } + } + async fn allowed_rows(&self, index: usize) -> Result> { Ok(match &self.restriction { Restriction::LiveRowIds(_) => AllowedRows::LiveRowIds(self.live_rows(index).await?), @@ -263,6 +291,58 @@ mod tests { .unwrap() } + async fn two_fragment_dataset() -> Dataset { + let batch = record_batch!(("value", Int32, [1, 2])).unwrap(); + let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + Dataset::write( + reader, + "memory://", + Some(WriteParams { + enable_stable_row_ids: true, + max_rows_per_file: 1, + ..Default::default() + }), + ) + .await + .unwrap() + } + + /// FTS applies a segment's coverage inside its own search rather than + /// filtering hits afterward, so it takes the restriction as a mask. For + /// row-address hits that mask has to allow each covered fragment whole -- + /// including offsets it holds no posting for -- and agree with the per-row + /// test the filtering paths use. + #[tokio::test] + async fn row_address_coverage_masks_whole_fragments() { + let dataset = two_fragment_dataset().await; + let first = segment(Some(RoaringBitmap::from_iter([0]))); + let second = segment(Some(RoaringBitmap::from_iter([1]))); + let coverage = + SegmentCoverage::resolve(&dataset, &[&first, &second], SegmentRowDomain::RowAddress) + .await + .unwrap() + .expect("two segments need masking"); + + for (index, covered, uncovered) in [(0usize, 0u32, 1u32), (1, 1, 0)] { + let mask = coverage.allowed_row_mask(index).await.unwrap(); + let per_row = coverage.allowed_rows(index).await.unwrap(); + for offset in [0u32, 7, u32::MAX] { + let inside = u64::from(RowAddress::new_from_parts(covered, offset)); + let outside = u64::from(RowAddress::new_from_parts(uncovered, offset)); + assert!( + mask.selected(inside), + "segment {index} should allow all of fragment {covered}" + ); + assert!( + !mask.selected(outside), + "segment {index} should not allow fragment {uncovered}" + ); + assert_eq!(mask.selected(inside), per_row.contains(inside)); + assert_eq!(mask.selected(outside), per_row.contains(outside)); + } + } + } + #[tokio::test] async fn skips_masking_for_one_segment_or_row_ids_without_stable_row_ids() { let stable = dataset(true).await; diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index 5565fd70b46..c8030b04fef 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -142,7 +142,7 @@ pub(super) async fn open_fts_segment( }; let allowed_rows = async { match coverage { - Some((coverage, index)) => Ok(Some(coverage.live_rows(index).await?)), + Some((coverage, index)) => Ok(Some(coverage.allowed_row_mask(index).await?)), None => Ok(None), } }; From 98b325fffaa7a59bff0c23db1634d151ae1d5b33 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 16:36:20 -0800 Subject: [PATCH 04/15] test(fts): pin the row-address migration's domain-sensitive paths Addresses the review's "I can't find a test that fails without either fix". Measured each fix by reverting it on this branch and running the suite, rather than assuming: - Prefilter domain translation (`utils.rs`): already covered -- 46 tests fail with `translate_filter_in_domain`/`translate_overlay_block_in_domain` neutered. - Old-data filter domain (`append.rs`, `false` -> `idx.results_are_row_addrs()`): already covered -- `stale_posting_after_in_place_update_with_stable_row_ids` and `test_optimize_fts_consolidates_single_row_appends::stable_ids` both fail when it is put back. - `legacy_domain_mismatch` (`append.rs`): genuinely uncovered. Reverting it changed nothing in the suite. Pinned here by `test_optimize_append_rebuilds_stray_legacy_fts_segment_with_stable_row_ids`, the FTS counterpart of the existing BTree/NGram `test_optimize_append_rebuilds_stray_legacy_segment_with_stable_row_ids`: append-mode optimize selects no old segments to merge, so without the check a stray row-id-domain segment is left beside a fresh address-domain delta. Its consequence is a hard failure rather than corruption -- `manifest_build`'s per-name guard rejects the commit, so optimize errors -- which the test now pins. Also adds the requested direct unit tests for `translate_treemap_to_row_addr_domain` (`row_addr_domain_tests`): rows in fragments past the first, allow-list and block-list shapes, a row moved by an update, and ids that no longer resolve. Note none of these can fail on the *base* commit: before Inverted moved to the row-address domain there was no address-domain FTS segment, so `results_are_row_addrs()` was always false for Inverted and the hardcoded `false` was correct. These are hazards the migration introduces and this PR handles, not fixes to pre-existing defects, so "fails on the base commit" is unsatisfiable for them; "fails with the hunk reverted on this branch" is the criterion that applies, and is what was measured above. Co-Authored-By: Claude Opus 5 --- rust/lance/src/index/append.rs | 117 +++++++++++++++++++++++++++++ rust/lance/src/io/exec/utils.rs | 129 ++++++++++++++++++++++++++++++++ 2 files changed, 246 insertions(+) diff --git a/rust/lance/src/index/append.rs b/rust/lance/src/index/append.rs index 051ebfd7f76..0057710df27 100644 --- a/rust/lance/src/index/append.rs +++ b/rust/lance/src/index/append.rs @@ -5293,6 +5293,123 @@ mod tests { } } + /// The same stray-legacy-segment gap for FTS, which reaches the rebuild + /// decision through the separate Inverted dispatch path rather than the + /// `update_criteria.requires_old_data` one the types above use. + /// + /// `select_segments_to_merge` picks nothing in append mode, so without + /// `legacy_domain_mismatch` folding every remaining row-id-domain segment + /// into the rebuild, optimize would try to leave the legacy segment beside + /// a freshly built address-domain delta -- an index whose two segments + /// disagree about what their stored identifiers mean. + #[tokio::test] + async fn test_optimize_append_rebuilds_stray_legacy_fts_segment_with_stable_row_ids() { + let test_dir = TempStrDir::default(); + let test_uri = test_dir.as_str(); + let batch = |start: i32, end: i32| { + let ids = Int32Array::from_iter_values(start..end); + let bodies = + StringArray::from_iter_values((start..end).map(|i| format!("common song{i}"))); + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("body", DataType::Utf8, false), + ])), + vec![Arc::new(ids), Arc::new(bodies)], + ) + .unwrap() + }; + + let initial = batch(0, 8); + let mut dataset = Dataset::write( + RecordBatchIterator::new(vec![Ok(initial.clone())], initial.schema()), + test_uri, + Some(WriteParams { + max_rows_per_file: 8, + enable_stable_row_ids: true, + ..Default::default() + }), + ) + .await + .unwrap(); + let params = InvertedIndexParams::default().num_workers(1); + let segment = crate::index::create::CreateIndexBuilder::new( + &mut dataset, + &["body"], + IndexType::Inverted, + ¶ms, + ) + .name("body_idx".into()) + .execute_uncommitted() + .await + .unwrap(); + assert!( + segment.results_are_row_addrs(), + "a segment built by the current code is always address-domain" + ); + + // Relabel below `INVERTED_ROW_ADDR_DOMAIN_VERSION` so the index reads + // as a pre-migration one. Its postings are still addresses, which is + // fine here: the rebuild this test asserts discards the segment's data + // and rescans, so only the label is ever consulted. + let legacy_segment = IndexMetadata { + index_version: 3, + ..segment + }; + dataset + .commit_existing_index_segments("body_idx", "body", vec![legacy_segment]) + .await + .unwrap(); + let legacy = dataset.load_indices_by_name("body_idx").await.unwrap(); + assert_eq!(legacy.len(), 1); + assert!(!legacy[0].results_are_row_addrs()); + + // A second fragment, left unindexed, then append-mode optimize: the + // case that selects zero old segments to merge. + let appended = batch(8, 16); + let mut dataset = Dataset::write( + RecordBatchIterator::new(vec![Ok(appended.clone())], appended.schema()), + test_uri, + Some(WriteParams { + max_rows_per_file: 8, + mode: WriteMode::Append, + ..Default::default() + }), + ) + .await + .unwrap(); + dataset + .optimize_indices(&OptimizeOptions::append()) + .await + .unwrap(); + + let dataset = DatasetBuilder::from_uri(test_uri).load().await.unwrap(); + let committed = dataset.load_indices_by_name("body_idx").await.unwrap(); + assert_eq!( + committed.len(), + 1, + "the legacy segment must be rebuilt with the new data, not left \ + beside it: {committed:?}" + ); + assert!( + committed[0].results_are_row_addrs(), + "the rebuilt segment must be address-domain" + ); + + // Every row must still be findable, from both the original fragment + // and the appended one. + let mut scan = dataset.scan(); + scan.full_text_search(FullTextSearchQuery::new("common".to_owned())) + .unwrap(); + assert_eq!(scan.count_rows().await.unwrap(), 16); + for term in ["song0", "song7", "song8", "song15"] { + let mut scan = dataset.scan(); + scan.full_text_search(FullTextSearchQuery::new(term.to_owned())) + .unwrap(); + assert_eq!(scan.count_rows().await.unwrap(), 1, "missing {term}"); + } + } + /// A trailing merge window must also rebuild legacy segments outside it. /// Use a real pre-migration index: committing a mixture of row domains is /// rejected before optimization can run. diff --git a/rust/lance/src/io/exec/utils.rs b/rust/lance/src/io/exec/utils.rs index 376d999ee76..5c72e34d1f9 100644 --- a/rust/lance/src/io/exec/utils.rs +++ b/rust/lance/src/io/exec/utils.rs @@ -3181,3 +3181,132 @@ mod tests { ); } } + +#[cfg(test)] +mod row_addr_domain_tests { + use super::*; + use crate::dataset::{UpdateBuilder, WriteParams}; + use arrow_array::{RecordBatchIterator, record_batch}; + use lance_core::utils::address::RowAddress; + use lance_core::utils::tempfile::TempStrDir; + use lance_select::RowSetOps; + + /// Four rows over two fragments under stable row ids, so a row id and its + /// row address are two different numbers for every row past the first + /// fragment. + async fn two_fragment_dataset(uri: &str) -> Dataset { + let batch = record_batch!(("id", Int32, [0, 1, 2, 3])).unwrap(); + let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + Dataset::write( + reader, + uri, + Some(WriteParams { + max_rows_per_file: 2, + enable_stable_row_ids: true, + ..Default::default() + }), + ) + .await + .unwrap() + } + + fn treemap(rows: impl IntoIterator) -> RowAddrTreeMap { + let mut map = RowAddrTreeMap::new(); + for row in rows { + map.insert(row); + } + map + } + + fn addr(fragment: u32, offset: u32) -> u64 { + u64::from(RowAddress::new_from_parts(fragment, offset)) + } + + /// Row ids 0..4 lie in fragments 0 and 1, so the second fragment's ids and + /// addresses disagree. Translating has to move exactly those. + #[tokio::test] + async fn translates_row_ids_in_every_fragment() { + let dir = TempStrDir::default(); + let dataset = two_fragment_dataset(&dir).await; + + let translated = translate_treemap_to_row_addr_domain(&dataset, &treemap(0..4)) + .await + .unwrap(); + let expected = treemap([addr(0, 0), addr(0, 1), addr(1, 0), addr(1, 1)]); + assert_eq!(translated, expected); + + // The ids of the second fragment really do differ from their + // addresses, or this test would pass without translating anything. + assert_ne!(treemap(0..4), expected); + } + + /// Both mask shapes carry the same translation: an allow-list and a + /// block-list of the same rows must name the same addresses. + #[tokio::test] + async fn translates_allow_lists_and_block_lists_alike() { + let dir = TempStrDir::default(); + let dataset = two_fragment_dataset(&dir).await; + let rows = treemap([2, 3]); + let expected = treemap([addr(1, 0), addr(1, 1)]); + + let allow = row_id_mask_to_row_addr_domain( + &dataset, + Arc::new(RowAddrMask::from_allowed(rows.clone())), + ) + .await + .unwrap(); + assert_eq!(allow.allow_list(), Some(&expected)); + assert!(allow.block_list().is_none()); + + let block = + row_id_mask_to_row_addr_domain(&dataset, Arc::new(RowAddrMask::from_block(rows))) + .await + .unwrap(); + assert_eq!(block.block_list(), Some(&expected)); + assert!(block.allow_list().is_none()); + } + + /// An update rewrites a row into a new fragment while it keeps its row id. + /// The translation has to follow it there -- taking the id for an address + /// would name whatever now sits at the old location. + #[tokio::test] + async fn follows_a_row_moved_by_an_update() { + let dir = TempStrDir::default(); + let dataset = two_fragment_dataset(&dir).await; + let before = translate_treemap_to_row_addr_domain(&dataset, &treemap([0])) + .await + .unwrap(); + assert_eq!(before, treemap([addr(0, 0)])); + + let dataset = UpdateBuilder::new(Arc::new(dataset)) + .update_where("id = 0") + .unwrap() + .set("id", "100") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap() + .new_dataset; + + // Row id 0 survives the update; its address does not. + let after = translate_treemap_to_row_addr_domain(&dataset, &treemap([0])) + .await + .unwrap(); + assert_ne!(after, before, "the row moved, so its address must change"); + assert_eq!(after.len(), Some(1)); + } + + /// A row id that no longer resolves contributes no address rather than + /// leaking through untranslated. + #[tokio::test] + async fn drops_row_ids_that_no_longer_resolve() { + let dir = TempStrDir::default(); + let dataset = two_fragment_dataset(&dir).await; + let translated = translate_treemap_to_row_addr_domain(&dataset, &treemap([0, 9_999])) + .await + .unwrap(); + assert_eq!(translated, treemap([addr(0, 0)])); + } +} From 0ca85d02b30047ded8aa9731cdfe5c71eec61da7 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 17:10:33 -0800 Subject: [PATCH 05/15] refactor(fts): address review on domain translation, spec wording and tests - `translate_treemap_to_row_addr_domain` now reports a whole-fragment entry instead of returning the treemap untranslated. In a row-id-domain mask such an entry would mean 2^32 contiguous row ids, so it really means an address-domain mask was mislabelled upstream; passing it through handed the caller a mask it then ANDed into an address-domain one, and silently dropped the translation of every `Partial` entry beside it. Nothing in the suite produces one, confirming it was unreachable-by-design rather than relied upon. - FTS format spec: state the domain rule normatively -- what readers must do with `_rowid`, when writers may still label a segment 1-3, that a version-4 reader must support everything version 3 does, and that the posting format is recorded separately and must not be inferred from `index_version`. - Extract the repeated relabel-to-row-id-domain snippet (12 copies across 5 files) as `utils::test::as_legacy_row_id_segment`, and say once, on the helper, what the comment used to say at each site -- including the part that was never written down: the segment it returns still stores row addresses while claiming row ids, so it is right for testing that the system detects the domain and wrong for testing what a query through it returns. - `normalize_inverted_details`: the comment claimed the fallback never synthesizes a posting format for version 4 while the arm below it mapped `3 | 4 => 3`. Keep the arm -- a segment arriving without the field should be read, not rejected -- and say why. - `create.rs`: drop the note about what Inverted used to do; the comment only needs to say why vector indices are refused. Co-Authored-By: Claude Opus 5 --- docs/src/format/index/scalar/fts.md | 2 +- .../src/dataset/optimize/tests/commit.rs | 5 +--- .../src/dataset/optimize/tests/frag_reuse.rs | 20 ++----------- rust/lance/src/dataset/write/update.rs | 11 ++----- rust/lance/src/index/append.rs | 19 ++---------- rust/lance/src/index/create.rs | 4 --- .../index/frag_reuse_with_stable_row_ids.rs | 29 +++---------------- rust/lance/src/index/scalar/inverted.rs | 7 +++-- rust/lance/src/io/exec/utils.rs | 20 +++++++++---- rust/lance/src/utils/test.rs | 29 +++++++++++++++++++ 10 files changed, 63 insertions(+), 83 deletions(-) diff --git a/docs/src/format/index/scalar/fts.md b/docs/src/format/index/scalar/fts.md index bd7ae6da5d2..f3399a2008c 100644 --- a/docs/src/format/index/scalar/fts.md +++ b/docs/src/format/index/scalar/fts.md @@ -20,7 +20,7 @@ The FTS index consists of multiple files storing the token dictionary, document An FTS index may contain multiple partitions. Each partition has its own set of token, document, and posting list files, prefixed with the partition ID (e.g. `part_0_tokens.lance`, `part_0_docs.lance`, `part_0_invert.lance`). The `metadata.lance` file lists all partition IDs in the index. At query time, every partition must be searched and the results combined to produce the final ranked output. Fewer partitions generally means better query performance, since each partition requires its own token dictionary lookup and posting list scan. The number of partitions is controlled by the training configuration -- specifically `LANCE_FTS_TARGET_SIZE` determines how large each merged partition can grow (see [Training Process](#training-process) for details). -From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. This version is independent of the posting-list format below (tracked separately via file metadata, not `index_version`): a row-address-domain segment can pair with any posting format. +From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, `docs.lance._rowid` holds the document's physical row address (`fragment_id << 32 | offset`). In versions 1 through 3 it holds the dataset's row id. Readers must interpret `_rowid` according to the segment's `index_version`. Writers may label a segment with version 1 through 3 only on a dataset without stable row ids, where row ids and row addresses are equal. A reader that supports version 4 must also support every capability of version 3. The posting-list format is recorded separately and must not be inferred from `index_version`. ### Token Dictionary File Schema diff --git a/rust/lance/src/dataset/optimize/tests/commit.rs b/rust/lance/src/dataset/optimize/tests/commit.rs index b5b9f66cf13..a562a5913a6 100644 --- a/rust/lance/src/dataset/optimize/tests/commit.rs +++ b/rust/lance/src/dataset/optimize/tests/commit.rs @@ -579,10 +579,7 @@ async fn test_commit_refuses_recording_mismatch_before_reserving_fragments( .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("i_idx", "cat", vec![legacy_segment]) .await diff --git a/rust/lance/src/dataset/optimize/tests/frag_reuse.rs b/rust/lance/src/dataset/optimize/tests/frag_reuse.rs index 12e8278c00b..1bb0c8e5abd 100644 --- a/rust/lance/src/dataset/optimize/tests/frag_reuse.rs +++ b/rust/lance/src/dataset/optimize/tests/frag_reuse.rs @@ -2870,21 +2870,13 @@ async fn test_compact_ngram_with_stable_row_ids(#[values(false, true)] defer_ind #[tokio::test] async fn test_defer_index_remap_rejected_while_row_id_index_present() { let mut dataset = zonemap_stable_row_id_dataset("memory://").await; - // A fresh Inverted index always trains in row-address domain, so a - // row-id-domain one (as every segment predating - // `INVERTED_ROW_ADDR_DOMAIN_VERSION` is) has to be simulated by relabeling - // a freshly built segment's `index_version` down -- the same trick - // `results_are_row_addrs` itself relies on to tell the two apart. let params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); let segment = CreateIndexBuilder::new(&mut dataset, &["cat"], IndexType::Inverted, ¶ms) .name("id_idx".into()) .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("id_idx", "cat", vec![legacy_segment]) .await @@ -3135,10 +3127,7 @@ async fn test_defer_index_remap_racing_row_id_index_creation() { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); concurrent .commit_existing_index_segments("id_idx", "cat", vec![legacy_segment]) .await @@ -3372,10 +3361,7 @@ async fn test_index_creation_racing_deferred_compaction_with_stable_row_ids( // segment this race specifically exercises (same trick as // `test_defer_index_remap_racing_row_id_index_creation`). let segment = builder.execute_uncommitted().await?; - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("i_idx", index_column, vec![legacy_segment]) .await diff --git a/rust/lance/src/dataset/write/update.rs b/rust/lance/src/dataset/write/update.rs index 94301496d3a..fd5556db957 100644 --- a/rust/lance/src/dataset/write/update.rs +++ b/rust/lance/src/dataset/write/update.rs @@ -1026,7 +1026,7 @@ mod tests { use lance_io::object_store::ObjectStoreParams; use lance_linalg::distance::MetricType; use lance_table::feature_flags::FLAG_MIXED_DATA_FILE_VERSIONS; - use lance_table::format::{IndexMetadata, ROW_CREATED_AT_VERSION_FIELD_ID}; + use lance_table::format::ROW_CREATED_AT_VERSION_FIELD_ID; use object_store::throttle::ThrottleConfig; use rstest::rstest; use tokio::sync::Barrier; @@ -1887,10 +1887,6 @@ mod tests { .await .unwrap(); - // A fresh Inverted index always trains in row-address domain, so a - // row-id-domain one is simulated by relabeling a freshly built - // segment's `index_version` down -- the same trick - // `results_are_row_addrs` itself relies on to tell the two apart. let scalar_params = ScalarIndexParams::for_builtin(BuiltinIndexType::Inverted); let segment = CreateIndexBuilder::new(&mut dataset, &["str"], IndexType::Inverted, &scalar_params) @@ -1898,10 +1894,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("str_idx", "str", vec![legacy_segment]) .await diff --git a/rust/lance/src/index/append.rs b/rust/lance/src/index/append.rs index 0057710df27..65c4282160f 100644 --- a/rust/lance/src/index/append.rs +++ b/rust/lance/src/index/append.rs @@ -5238,10 +5238,7 @@ mod tests { // legacy segments on disk differ from a fresh one only in that label // (each plugin's `load_index` derives domain purely from the version // its caller passes in, never from the file itself). - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("id_idx", "id", vec![legacy_segment]) .await @@ -5525,10 +5522,7 @@ mod tests { assert!(legacy_segment.results_are_row_addrs()); // Relabel as pre-migration row-id domain, simulating a segment built // before stable row ids were enabled for this dataset. - let legacy_segment = IndexMetadata { - index_version: 0, - ..legacy_segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(legacy_segment); dataset .commit_existing_index_segments("value_idx", "value", vec![legacy_segment]) .await @@ -6998,10 +6992,6 @@ mod tests { // Exercise the stable-row-id allow-list and address-domain deletion // filtering paths. Both must propagate unreadable deletion vectors. if index_type == IndexType::Inverted { - // A fresh Inverted index always trains in row-address domain, so - // the row-id-domain allow-list path is simulated by relabeling a - // freshly built segment's `index_version` down -- the same trick - // `results_are_row_addrs` itself relies on to tell the two apart. let segment = CreateIndexBuilder::new( &mut dataset, &["cat"], @@ -7011,10 +7001,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); let name = legacy_segment.name.clone(); dataset .commit_existing_index_segments(&name, "cat", vec![legacy_segment]) diff --git a/rust/lance/src/index/create.rs b/rust/lance/src/index/create.rs index 90855a61fbd..55c6f459fea 100644 --- a/rust/lance/src/index/create.rs +++ b/rust/lance/src/index/create.rs @@ -245,10 +245,6 @@ impl<'a> CreateIndexBuilder<'a> { // handing that name out again commits two indices under it. let indices = load_all_indices(self.dataset).await?; // Vector indices always store row ids, so refuse them before training. - // Inverted used to as well, but it now trains in row-address domain - // like every other scalar index type (see - // `INVERTED_ROW_ADDR_DOMAIN_VERSION`), so it is no longer refused - // here. let index_kind = if self.index_type.is_vector() { Some("vector") } else { diff --git a/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs b/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs index 8e830d36b1f..2eb3447d8ee 100644 --- a/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs +++ b/rust/lance/src/index/frag_reuse_with_stable_row_ids.rs @@ -772,10 +772,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("category_idx", "category", vec![legacy_segment]) .await @@ -963,10 +960,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); dataset .commit_existing_index_segments("category_idx", "category", vec![legacy_segment]) .await @@ -1066,10 +1060,6 @@ mod tests { #[tokio::test] async fn test_incompatible_indices_are_hidden_from_readers() { let mut dataset = stable_row_id_dataset("memory://").await; - // A fresh Inverted index always trains in row-address domain, so the - // collision this test demonstrates is simulated by relabeling a - // freshly built segment's `index_version` down -- the same trick - // `results_are_row_addrs` itself relies on to tell the two apart. let segment = dataset .create_index_builder( &["category"], @@ -1079,10 +1069,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = IndexMetadata { - index_version: 0, - ..segment - }; + let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); let name = legacy_segment.name.clone(); dataset .commit_existing_index_segments(&name, "category", vec![legacy_segment]) @@ -1316,11 +1303,6 @@ mod tests { let mut dataset = stable_row_id_dataset(dir.as_str()).await; let mut other = Dataset::open(dir.as_str()).await.unwrap(); let frag_reuse = empty_frag_reuse_index(&dataset, RoaringBitmap::new()).await; - // A fresh Inverted index always trains in row-address domain, so the - // race this test exercises (a row-id-domain index and an FRI racing - // each other) is simulated by relabeling a freshly built segment's - // `index_version` down -- the same trick `results_are_row_addrs` - // itself relies on to tell the two apart. let inverted_index = other .create_index_builder( &["category"], @@ -1332,10 +1314,7 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let inverted_index = IndexMetadata { - index_version: 0, - ..inverted_index - }; + let inverted_index = crate::utils::test::as_legacy_row_id_segment(inverted_index); let result = if frag_reuse_first { commit_new_indices(&mut dataset, vec![frag_reuse]) diff --git a/rust/lance/src/index/scalar/inverted.rs b/rust/lance/src/index/scalar/inverted.rs index 0d1ee01aaff..b6726a23b13 100644 --- a/rust/lance/src/index/scalar/inverted.rs +++ b/rust/lance/src/index/scalar/inverted.rs @@ -879,8 +879,11 @@ pub(crate) fn transform_fts_document_stream( /// `index_version` 4 ([`lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION`]) /// marks row-address-domain segments; it is independent of the posting-list /// format, which every such segment already carries explicitly in -/// `details.posting_format_version` (see `InvertedIndexPlugin::train_inverted_index`), -/// so the fallback below never needs to synthesize one for it. +/// `details.posting_format_version` (see `InvertedIndexPlugin::train_inverted_index`). +/// The fallback below still maps version 4 to posting format V3, the newest +/// format and the only one a version-4 segment is ever written with, so that a +/// segment reaching here without the field -- which a correct writer never +/// produces -- is read rather than rejected. pub(crate) fn normalize_inverted_details( index: &IndexMetadata, mut details: InvertedIndexDetails, diff --git a/rust/lance/src/io/exec/utils.rs b/rust/lance/src/io/exec/utils.rs index 5c72e34d1f9..2230fb9b2bb 100644 --- a/rust/lance/src/io/exec/utils.rs +++ b/rust/lance/src/io/exec/utils.rs @@ -515,16 +515,26 @@ pub(crate) fn build_prefilter( } /// Translates one treemap's entries from row-id domain to row-address -/// domain. A "whole fragment" entry can't be enumerated one id at a time; it -/// is vanishingly unlikely to appear in a row-id-domain mask (it would -/// require 2^32 contiguous ids), so it is left untranslated rather than -/// failing the query. +/// domain. +/// +/// A "whole fragment" entry cannot be enumerated one id at a time, and in a +/// row-id-domain mask it should not exist: it would mean 2^32 contiguous row +/// ids, so in practice it means a fragment-shaped (already address-domain) +/// mask was labelled as row-id domain somewhere upstream. Returning the +/// treemap untranslated would hand the caller a mask it then ANDs into an +/// address-domain one, silently selecting unrelated rows -- and would drop +/// the translation of every `Partial` entry alongside it. It is reported +/// instead. pub(crate) async fn translate_treemap_to_row_addr_domain( dataset: &Dataset, treemap: &RowAddrTreeMap, ) -> Result { let Some(row_ids) = treemap.row_addrs() else { - return Ok(treemap.clone()); + return Err(Error::internal( + "a row-id-domain mask cannot hold a whole-fragment entry; it would mean 2^32 \ + contiguous row ids, so this mask is really address-domain and was mislabelled \ + before it reached the FTS prefilter", + )); }; let row_ids: Vec = row_ids.map(u64::from).collect(); let addrs = row_ids_to_row_addrs(dataset, &row_ids).await?; diff --git a/rust/lance/src/utils/test.rs b/rust/lance/src/utils/test.rs index 98dcea13bb5..68a74de55d4 100644 --- a/rust/lance/src/utils/test.rs +++ b/rust/lance/src/utils/test.rs @@ -1340,3 +1340,32 @@ pub async fn data_file_schema(dataset: &Dataset, path: &str) -> Schema { .unwrap(); reader.schema().as_ref().clone() } + +/// Relabel a freshly built index segment as a pre-migration, row-id-domain +/// one. +/// +/// Every builtin scalar index type now trains in the row-address domain +/// unconditionally, so a row-id-domain segment -- what every segment +/// predating its type's `*_ROW_ADDR_DOMAIN_VERSION` is -- can only be +/// obtained by relabeling a fresh one's `index_version` down. That is the +/// same signal `IndexMetadata::results_are_row_addrs` reads to tell the two +/// apart, and a real legacy segment on disk differs from a fresh one only in +/// that label: each plugin's `load_index` derives the domain from the version +/// its caller passes in, never from the file itself. +/// +/// **The returned segment's stored identifiers are still row addresses while +/// it claims to store row ids.** That makes it right for testing that the +/// system *detects* the domain -- a guard, a rejected commit, a forced +/// rebuild -- and wrong for testing what a query through it returns, which +/// would read addresses as ids and silently produce wrong rows. For a +/// queryable legacy segment the identities have to be remapped too, not just +/// relabeled. +#[cfg(test)] +pub fn as_legacy_row_id_segment( + segment: lance_table::format::IndexMetadata, +) -> lance_table::format::IndexMetadata { + lance_table::format::IndexMetadata { + index_version: 0, + ..segment + } +} From 19d267ca228a3098775b30ea8121835c190a0b40 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 17:26:53 -0800 Subject: [PATCH 06/15] fix(fts): keep tied top-k results in row-id order after translation Paging one row at a time through three equal-scoring rows returned `[1, 1, 2]` instead of `[0, 1, 2]`, with no writes between pages. Top-k selection ranks ties by the identifier the index stores, and that is now a row address. It cannot do otherwise: `combined_maxscore` discovers candidates in ascending stored-id order (`.min()` over the cursor heads), and its pruning is sound only because a candidate tying the threshold arrives after, and so loses to, every incumbent. Re-keying the heap on translated row ids -- the obvious fix -- would break that invariant, since candidates would still arrive in address order. So the ordering is reconciled after selection instead. An update moves a row's address without moving its row id, so selection keeps the lowest *address* among ties while the plan above sorts by `_rowid`; with a tight limit the row the plan would have ranked first was never returned at all, and paging repeated its neighbour. Each search whose results will be translated now retains `FTS_TIE_RERANK_BUDGET` extra candidates, so a tie group at the cutoff is held whole rather than cut at an arbitrary address, and `finalize_row_ids_and_scores` orders the survivors by `(score DESC, row_id ASC)` before applying the real limit. The widening is what fixes the paginated case -- the plan's own sort then sees the whole tie group -- and the re-rank covers the fully covered plan that returns this search's output directly, with no `SortExec` above it. Both only engage when results are actually translated (stable row ids plus an address-domain index), so a query needing no translation is unchanged. Like `WAND_TIE_COMPLETION_BUDGET`, the budget bounds how large a tie group can be and still resolve exactly. Applied to every FTS path that translates after a bounded top-k: combined fields, and the three compound paths. Co-Authored-By: Claude Opus 5 --- .../tests/dataset_fts_combined_fields.rs | 75 +++++++++++++++++++ rust/lance/src/io/exec/fts/combined_fields.rs | 25 +++++-- rust/lance/src/io/exec/fts/compound.rs | 60 +++++++++++++-- rust/lance/src/io/exec/fts/segments.rs | 64 ++++++++++++++++ 4 files changed, 212 insertions(+), 12 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index aac0f104519..d0d86b1f1b9 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -2921,3 +2921,78 @@ async fn test_fts_mixed_domain_within_one_index_is_rejected_at_commit() { "unexpected error: {error}" ); } + +/// Top-k selection ranks ties by the identifier the index stores, which is now +/// a row address, while the plan above sorts by `_rowid`. An update moves a +/// row's address without moving its row id, so the two orders disagree and +/// paging through a tie skipped row 0 and returned row 1 twice. Each page must +/// be the page the plan's own `(score DESC, _rowid ASC)` order implies. +#[tokio::test] +async fn test_fts_combined_fields_tied_pagination_follows_row_id_order() { + let dir = TempStrDir::default(); + let ds = write_fts_dataset( + &dir, + combined_fields_batch(vec![0, 1], vec!["alpha", "alpha"], vec!["beta", "beta"]), + Some(WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + ) + .await; + // Rewrites row id 0 into a new fragment, so its address now sorts after + // row id 1's while its row id still sorts before. + let updated = crate::dataset::UpdateBuilder::new(Arc::new(ds)) + .update_where("id = 0") + .unwrap() + .set("title", "'alpha'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut ds = updated.new_dataset.as_ref().clone(); + create_inverted_indices(&mut ds, &["title", "body"], &combined_fields_test_params()).await; + let ds = append_fts_dataset( + &dir, + combined_fields_batch(vec![2], vec!["alpha"], vec!["beta"]), + None, + ) + .await; + + let page = async |offset: i64| -> Vec { + let batch = ds + .scan() + .project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query(combined_query( + "alpha beta", + Operator::And, + ))) + .unwrap() + .limit(Some(1), Some(offset)) + .unwrap() + .try_into_batch() + .await + .unwrap(); + batch["id"].as_primitive::().values().to_vec() + }; + + let mut pages = Vec::new(); + for offset in 0..3 { + pages.extend(page(offset).await); + } + assert_eq!( + pages, + vec![0, 1, 2], + "one-row pages over a tie must walk every row once, in row-id order" + ); + + // The same rows, unpaginated, in the same order. + let all = fts_result_id_scores(&ds, combined_query("alpha beta", Operator::And), Some(10)) + .await + .into_iter() + .map(|(id, _)| id) + .collect::>(); + assert_eq!(all, vec![0, 1, 2]); +} diff --git a/rust/lance/src/io/exec/fts/combined_fields.rs b/rust/lance/src/io/exec/fts/combined_fields.rs index d074a851b75..d6df7c98f38 100644 --- a/rust/lance/src/io/exec/fts/combined_fields.rs +++ b/rust/lance/src/io/exec/fts/combined_fields.rs @@ -44,8 +44,8 @@ use tracing::instrument; use super::corpus::SharedFtsScorer; use super::query_tokens::{TokenizedQuery, fmt_tokenized_query, record_tokenized_query}; use super::segments::{ - combined_columns_the_prefilter_may_match, fts_row_addr_to_row_id, - fts_segments_are_address_domain, open_fts_segments, translate_row_ids_and_scores, + combined_columns_the_prefilter_may_match, finalize_row_ids_and_scores, fts_row_addr_to_row_id, + fts_segments_are_address_domain, open_fts_segments, widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -699,18 +699,33 @@ impl ExecutionPlan for CombinedFieldsQueryExec { &metrics, ) .await; + // Hold a tie group at the cutoff whole so it can be ordered by + // row id after translation; see `finalize_row_ids_and_scores`. + let search_params = + match widen_limit_for_tie_rerank(params.limit, row_addr_to_row_id.is_some()) { + widened if widened != params.limit => { + let mut widened_params = params.clone(); + widened_params.limit = widened; + widened_params + } + _ => params.clone(), + }; let (doc_ids, scores) = combined_fields_search( &columns, &tokens, - ¶ms, + &search_params, &query, scorer.as_ref(), pre_filter, metrics.as_ref(), ) .await?; - let (doc_ids, scores) = - translate_row_ids_and_scores(doc_ids, scores, row_addr_to_row_id.as_deref()); + let (doc_ids, scores) = finalize_row_ids_and_scores( + doc_ids, + scores, + row_addr_to_row_id.as_deref(), + params.limit, + ); metrics.baseline_metrics.record_output(doc_ids.len()); let batch = RecordBatch::try_new( diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index 1c6373b54eb..c293f883bab 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -63,8 +63,9 @@ use super::query_tokens::{ tokenize_cross_column_compound_query, tokenizer_for_match_query, }; use super::segments::{ - fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, - search_prepared_segments, segments_the_prefilter_may_match, translate_row_ids_and_scores, + finalize_row_ids_and_scores, fts_row_addr_to_row_id, fts_segments_are_address_domain, + open_fts_segments, search_prepared_segments, segments_the_prefilter_may_match, + widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -756,6 +757,18 @@ impl ExecutionPlan for HybridCompoundQueryExec { .await?; let address_domain = fts_segments_are_address_domain(&dataset, segments_to_open)?; let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, address_domain).await?; + // Hold a tie group at the cutoff whole so it survives to be ordered by + // row id after translation; see `finalize_row_ids_and_scores`. + let requested_limit = params.limit; + let params = + match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { + widened if widened != requested_limit => { + let mut widened_params = params.clone(); + widened_params.limit = widened; + widened_params + } + _ => params.clone(), + }; let first_index = indices.first().ok_or_else(|| { DataFusionError::Execution(format!( "FTS index for column {column} has no committed segments" @@ -842,10 +855,11 @@ impl ExecutionPlan for HybridCompoundQueryExec { ) .await .map_err(DataFusionError::from)?; - DataFusionResult::Ok(translate_row_ids_and_scores( + DataFusionResult::Ok(finalize_row_ids_and_scores( row_ids, scores, row_addr_to_row_id.as_deref(), + requested_limit, )) }; let residual_query = query.clone(); @@ -1172,6 +1186,18 @@ impl ExecutionPlan for CompoundQueryExec { let address_domain = fts_segments_are_address_domain(&dataset_for_scope, &segments)?; let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset_for_scope, address_domain).await?; + // Hold a tie group at the cutoff whole so it survives to be ordered by + // row id after translation; see `finalize_row_ids_and_scores`. + let requested_limit = params.limit; + let params = + match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { + widened if widened != requested_limit => { + let mut widened_params = params.clone(); + widened_params.limit = widened; + widened_params + } + _ => params.clone(), + }; if let Some(first_index) = indices.first() { let snapshot = tokenize_compound_query(&query, first_index.as_ref())?; tokenized_query.get_or_init(|| snapshot); @@ -1480,8 +1506,12 @@ impl ExecutionPlan for CompoundQueryExec { } } }; - let (row_ids, scores) = - translate_row_ids_and_scores(row_ids, scores, row_addr_to_row_id.as_deref()); + let (row_ids, scores) = finalize_row_ids_and_scores( + row_ids, + scores, + row_addr_to_row_id.as_deref(), + requested_limit, + ); metrics.baseline_metrics.record_output(row_ids.len()); Ok::<_, DataFusionError>(RecordBatch::try_new( FTS_SCHEMA.clone(), @@ -1841,6 +1871,18 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { })) .await?; let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset, address_domain).await?; + // Hold a tie group at the cutoff whole so it survives to be ordered by + // row id after translation; see `finalize_row_ids_and_scores`. + let requested_limit = params.limit; + let params = + match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { + widened if widened != requested_limit => { + let mut widened_params = params.clone(); + widened_params.limit = widened; + widened_params + } + _ => params.clone(), + }; let mut tokenizer_indices = HashMap::with_capacity(opened_columns.len()); let mut partition_counts = HashMap::with_capacity(opened_columns.len()); @@ -1903,8 +1945,12 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { metrics.clone(), ) .await?; - let (row_ids, scores) = - translate_row_ids_and_scores(row_ids, scores, row_addr_to_row_id.as_deref()); + let (row_ids, scores) = finalize_row_ids_and_scores( + row_ids, + scores, + row_addr_to_row_id.as_deref(), + requested_limit, + ); metrics.baseline_metrics.record_output(row_ids.len()); Ok::<_, DataFusionError>(RecordBatch::try_new( FTS_SCHEMA.clone(), diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index c8030b04fef..f6c3b8ca5e4 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -227,6 +227,70 @@ pub(super) async fn fts_row_addr_to_row_id( Ok(Some(Arc::new(lookup))) } +/// Extra candidates to retain past a query's own `limit` so that a tie +/// straddling the top-k cutoff survives long enough to be re-ranked on row id. +/// +/// Mirrors `WAND_TIE_COMPLETION_BUDGET`: it bounds how large a tie group can +/// be and still be resolved exactly, rather than promising to resolve one of +/// any size. +pub(super) const FTS_TIE_RERANK_BUDGET: usize = 128; + +/// The limit a search should actually run with, given the one the query asked +/// for. Widened only when results will be translated afterward, so a query +/// that needs no translation pays nothing. +pub(super) fn widen_limit_for_tie_rerank(limit: Option, translating: bool) -> Option { + match limit { + Some(limit) if translating => Some(limit.saturating_add(FTS_TIE_RERANK_BUDGET)), + other => other, + } +} + +/// Translate a final `(row_ids, scores)` pair out of the index's stored domain +/// and put it back into the order a caller sees, dropping unresolvable rows +/// and keeping the two vectors aligned. +/// +/// Selection ranks by `(score DESC, stored identifier ASC)` and cannot do +/// otherwise: `combined_maxscore` discovers candidates in ascending stored-id +/// order (`.min()` over the cursor heads), and its pruning is only sound +/// because a candidate that ties the threshold arrives after -- and so loses +/// to -- every incumbent. Once that stored identifier is a row address, the +/// order selection imposes among tied scores is physical, while the plan above +/// sorts by `(score DESC, _rowid ASC)`. Paging through a tie would then skip +/// and repeat rows, because each page's selection keeps the lowest *address* +/// while the sort reorders by *row id*. +/// +/// Re-ranking the survivors here settles it: with [`FTS_TIE_RERANK_BUDGET`] +/// extra candidates retained (see [`widen_limit_for_tie_rerank`]), a tie group +/// at the cutoff is held whole, translated, and ordered by row id before +/// `limit` is applied -- so the rows that survive are the ones the plan's own +/// ordering would have picked. Translating earlier, inside selection, is not +/// an option: it would key the heap on row ids while candidates still arrive +/// in address order, breaking the invariant the pruning rests on. +pub(super) fn finalize_row_ids_and_scores( + row_ids: Vec, + scores: Vec, + row_addr_to_row_id: Option<&RowAddrToRowId>, + limit: Option, +) -> (Vec, Vec) { + if row_addr_to_row_id.is_none() { + // Stored identifiers are already row ids, so selection ordered by the + // same key the plan sorts on and the limit was never widened. + return (row_ids, scores); + } + let (row_ids, scores) = translate_row_ids_and_scores(row_ids, scores, row_addr_to_row_id); + let mut ranked = row_ids.into_iter().zip(scores).collect::>(); + ranked.sort_by(|(left_row, left_score), (right_row, right_score)| { + right_score + .partial_cmp(left_score) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| left_row.cmp(right_row)) + }); + if let Some(limit) = limit { + ranked.truncate(limit); + } + ranked.into_iter().unzip() +} + /// Translate and drop unresolvable rows from a final `(row_ids, scores)` /// result pair, keeping the two aligned. A `None` translator is a no-op. pub(super) fn translate_row_ids_and_scores( From c73047f420a3f88481bf5a28a74f078dc0ae45f9 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 22:18:57 -0800 Subject: [PATCH 07/15] fix(fts): complete an over-large cutoff tie exactly before truncating A fixed re-rank margin is not enough on its own. With 131 identically scoring rows the tie at the top-k cutoff exceeds `FTS_TIE_RERANK_BUDGET`, so the retained candidates were still cut at an arbitrary address and the one-row pages returned `[1, 2, 2]` instead of `[0, 1, 2]`. Equal scores across many short documents are an ordinary FTS case, and retrying the same pages cannot recover the discarded row. `cutoff_tie_unresolved` now detects it: the search filled its widened cap *and* the score at the requested cutoff still equals the last score retained, so rows beyond the cap may tie the cutoff too and which of them belong in the top-k cannot be decided from what came back. The search is then completed exactly -- the same escape hatch the WAND tie certificate takes when its own completion budget is exhausted, which this previously lacked. Applied to combined fields, the hybrid compound path and the cross-column compound path, each of which issues one search that can simply be reissued. `CompoundQueryExec` cannot: the branch structure below it consumes its prefilter and candidate set, so it searches exhaustively when results will be translated and lets `finalize_row_ids_and_scores` apply the limit. Teaching the collectors to retain ties at the k-th score in one pass would remove both that and the other paths' second search; this keeps the fix inside the exec layer. Co-Authored-By: Claude Opus 5 --- .../tests/dataset_fts_combined_fields.rs | 76 +++++++++++++++++++ rust/lance/src/io/exec/fts/combined_fields.rs | 27 ++++++- rust/lance/src/io/exec/fts/compound.rs | 74 +++++++++++++----- rust/lance/src/io/exec/fts/segments.rs | 31 ++++++++ 4 files changed, 188 insertions(+), 20 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index d0d86b1f1b9..cb2ad944239 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -2922,6 +2922,82 @@ async fn test_fts_mixed_domain_within_one_index_is_rejected_at_commit() { ); } +/// The same pagination guarantee for a tie larger than the re-rank budget. +/// Equal scores across many short documents are an ordinary FTS case, so a +/// fixed margin is not enough on its own: 131 identical rows exceed it, and +/// truncating them at an arbitrary address made the one-row pages return +/// `[1, 2, 2]`. The cutoff tie has to be completed exactly instead. +#[rstest] +#[case::within_budget(8)] +#[case::exceeds_budget(131)] +#[tokio::test] +async fn test_fts_combined_fields_tied_pagination_completes_large_ties(#[case] rows: i32) { + let dir = TempStrDir::default(); + let ds = write_fts_dataset( + &dir, + combined_fields_batch( + (0..rows).collect(), + vec!["alpha"; rows as usize], + vec!["beta"; rows as usize], + ), + Some(WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + ) + .await; + // Moves row id 0's address behind every other row's, while its row id + // still sorts first. + let updated = crate::dataset::UpdateBuilder::new(Arc::new(ds)) + .update_where("id = 0") + .unwrap() + .set("title", "'alpha'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut ds = updated.new_dataset.as_ref().clone(); + create_inverted_indices(&mut ds, &["title", "body"], &combined_fields_test_params()).await; + let ds = append_fts_dataset( + &dir, + combined_fields_batch(vec![rows], vec!["alpha"], vec!["beta"]), + None, + ) + .await; + + let mut pages = Vec::new(); + for offset in 0..3 { + let batch = ds + .scan() + .project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query(combined_query( + "alpha beta", + Operator::And, + ))) + .unwrap() + .limit(Some(1), Some(offset)) + .unwrap() + .try_into_batch() + .await + .unwrap(); + pages.extend( + batch["id"] + .as_primitive::() + .values() + .iter() + .copied(), + ); + } + assert_eq!( + pages, + vec![0, 1, 2], + "one-row pages over a {rows}-row tie must walk every row once, in row-id order" + ); +} + /// Top-k selection ranks ties by the identifier the index stores, which is now /// a row address, while the plan above sorts by `_rowid`. An update moves a /// row's address without moving its row id, so the two orders disagree and diff --git a/rust/lance/src/io/exec/fts/combined_fields.rs b/rust/lance/src/io/exec/fts/combined_fields.rs index d6df7c98f38..17de13d16de 100644 --- a/rust/lance/src/io/exec/fts/combined_fields.rs +++ b/rust/lance/src/io/exec/fts/combined_fields.rs @@ -44,8 +44,9 @@ use tracing::instrument; use super::corpus::SharedFtsScorer; use super::query_tokens::{TokenizedQuery, fmt_tokenized_query, record_tokenized_query}; use super::segments::{ - combined_columns_the_prefilter_may_match, finalize_row_ids_and_scores, fts_row_addr_to_row_id, - fts_segments_are_address_domain, open_fts_segments, widen_limit_for_tie_rerank, + combined_columns_the_prefilter_may_match, cutoff_tie_unresolved, finalize_row_ids_and_scores, + fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, + widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -716,10 +717,30 @@ impl ExecutionPlan for CombinedFieldsQueryExec { &search_params, &query, scorer.as_ref(), - pre_filter, + pre_filter.clone(), metrics.as_ref(), ) .await?; + // A tie larger than the widened cap cannot be ordered from what + // came back, so complete it exactly rather than truncating it at an + // arbitrary address. + let (doc_ids, scores) = + if cutoff_tie_unresolved(&scores, params.limit, search_params.limit) { + let mut exact_params = params.clone(); + exact_params.limit = None; + combined_fields_search( + &columns, + &tokens, + &exact_params, + query.operator(), + scorer.as_ref(), + pre_filter, + metrics.as_ref(), + ) + .await? + } else { + (doc_ids, scores) + }; let (doc_ids, scores) = finalize_row_ids_and_scores( doc_ids, scores, diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index c293f883bab..813fcd81671 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -63,9 +63,9 @@ use super::query_tokens::{ tokenize_cross_column_compound_query, tokenizer_for_match_query, }; use super::segments::{ - finalize_row_ids_and_scores, fts_row_addr_to_row_id, fts_segments_are_address_domain, - open_fts_segments, search_prepared_segments, segments_the_prefilter_may_match, - widen_limit_for_tie_rerank, + cutoff_tie_unresolved, finalize_row_ids_and_scores, fts_row_addr_to_row_id, + fts_segments_are_address_domain, open_fts_segments, search_prepared_segments, + segments_the_prefilter_may_match, widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -849,12 +849,32 @@ impl ExecutionPlan for HybridCompoundQueryExec { &indices, &query, ¶ms, - prefilter, + prefilter.clone(), metrics.clone(), - committed_scorer, + committed_scorer.clone(), ) .await .map_err(DataFusionError::from)?; + // A tie larger than the widened cap cannot be ordered from what + // came back; complete it exactly instead of cutting it at an + // arbitrary address. + let (row_ids, scores) = + if cutoff_tie_unresolved(&scores, requested_limit, params.limit) { + let mut exact_params = params.clone(); + exact_params.limit = None; + compound_search_with_base_scorer( + &indices, + &query, + &exact_params, + prefilter, + metrics.clone(), + committed_scorer, + ) + .await + .map_err(DataFusionError::from)? + } else { + (row_ids, scores) + }; DataFusionResult::Ok(finalize_row_ids_and_scores( row_ids, scores, @@ -1186,18 +1206,23 @@ impl ExecutionPlan for CompoundQueryExec { let address_domain = fts_segments_are_address_domain(&dataset_for_scope, &segments)?; let row_addr_to_row_id = fts_row_addr_to_row_id(&dataset_for_scope, address_domain).await?; - // Hold a tie group at the cutoff whole so it survives to be ordered by - // row id after translation; see `finalize_row_ids_and_scores`. + // Candidates have to be ordered by row id after translation (see + // `finalize_row_ids_and_scores`), which needs any tie at the cutoff + // held whole. The siblings widen the limit and complete an + // over-large tie by re-running the search; this one cannot, because + // the branch structure below consumes its prefilter and candidate + // set, so it searches exhaustively and lets `finalize` apply the + // limit. Teaching the collectors to keep ties at the k-th score in + // one pass would remove both this and the siblings' second search. let requested_limit = params.limit; - let params = - match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { - widened if widened != requested_limit => { - let mut widened_params = params.clone(); - widened_params.limit = widened; - widened_params - } - _ => params.clone(), - }; + let params = match (requested_limit, row_addr_to_row_id.is_some()) { + (Some(_), true) => { + let mut exact_params = params.clone(); + exact_params.limit = None; + exact_params + } + _ => params.clone(), + }; if let Some(first_index) = indices.first() { let snapshot = tokenize_compound_query(&query, first_index.as_ref())?; tokenized_query.get_or_init(|| snapshot); @@ -1941,10 +1966,25 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { &search_columns, &query, ¶ms, - prefilter, + prefilter.clone(), metrics.clone(), ) .await?; + let (row_ids, scores) = if cutoff_tie_unresolved(&scores, requested_limit, params.limit) + { + let mut exact_params = params.clone(); + exact_params.limit = None; + cross_column_compound_search( + &search_columns, + &query, + &exact_params, + prefilter, + metrics.clone(), + ) + .await? + } else { + (row_ids, scores) + }; let (row_ids, scores) = finalize_row_ids_and_scores( row_ids, scores, diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index f6c3b8ca5e4..8bc81effadb 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -245,6 +245,37 @@ pub(super) fn widen_limit_for_tie_rerank(limit: Option, translating: bool } } +/// Whether a bounded search may have cut a tie group that straddles the top-k +/// cutoff, so its result cannot be re-ranked into the right order. +/// +/// True only when the search actually filled the widened cap *and* the score +/// at the requested cutoff still equals the last score retained: then rows +/// beyond the cap may tie the cutoff too, and which of them belong in the +/// top-k cannot be decided from what came back. The caller completes the tie +/// by re-running the search exactly, the same escape hatch the WAND tie +/// certificate takes when its own completion budget is exhausted -- +/// [`FTS_TIE_RERANK_BUDGET`] alone silently truncates a larger tie, and equal +/// scores across many short documents are an ordinary FTS case, not a corner +/// one. +pub(super) fn cutoff_tie_unresolved( + scores: &[f32], + requested_limit: Option, + searched_limit: Option, +) -> bool { + let (Some(requested), Some(searched)) = (requested_limit, searched_limit) else { + return false; + }; + if requested == 0 || scores.len() < searched || scores.len() <= requested { + // Nothing was cut: the search ran out of matches before its cap, or + // everything it found survives the requested limit anyway. + return false; + } + scores + .get(requested - 1) + .zip(scores.last()) + .is_some_and(|(cutoff, last)| cutoff == last) +} + /// Translate a final `(row_ids, scores)` pair out of the index's stored domain /// and put it back into the order a caller sees, dropping unresolvable rows /// and keeping the two vectors aligned. From ac8c53360091c9de66cf9589b911a3e79082ee28 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 23 Nov 2026 23:02:09 -0800 Subject: [PATCH 08/15] fix(fts): bound the cross-column tie replay and extend it to Match/Phrase Two gaps in the previous commit's exact-completion fallback. `cross_column_compound_search` rejects an unbounded limit outright ("cross-column compound FTS requires a bounded result limit"), so replaying with `limit: None` turned a large cutoff tie from a wrong answer into a failed query: a title/body MUST query with `limit=1` over 131 equal-scoring rows errored on its first page. The replay now bounds itself by `exhaustive_limit` -- every row the dataset physically stores, read from the manifest with no per-fragment I/O -- which no result set can exceed. A legacy fragment that does not record its row count falls back to no bound rather than to an undercount that would truncate the tie again. The other collectors take `params.limit.unwrap_or(usize::MAX)` and were unaffected. The Match and Phrase paths never widened their limit at all, so a bare Match over the same 131-row tie still paged `[1, 2, 2]`. They translate through `scored_documents_batch`, which dropped unresolvable rows but never restored `_rowid` order or applied a limit. It now re-ranks and truncates like `finalize_row_ids_and_scores`, and both paths widen, detect an unresolved cutoff tie, and complete it exactly -- `PreparedMatch` carries its own params, so the Match replay rebuilds it around an exact copy. Covered by `test_fts_large_tie_pagination_across_query_shapes`, which runs the cross-column, single-column-boolean and bare-Match shapes; the bare-Match case is what surfaced the second gap. Co-Authored-By: Claude Opus 5 --- .../tests/dataset_fts_combined_fields.rs | 81 ++++++++++++++ rust/lance/src/io/exec/fts/boolean.rs | 4 +- rust/lance/src/io/exec/fts/compound.rs | 10 +- rust/lance/src/io/exec/fts/match_query.rs | 71 +++++++++++- rust/lance/src/io/exec/fts/matches.rs | 18 +++ rust/lance/src/io/exec/fts/phrase.rs | 60 ++++++++-- rust/lance/src/io/exec/fts/segments.rs | 103 +++++++++++++++++- 7 files changed, 324 insertions(+), 23 deletions(-) diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index cb2ad944239..34bc653ad59 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -3072,3 +3072,84 @@ async fn test_fts_combined_fields_tied_pagination_follows_row_id_order() { .collect::>(); assert_eq!(all, vec![0, 1, 2]); } + +/// The same large-tie guarantee for the query shapes that do not go through +/// `combined_fields`: a cross-column MUST query, a single-column boolean, and +/// a bare Match. Each reaches a different collector, and `cross_column`'s +/// rejects an unbounded limit outright -- so completing its cutoff tie needs a +/// bound no result set can exceed rather than "no limit". +#[rstest] +#[case::cross_column_must(true, false)] +#[case::single_column_boolean(false, true)] +#[case::bare_match(false, false)] +#[tokio::test] +async fn test_fts_large_tie_pagination_across_query_shapes( + #[case] cross_column: bool, + #[case] single_boolean: bool, +) { + use lance_index::scalar::inverted::query::{BooleanQuery, Occur}; + let dir = TempStrDir::default(); + let ds = write_fts_dataset( + &dir, + combined_fields_batch((0..131).collect(), vec!["alpha"; 131], vec!["beta"; 131]), + Some(WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + ) + .await; + let updated = crate::dataset::UpdateBuilder::new(Arc::new(ds)) + .update_where("id = 0") + .unwrap() + .set("title", "'alpha'") + .unwrap() + .build() + .unwrap() + .execute() + .await + .unwrap(); + let mut ds = updated.new_dataset.as_ref().clone(); + create_inverted_indices(&mut ds, &["title", "body"], &combined_fields_test_params()).await; + + let mut pages = Vec::new(); + for offset in 0..3 { + let title: FtsQuery = MatchQuery::new("alpha".into()) + .with_column(Some("title".into())) + .into(); + let query: FtsQuery = if cross_column { + BooleanQuery::new([ + (Occur::Must, title), + ( + Occur::Must, + MatchQuery::new("beta".into()) + .with_column(Some("body".into())) + .into(), + ), + ]) + .into() + } else if single_boolean { + BooleanQuery::new([(Occur::Must, title.clone()), (Occur::Should, title)]).into() + } else { + title + }; + let batch = ds + .scan() + .project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query(query)) + .unwrap() + .limit(Some(1), Some(offset)) + .unwrap() + .try_into_batch() + .await + .unwrap(); + pages.extend( + batch["id"] + .as_primitive::() + .values() + .iter() + .copied(), + ); + } + assert_eq!(pages, vec![0, 1, 2]); +} diff --git a/rust/lance/src/io/exec/fts/boolean.rs b/rust/lance/src/io/exec/fts/boolean.rs index 73909fd039d..d3908700fe3 100644 --- a/rust/lance/src/io/exec/fts/boolean.rs +++ b/rust/lance/src/io/exec/fts/boolean.rs @@ -200,7 +200,7 @@ impl ExecutionPlan for BoostQueryExec { .collect::>(); metrics.baseline_metrics.record_output(documents.len()); - let batch = document_key_scores_batch(schema, documents, None)?; + let batch = document_key_scores_batch(schema, documents, None, None)?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( @@ -549,7 +549,7 @@ impl ExecutionPlan for BooleanQueryExec { .take(params.limit.unwrap_or(usize::MAX)) .collect::>(); metrics.baseline_metrics.record_output(documents.len()); - let batch = document_key_scores_batch(schema, documents, None)?; + let batch = document_key_scores_batch(schema, documents, None, None)?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index 813fcd81671..8665cb04762 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -63,7 +63,7 @@ use super::query_tokens::{ tokenize_cross_column_compound_query, tokenizer_for_match_query, }; use super::segments::{ - cutoff_tie_unresolved, finalize_row_ids_and_scores, fts_row_addr_to_row_id, + cutoff_tie_unresolved, exhaustive_limit, finalize_row_ids_and_scores, fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, search_prepared_segments, segments_the_prefilter_may_match, widen_limit_for_tie_rerank, }; @@ -786,7 +786,7 @@ impl ExecutionPlan for HybridCompoundQueryExec { let terms = residual_seed.exact_query_terms(&query)?; if terms.is_empty() { metrics.baseline_metrics.record_output(0); - return scored_documents_batch(schema, Vec::new(), None) + return scored_documents_batch(schema, Vec::new(), None, None) .map_err(DataFusionError::from); } let allowed_terms = Arc::new(terms.iter().cloned().collect::>()); @@ -914,7 +914,7 @@ impl ExecutionPlan for HybridCompoundQueryExec { }); documents.truncate(limit); metrics.baseline_metrics.record_output(documents.len()); - scored_documents_batch(schema, documents, None).map_err(DataFusionError::from) + scored_documents_batch(schema, documents, None, None).map_err(DataFusionError::from) }); Ok(Box::pin(RecordBatchStreamAdapter::new( self.schema(), @@ -1973,7 +1973,9 @@ impl ExecutionPlan for CrossColumnCompoundQueryExec { let (row_ids, scores) = if cutoff_tie_unresolved(&scores, requested_limit, params.limit) { let mut exact_params = params.clone(); - exact_params.limit = None; + // This collector rejects an unbounded limit, so bound the + // replay by every row the dataset holds instead. + exact_params.limit = Some(exhaustive_limit(&dataset)); cross_column_compound_search( &search_columns, &query, diff --git a/rust/lance/src/io/exec/fts/match_query.rs b/rust/lance/src/io/exec/fts/match_query.rs index 77735ea1172..e7d26c634da 100644 --- a/rust/lance/src/io/exec/fts/match_query.rs +++ b/rust/lance/src/io/exec/fts/match_query.rs @@ -39,8 +39,9 @@ use super::query_tokens::{ TokenizedQuery, fmt_tokenized_query, record_tokenized_query, tokenizer_for_match_query, }; use super::segments::{ - fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, - search_prepared_segments, segments_the_prefilter_may_match, + cutoff_may_be_tied, cutoff_tie_unresolved, fts_row_addr_to_row_id, + fts_segments_are_address_domain, open_fts_segments, search_prepared_segments, + segments_the_prefilter_may_match, widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -769,21 +770,81 @@ impl ExecutionPlan for MatchQueryExec { ) .await; let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, address_domain).await?; + // Selection ranks ties by stored row address, so any tie at the + // cutoff has to survive translation intact before `_rowid` order is + // restored; see `finalize_row_ids_and_scores`. + let requested_limit = prepared.params.limit; + let prepared = + match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { + widened if widened != requested_limit => { + let mut widened_params = prepared.params.as_ref().clone(); + widened_params.limit = widened; + Arc::new(PreparedMatch { + query: prepared.query.clone(), + params: Arc::new(widened_params), + operator: prepared.operator, + }) + } + _ => prepared, + }; let mut documents = search_prepared_segments( &indices, - prepared, - pre_filter, + prepared.clone(), + pre_filter.clone(), metrics.clone(), None, unordered_results, ) .await?; + // A tie larger than the widened cap cannot be ordered from what came + // back, so complete it exactly rather than cutting it at an + // arbitrary address. + // + // Gated on the count-only half of the test first: an unbounded + // search has no cutoff to tie at, and is also where the match set + // is largest, so it must not pay to materialize scores it cannot + // use. Inside the gate the scores are sorted rather than taken in + // search order, because `unordered_results` lets a leaf skip its + // final sort when nothing downstream needs the order, and + // `cutoff_tie_unresolved` reads them positionally. + // (`scored_documents_batch` sorts the surviving documents itself + // whenever it translates, which is exactly when this runs.) + if cutoff_may_be_tied(documents.len(), requested_limit, prepared.params.limit) { + let mut scores = documents + .iter() + .map(|document| document.score.0) + .collect::>(); + scores.sort_unstable_by(|left, right| right.total_cmp(left)); + if cutoff_tie_unresolved(&scores, requested_limit, prepared.params.limit) { + let mut exact_params = prepared.params.as_ref().clone(); + exact_params.limit = None; + let exact = Arc::new(PreparedMatch { + query: prepared.query.clone(), + params: Arc::new(exact_params), + operator: prepared.operator, + }); + documents = search_prepared_segments( + &indices, + exact, + pre_filter, + metrics.clone(), + None, + unordered_results, + ) + .await?; + } + } documents.iter_mut().for_each(|document| { document.score.0 *= query.boost; }); metrics.baseline_metrics.record_output(documents.len()); - let batch = scored_documents_batch(schema, documents, row_addr_to_row_id.as_deref())?; + let batch = scored_documents_batch( + schema, + documents, + row_addr_to_row_id.as_deref(), + requested_limit, + )?; Ok::<_, DataFusionError>(batch) }); diff --git a/rust/lance/src/io/exec/fts/matches.rs b/rust/lance/src/io/exec/fts/matches.rs index 98ad2e60ba3..cf8ce3b6167 100644 --- a/rust/lance/src/io/exec/fts/matches.rs +++ b/rust/lance/src/io/exec/fts/matches.rs @@ -53,6 +53,7 @@ pub(super) fn scored_documents_batch( schema: SchemaRef, mut documents: Vec, row_addr_to_row_id: Option<&RowAddrToRowId>, + limit: Option, ) -> Result { if let Some(translate) = row_addr_to_row_id { documents.retain_mut(|document| match translate(document.row_id) { @@ -62,6 +63,21 @@ pub(super) fn scored_documents_batch( } None => false, }); + // Selection ranked ties by stored row address; the plan above orders by + // `_rowid`. Restore that order before applying the caller's limit, or + // paging a tie skips and repeats rows -- see + // `finalize_row_ids_and_scores` for the full account. + documents.sort_by(|left, right| { + right + .score + .0 + .partial_cmp(&left.score.0) + .unwrap_or(std::cmp::Ordering::Equal) + .then_with(|| left.row_id.cmp(&right.row_id)) + }); + if let Some(limit) = limit { + documents.truncate(limit); + } } let row_ids = UInt64Array::from_iter_values(documents.iter().map(|document| document.row_id)); let scores = Float32Array::from_iter_values(documents.iter().map(|document| document.score.0)); @@ -163,6 +179,7 @@ pub(super) fn document_key_scores_batch( schema: SchemaRef, values: impl IntoIterator, row_addr_to_row_id: Option<&RowAddrToRowId>, + limit: Option, ) -> Result { scored_documents_batch( schema, @@ -171,6 +188,7 @@ pub(super) fn document_key_scores_batch( .map(|(key, score)| ScoredDoc::with_doc_index(key.row_id, key.doc_index, score)) .collect(), row_addr_to_row_id, + limit, ) } diff --git a/rust/lance/src/io/exec/fts/phrase.rs b/rust/lance/src/io/exec/fts/phrase.rs index 688e89cec63..31e425f908c 100644 --- a/rust/lance/src/io/exec/fts/phrase.rs +++ b/rust/lance/src/io/exec/fts/phrase.rs @@ -37,8 +37,9 @@ use super::corpus::SharedFtsScorer; use super::matches::scored_documents_batch; use super::query_tokens::{TokenizedQuery, fmt_tokenized_query, record_tokenized_query}; use super::segments::{ - fts_row_addr_to_row_id, fts_segments_are_address_domain, open_fts_segments, search_segments, - segments_the_prefilter_may_match, + cutoff_may_be_tied, cutoff_tie_unresolved, fts_row_addr_to_row_id, + fts_segments_are_address_domain, open_fts_segments, search_segments, + segments_the_prefilter_may_match, widen_limit_for_tie_rerank, }; use super::selection::{FtsIndexMetrics, FtsSegmentSelection}; @@ -608,19 +609,62 @@ impl ExecutionPlan for PhraseQueryExec { let tokens = Arc::new(tokens); let params = Arc::new(params); let row_addr_to_row_id = fts_row_addr_to_row_id(&ds_for_scope, address_domain).await?; - let documents = search_segments( + // Selection ranks ties by stored row address, so any tie at the + // cutoff has to survive translation intact before `_rowid` order is + // restored; see `finalize_row_ids_and_scores`. + let requested_limit = params.limit; + let params = + match widen_limit_for_tie_rerank(requested_limit, row_addr_to_row_id.is_some()) { + widened if widened != requested_limit => { + let mut widened_params = params.as_ref().clone(); + widened_params.limit = widened; + Arc::new(widened_params) + } + _ => params, + }; + let mut documents = search_segments( &indices, - tokens, - params, + tokens.clone(), + params.clone(), lance_index::scalar::inverted::query::Operator::And, - pre_filter, + pre_filter.clone(), metrics.clone(), - base_scorer, + base_scorer.clone(), None, ) .await?; + // A tie larger than the widened cap cannot be ordered from what came + // back, so complete it exactly. Gated on the count-only half of the + // test so an unbounded search, which has no cutoff to tie at and + // the largest match set, does not materialize scores for nothing. + if cutoff_may_be_tied(documents.len(), requested_limit, params.limit) { + let scores = documents + .iter() + .map(|document| document.score.0) + .collect::>(); + if cutoff_tie_unresolved(&scores, requested_limit, params.limit) { + let mut exact_params = params.as_ref().clone(); + exact_params.limit = None; + documents = search_segments( + &indices, + tokens, + Arc::new(exact_params), + lance_index::scalar::inverted::query::Operator::And, + pre_filter, + metrics.clone(), + base_scorer, + None, + ) + .await?; + } + } metrics.baseline_metrics.record_output(documents.len()); - let batch = scored_documents_batch(schema, documents, row_addr_to_row_id.as_deref())?; + let batch = scored_documents_batch( + schema, + documents, + row_addr_to_row_id.as_deref(), + requested_limit, + )?; Ok::<_, DataFusionError>(batch) }); Ok(Box::pin(RecordBatchStreamAdapter::new( diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index 8bc81effadb..a7260c9761e 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -245,6 +245,28 @@ pub(super) fn widen_limit_for_tie_rerank(limit: Option, translating: bool } } +/// Whether a search could have cut a tie at all, decided from counts alone. +/// +/// The cheap half of [`cutoff_tie_unresolved`]'s preconditions, split out so a +/// caller can skip materializing the scores when the answer is already no -- +/// which is every unbounded search, where the match set is also at its +/// largest. `cutoff_tie_unresolved` calls it too, so the two cannot drift +/// apart. +/// +/// False when the search was unbounded (no cutoff exists), asked for nothing, +/// ran out of matches before reaching its cap (nothing was cut), or returned +/// no more than the requested limit (everything it found survives anyway). +pub(super) fn cutoff_may_be_tied( + count: usize, + requested_limit: Option, + searched_limit: Option, +) -> bool { + let (Some(requested), Some(searched)) = (requested_limit, searched_limit) else { + return false; + }; + requested > 0 && count >= searched && count > requested +} + /// Whether a bounded search may have cut a tie group that straddles the top-k /// cutoff, so its result cannot be re-ranked into the right order. /// @@ -262,12 +284,10 @@ pub(super) fn cutoff_tie_unresolved( requested_limit: Option, searched_limit: Option, ) -> bool { - let (Some(requested), Some(searched)) = (requested_limit, searched_limit) else { + let Some(requested) = requested_limit else { return false; }; - if requested == 0 || scores.len() < searched || scores.len() <= requested { - // Nothing was cut: the search ran out of matches before its cap, or - // everything it found survives the requested limit anyway. + if !cutoff_may_be_tied(scores.len(), requested_limit, searched_limit) { return false; } scores @@ -276,6 +296,28 @@ pub(super) fn cutoff_tie_unresolved( .is_some_and(|(cutoff, last)| cutoff == last) } +/// An upper bound on how many rows any query over `dataset` could match: +/// every row it physically stores. +/// +/// Completing a cutoff tie needs a search that sees every match, but not every +/// collector accepts an unbounded limit -- `cross_column_compound_search` +/// rejects `None` outright -- so the replay passes a bound no result set can +/// exceed instead. Read from the manifest, with no per-fragment I/O; a legacy +/// fragment that does not record its row count falls back to no bound at all +/// rather than to an undercount that would silently truncate the tie again. +pub(super) fn exhaustive_limit(dataset: &Dataset) -> usize { + let mut total: usize = 0; + for fragment in dataset.manifest.fragments.iter() { + let Some(physical_rows) = fragment.physical_rows else { + return usize::MAX; + }; + total = total.saturating_add(physical_rows); + } + // A zero limit means "no results"; a dataset with no rows has none to + // return anyway, and the collectors reject 0. + total.max(1) +} + /// Translate a final `(row_ids, scores)` pair out of the index's stored domain /// and put it back into the order a caller sees, dropping unresolvable rows /// and keeping the two vectors aligned. @@ -587,6 +629,59 @@ pub(super) async fn search_segments( #[cfg(test)] mod tests { + /// The cheap gate never hides a tie the full check would have found: for + /// every shape of (count, requested, searched), `cutoff_tie_unresolved` + /// implies `cutoff_may_be_tied`. Callers skip materializing scores on the + /// strength of that, so a drift between the two would silently stop + /// completing ties. + #[test] + fn test_cutoff_may_be_tied_admits_everything_the_full_check_resolves() { + let mut resolved_any = false; + for count in 0..6usize { + // All-equal scores, the case most likely to be reported as a tie. + let scores = vec![1.0f32; count]; + for requested in [None, Some(0), Some(1), Some(2), Some(5)] { + for searched in [None, Some(0), Some(1), Some(2), Some(5)] { + let unresolved = super::cutoff_tie_unresolved(&scores, requested, searched); + let may = super::cutoff_may_be_tied(count, requested, searched); + assert!( + !unresolved || may, + "count={count} requested={requested:?} searched={searched:?}: \ + the full check resolved a tie the gate would have skipped" + ); + resolved_any |= unresolved; + } + } + } + assert!( + resolved_any, + "no case reported a tie, so the implication above held vacuously" + ); + } + + /// The gate is what keeps an unbounded search from paying for scores it + /// cannot use -- it has no cutoff to tie at, and is the case with the + /// largest match set. + #[test] + fn test_cutoff_may_be_tied_is_false_without_a_bound() { + assert!(!super::cutoff_may_be_tied(10_000, None, None)); + assert!(!super::cutoff_may_be_tied(10_000, None, Some(4))); + assert!(!super::cutoff_may_be_tied(10_000, Some(4), None)); + assert!(super::cutoff_may_be_tied(10, Some(2), Some(4))); + } + + /// `cutoff_tie_unresolved` reads its scores positionally, so a caller has + /// to hand them over in rank order. The same page of the same tie answers + /// the opposite way unordered, which would cut a tie at an arbitrary + /// address instead of completing it -- see the sort in `MatchQueryExec`. + #[test] + fn test_cutoff_tie_unresolved_reads_scores_positionally() { + let ranked = [2.0, 1.0, 1.0, 1.0]; + assert!(super::cutoff_tie_unresolved(&ranked, Some(2), Some(4))); + let unordered = [1.0, 1.0, 1.0, 2.0]; + assert!(!super::cutoff_tie_unresolved(&unordered, Some(2), Some(4))); + } + use super::*; use lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION; From d1fc4154fa355af5ad21b0ce4e91bebdab60329a Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Tue, 24 Nov 2026 07:20:12 -0800 Subject: [PATCH 09/15] feat(index)!: name the FTS document identity column for its domain Addresses the review's point that `docs.lance._rowid` holding row addresses is easy for another implementation to misread, and that with no reader implementing version 4 yet this is the last cheap moment to pick the name. From `INVERTED_ROW_ADDR_DOMAIN_VERSION` the column is `_rowaddr`; versions 1 through 3 keep `_rowid`. The name now tracks `index_version`, which is worth more than the tidiness: a reader that ignores the version finds no such column instead of silently reading one domain's values as the other's, turning the exact foot-gun behind three of this PR's bugs into a loud failure. The constraint that made this more than a rename is that `build_scalar_index` relabels a fresh build down to a legacy version on a dataset without stable row ids, so an older reader can still read it -- and that reader looks for `_rowid`. The name therefore has to be chosen before the file is written, from the version the segment will end up committed with. `TrainingRequest` grows a defaulted `set_stable_row_ids` hook so only FTS has to care; `build_scalar_index` calls it, and the name is threaded to `DocSet::to_batch`. Rewrites keep their source segment's version, so they keep its column: a loaded `DocSet` records the name it read, `into_builder` inherits it, and `to_builder` sets it from the opened index -- so no merge, remap or consolidation path has to remember. MemWAL FTS commits legacy versions and keeps `_rowid` unchanged. Readers resolve the name from the file's own schema rather than the index version (`docs_identity_column`), so one reader serves both and an existing version-4 fixture written before this change still opens. `test_fts_docs_identity_column_matches_index_version` asserts the column actually written, for both domains and across a merge. That assertion is what makes the threading verifiable: with schema-driven reading, a build path that was never told which name to write would otherwise still work and quietly violate the spec -- it caught two such paths (append/consolidation and partition-derived builders) that reading alone did not. Co-Authored-By: Claude Opus 5 --- docs/src/format/index/scalar/fts.md | 4 +- rust/lance-index/src/scalar/inverted.rs | 53 ++++++- .../src/scalar/inverted/builder.rs | 63 +++++++- .../src/scalar/inverted/builder/pipeline.rs | 1 + .../src/scalar/inverted/documents.rs | 64 ++++++-- .../src/scalar/inverted/index/doc_set.rs | 34 ++++- .../scalar/inverted/index/inverted_index.rs | 24 +++ .../src/scalar/inverted/index/partition.rs | 4 + .../scalar/inverted/index/tests/scoring.rs | 2 +- rust/lance-index/src/scalar/registry.rs | 13 ++ .../tests/dataset_fts_combined_fields.rs | 144 ++++++++++++++++++ rust/lance/src/index/scalar.rs | 7 +- 12 files changed, 386 insertions(+), 27 deletions(-) diff --git a/docs/src/format/index/scalar/fts.md b/docs/src/format/index/scalar/fts.md index f3399a2008c..068daf550a6 100644 --- a/docs/src/format/index/scalar/fts.md +++ b/docs/src/format/index/scalar/fts.md @@ -20,7 +20,7 @@ The FTS index consists of multiple files storing the token dictionary, document An FTS index may contain multiple partitions. Each partition has its own set of token, document, and posting list files, prefixed with the partition ID (e.g. `part_0_tokens.lance`, `part_0_docs.lance`, `part_0_invert.lance`). The `metadata.lance` file lists all partition IDs in the index. At query time, every partition must be searched and the results combined to produce the final ranked output. Fewer partitions generally means better query performance, since each partition requires its own token dictionary lookup and posting list scan. The number of partitions is controlled by the training configuration -- specifically `LANCE_FTS_TARGET_SIZE` determines how large each merged partition can grow (see [Training Process](#training-process) for details). -From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, `docs.lance._rowid` holds the document's physical row address (`fragment_id << 32 | offset`). In versions 1 through 3 it holds the dataset's row id. Readers must interpret `_rowid` according to the segment's `index_version`. Writers may label a segment with version 1 through 3 only on a dataset without stable row ids, where row ids and row addresses are equal. A reader that supports version 4 must also support every capability of version 3. The posting-list format is recorded separately and must not be inferred from `index_version`. +From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, each document's identity is stored in `docs.lance._rowaddr` and holds the document's physical row address (`fragment_id << 32 | offset`). In versions 1 through 3 it is stored in `docs.lance._rowid` and holds the dataset's row id. The column name therefore tracks `index_version`: a reader must select the column for the segment's version, and a reader that looks for the wrong one finds no such column rather than silently reading one domain's values as the other's. Writers may label a segment with version 1 through 3 only on a dataset without stable row ids, where row ids and row addresses are equal, and must then name the column `_rowid` so that a reader supporting only those versions can still read it. A reader that supports version 4 must also support every capability of version 3. The posting-list format is recorded separately and must not be inferred from `index_version`. ### Token Dictionary File Schema @@ -33,7 +33,7 @@ From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, `docs.lance._ | Column | Type | Nullable | Description | |---------------|--------|----------|----------------------------------| -| `_rowid` | UInt64 | false | Document row ID (format version <= 3) or row address (format version >= 4); see above | +| `_rowid` / `_rowaddr` | UInt64 | false | Document row ID, named `_rowid` (format version <= 3), or row address, named `_rowaddr` (format version >= 4); see above | | `_num_tokens` | UInt32 | false | Number of tokens in the document | Partitioned `docs.lance` files may include the optional schema metadata key diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index 7c9ab5213c5..d587fafdc06 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -50,7 +50,7 @@ pub use cross_column::cross_column_compound_search; use datafusion_execution::SendableRecordBatchStream; use documents::DocumentRemapping; pub use index::*; -use lance_core::{Result, cache::LanceCache}; +use lance_core::{ROW_ADDR, ROW_ID, Result, cache::LanceCache}; pub use lance_tokenizer::Language; pub use scorer::{CombinedFieldsBM25Scorer, MemBM25Scorer, Scorer}; pub use tokenizer::*; @@ -493,12 +493,40 @@ use super::IndexStore; pub struct InvertedIndexPlugin; impl InvertedIndexPlugin { + /// Train a segment that writes its document identities under the legacy + /// [`ROW_ID`] column. Callers that know the segment will keep + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] should use + /// [`Self::train_inverted_index_in_domain`] with [`ROW_ADDR`] instead. pub async fn train_inverted_index( data: SendableRecordBatchStream, index_store: &dyn IndexStore, params: InvertedIndexParams, fragment_ids: Option>, progress: Arc, + ) -> Result { + Self::train_inverted_index_in_domain( + data, + index_store, + params, + fragment_ids, + progress, + ROW_ID, + ) + .await + } + + /// Like [`Self::train_inverted_index`], naming the document identity + /// column explicitly. The name must match the `index_version` the + /// finished segment is committed with: [`ROW_ADDR`] for + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`], [`ROW_ID`] for a segment + /// relabelled to a legacy version. + pub async fn train_inverted_index_in_domain( + data: SendableRecordBatchStream, + index_store: &dyn IndexStore, + params: InvertedIndexParams, + fragment_ids: Option>, + progress: Arc, + identity_column: &'static str, ) -> Result { let fragment_mask = fragment_ids.as_ref().and_then(|frag_ids| { if !frag_ids.is_empty() { @@ -515,7 +543,8 @@ impl InvertedIndexPlugin { let details = pbold::InvertedIndexDetails::try_from(¶ms)?; let mut inverted_index = InvertedIndexBuilder::new_with_fragment_mask(params, fragment_mask) - .with_progress(progress); + .with_progress(progress) + .with_identity_column(identity_column); let files = inverted_index.update(data, index_store, None).await?; Ok(CreatedIndex { index_details: prost_types::Any::from_msg(&details).unwrap(), @@ -577,18 +606,35 @@ impl InvertedIndexPlugin { struct InvertedIndexTrainingRequest { parameters: InvertedIndexParams, criteria: TrainingCriteria, + /// The column the trained segment writes document identities under. The + /// caller sets [`ROW_ADDR`] when the segment will keep + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]; it stays [`ROW_ID`] when the + /// segment will be relabelled to a legacy version, where an old reader + /// expects that name and the two domains coincide anyway. + identity_column: &'static str, } impl InvertedIndexTrainingRequest { pub fn new(parameters: InvertedIndexParams) -> Self { Self { parameters, + identity_column: ROW_ID, criteria: TrainingCriteria::new(TrainingOrdering::None).with_row_addr(), } } } impl TrainingRequest for InvertedIndexTrainingRequest { + fn set_stable_row_ids(&mut self, stable_row_ids: bool) { + // Without stable row ids `build_scalar_index` relabels the finished + // segment to a pre-`INVERTED_ROW_ADDR_DOMAIN_VERSION` version so an + // older reader still understands it -- and that reader looks for + // `ROW_ID`. The two domains coincide there, so the legacy name is + // truthful. With stable row ids the segment keeps version 4 and names + // the column for what it actually holds. + self.identity_column = if stable_row_ids { ROW_ADDR } else { ROW_ID }; + } + fn as_any(&self) -> &dyn std::any::Any { self } @@ -649,12 +695,13 @@ impl BasicTrainer for InvertedIndexPlugin { "must provide training request created by new_training_request".into(), ) })?; - Self::train_inverted_index( + Self::train_inverted_index_in_domain( data, index_store, request.parameters.clone(), fragment_ids, progress, + request.identity_column, ) .await } diff --git a/rust/lance-index/src/scalar/inverted/builder.rs b/rust/lance-index/src/scalar/inverted/builder.rs index d32c8a0139a..d012db18d61 100644 --- a/rust/lance-index/src/scalar/inverted/builder.rs +++ b/rust/lance-index/src/scalar/inverted/builder.rs @@ -225,6 +225,11 @@ pub struct InvertedIndexBuilder { src_store: Option>, progress: Arc, deleted_fragments: RoaringBitmap, + /// The column documents' identities are written under. Defaults to the + /// legacy `ROW_ID`; a build committed as + /// `INVERTED_ROW_ADDR_DOMAIN_VERSION` sets `ROW_ADDR` via + /// [`Self::with_identity_column`]. + identity_column: &'static str, } impl InvertedIndexBuilder { @@ -270,9 +275,23 @@ impl InvertedIndexBuilder { posting_tail_codec: format_version.posting_tail_codec(), progress: noop_progress(), deleted_fragments, + identity_column: ROW_ID, } } + /// Write documents' identities under `identity_column`. Must agree with + /// the `index_version` the finished segment is committed with: from + /// `INVERTED_ROW_ADDR_DOMAIN_VERSION` that is [`ROW_ADDR`], and a build + /// relabelled down to a legacy version keeps [`ROW_ID`]. + pub fn with_identity_column(mut self, identity_column: &'static str) -> Self { + self.identity_column = identity_column; + self + } + + pub(crate) fn identity_column(&self) -> &'static str { + self.identity_column + } + pub fn with_posting_tail_codec(mut self, posting_tail_codec: PostingTailCodec) -> Self { self.format_version = InvertedListFormatVersion::from_posting_tail_codec_and_block_size( posting_tail_codec, @@ -553,6 +572,7 @@ impl InvertedIndexBuilder { worker_memory_limit_bytes, block_size: self.params.block_size, coordinate_rank: document_coordinate_rank(&stream.schema()), + identity_column: self.identity_column, }; let id_alloc = self.partition_id_allocator(); let tokenized_count = Arc::new(AtomicU64::new(0)); @@ -1169,6 +1189,11 @@ pub struct InnerBuilder { pub(super) tokens: TokenDictionary, pub(crate) posting_lists: Vec, pub(crate) docs: DocSet, + /// The column the documents' identities are written under. Defaults to + /// the legacy [`ROW_ID`]; a build that will be labelled + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`](super::INVERTED_ROW_ADDR_DOMAIN_VERSION) + /// sets [`ROW_ADDR`] through [`Self::with_identity_column`]. + identity_column: &'static str, } impl InnerBuilder { @@ -1232,9 +1257,18 @@ impl InnerBuilder { tokens: TokenDictionary::default(), posting_lists: Vec::new(), docs: DocSet::default(), + identity_column: ROW_ID, } } + /// Write the documents' identities under `identity_column` (see + /// [`DocSet::to_batch`]). Must agree with the `index_version` the finished + /// segment is committed with. + pub fn with_identity_column(mut self, identity_column: &'static str) -> Self { + self.identity_column = identity_column; + self + } + pub fn new_with_posting_tail_codec( id: u64, with_position: bool, @@ -1383,8 +1417,20 @@ impl InnerBuilder { tokens, posting_lists, docs, + identity_column, } = other; + // A merged partition writes one schema, so the name is taken from + // whichever side actually came from a persisted segment: a freshly + // built partition still carries the default until the build is told + // which to use, and consolidation merges those into partitions loaded + // from files. `write_docs` uses the accumulating builder's name, so + // adopting a non-default incoming one keeps a rewrite on the name its + // source was read under. + if identity_column != ROW_ID { + self.identity_column = identity_column; + } + if self.with_position != with_position { return Err(Error::index(format!( "cannot merge partitions with mismatched positions settings: {} vs {}", @@ -1644,7 +1690,7 @@ impl InnerBuilder { path: &str, ) -> Result { log::info!("writing docs of partition {}", self.id); - let batch = docs.to_batch()?; + let batch = docs.to_batch(self.identity_column)?; let mut writer = store.new_index_file(path, batch.schema()).await?; writer.write_record_batch(batch).await?; writer @@ -1684,6 +1730,7 @@ impl PartitionWriteTarget { } struct IndexWorker { + identity_column: &'static str, tokenizer: Box, dest_store: Arc, id_alloc: Arc, @@ -1727,6 +1774,7 @@ struct IndexWorkerConfig { worker_memory_limit_bytes: u64, block_size: usize, coordinate_rank: usize, + identity_column: &'static str, } impl IndexWorker { @@ -1783,10 +1831,12 @@ impl IndexWorker { config.token_set_format, config.format_version, config.block_size, - ); + ) + .with_identity_column(config.identity_column); builder.docs = DocSet::with_coordinate_rank(config.coordinate_rank); Ok(Self { + identity_column: config.identity_column, tokenizer, dest_store, builder, @@ -2192,7 +2242,8 @@ impl IndexWorker { self.token_set_format, format_version, block_size, - ); + ) + .with_identity_column(self.identity_column); replacement.docs = DocSet::with_coordinate_rank(self.coordinate_rank); let builder = std::mem::replace(&mut self.builder, replacement); if let Some(sender) = &self.run_sender { @@ -4840,6 +4891,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: params.block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; @@ -4865,6 +4917,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: params.block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; @@ -5266,6 +5319,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: InvertedIndexParams::default().block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; @@ -5663,6 +5717,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: InvertedIndexParams::default().block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; @@ -5696,6 +5751,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: InvertedIndexParams::default().block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; @@ -5736,6 +5792,7 @@ mod tests { worker_memory_limit_bytes: u64::MAX, block_size: InvertedIndexParams::default().block_size, coordinate_rank: 0, + identity_column: ROW_ID, }, ) .await?; diff --git a/rust/lance-index/src/scalar/inverted/builder/pipeline.rs b/rust/lance-index/src/scalar/inverted/builder/pipeline.rs index fa739265eef..b0d69595bb8 100644 --- a/rust/lance-index/src/scalar/inverted/builder/pipeline.rs +++ b/rust/lance-index/src/scalar/inverted/builder/pipeline.rs @@ -115,6 +115,7 @@ pub(super) async fn build( worker_memory_limit_bytes: config.run_memory_limit_bytes, block_size: builder.params.block_size, coordinate_rank: document_coordinate_rank(&stream.schema()), + identity_column: builder.identity_column(), }; let ids = builder.partition_id_allocator(); let tokenized = Arc::new(AtomicU64::new(0)); diff --git a/rust/lance-index/src/scalar/inverted/documents.rs b/rust/lance-index/src/scalar/inverted/documents.rs index 0990c878daf..0327e7635c6 100644 --- a/rust/lance-index/src/scalar/inverted/documents.rs +++ b/rust/lance-index/src/scalar/inverted/documents.rs @@ -20,7 +20,7 @@ use lance_core::cache::{CacheKey, CacheLoadOrigin, WeakLanceCache}; use lance_core::deepsize::DeepSizeOf; use lance_core::utils::address::RowAddress; use lance_core::utils::tokio::spawn_cpu; -use lance_core::{Error, ROW_ID, Result}; +use lance_core::{Error, ROW_ADDR, ROW_ID, Result}; use lance_select::{RowAddrMask, RowAddrSelection, RowAddrTreeMap}; use object_store::path::Path; use roaring::RoaringBitmap; @@ -34,6 +34,48 @@ use super::index::{ document_coordinate_rank, quantize_doc_length, }; +/// [`docs_identity_column`] for an opened docs file, whose schema is a Lance +/// schema rather than an Arrow one. +pub fn docs_identity_column_of( + reader: &dyn lance_index_core::scalar::IndexReader, +) -> Result<&'static str> { + if reader.schema().field(ROW_ADDR).is_some() { + Ok(ROW_ADDR) + } else if reader.schema().field(ROW_ID).is_some() { + Ok(ROW_ID) + } else { + Err(Error::invalid_input(format!( + "docs file has neither a {ROW_ADDR} nor a {ROW_ID} column; it cannot identify its \ + documents" + ))) + } +} + +/// The column holding each document's identity in a `docs.lance` file. +/// +/// From [`INVERTED_ROW_ADDR_DOMAIN_VERSION`](super::INVERTED_ROW_ADDR_DOMAIN_VERSION) +/// a segment stores physical row addresses and names the column [`ROW_ADDR`]; +/// a segment persisted before it stores row ids in [`ROW_ID`]. +/// +/// Resolved from the file's own schema rather than from the index version, so +/// one reader serves both without threading the version to every read site. +/// The names are what makes the two distinguishable at all: the values are +/// `u64` either way, so a file whose column disagrees with its declared +/// version fails here on a missing column instead of silently reinterpreting +/// addresses as ids. +pub fn docs_identity_column(schema: &arrow_schema::Schema) -> Result<&'static str> { + if schema.column_with_name(ROW_ADDR).is_some() { + Ok(ROW_ADDR) + } else if schema.column_with_name(ROW_ID).is_some() { + Ok(ROW_ID) + } else { + Err(Error::invalid_input(format!( + "docs file has neither a {ROW_ADDR} nor a {ROW_ID} column; it cannot identify its \ + documents" + ))) + } +} + /// Schema metadata key persisted in every modern `docs.lance` partition. pub(super) const TOTAL_TOKENS_KEY: &str = "total_tokens"; @@ -1693,8 +1735,9 @@ impl PartitionDocuments { }, || async move { let reader = store.open_index_file(&path).await?; - let batch = reader.read_range(0..num_docs, Some(&[ROW_ID])).await?; - let row_ids = required_u64_column(&batch, ROW_ID, &path)?; + let identity = docs_identity_column_of(reader.as_ref())?; + let batch = reader.read_range(0..num_docs, Some(&[identity])).await?; + let row_ids = required_u64_column(&batch, identity, &path)?; if row_ids.null_count() != 0 { return Err(corrupt_docs( &path, @@ -1988,12 +2031,12 @@ impl PartitionDocuments { index..index + 1 }) .collect::>(); - let batch = self - .reader() - .await? - .read_ranges(&ranges, Some(&[ROW_ID, NUM_TOKEN_COL])) + let reader = self.reader().await?; + let identity = docs_identity_column_of(reader.as_ref())?; + let batch = reader + .read_ranges(&ranges, Some(&[identity, NUM_TOKEN_COL])) .await?; - let row_ids = required_u64_column(&batch, ROW_ID, &self.path)?; + let row_ids = required_u64_column(&batch, identity, &self.path)?; let lengths = required_u32_column(&batch, NUM_TOKEN_COL, &self.path)?; if row_ids.null_count() != 0 || lengths.null_count() != 0 @@ -2231,12 +2274,13 @@ impl PartitionDocuments { .get_or_try_init(|| async { if self.lengths.get().is_none() && self.projection.get().is_none() { let reader = self.reader().await?; + let identity = docs_identity_column_of(reader.as_ref())?; let batch = reader - .read_range(0..self.num_docs, Some(&[ROW_ID, NUM_TOKEN_COL])) + .read_range(0..self.num_docs, Some(&[identity, NUM_TOKEN_COL])) .await?; let lengths = self.lengths_from_batch(&batch)?; let row_ids = - Arc::new(required_u64_column(&batch, ROW_ID, &self.path)?.clone()); + Arc::new(required_u64_column(&batch, identity, &self.path)?.clone()); if row_ids.null_count() != 0 { return Err(corrupt_docs( &self.path, diff --git a/rust/lance-index/src/scalar/inverted/index/doc_set.rs b/rust/lance-index/src/scalar/inverted/index/doc_set.rs index a278c3c7276..53a4ea48c41 100644 --- a/rust/lance-index/src/scalar/inverted/index/doc_set.rs +++ b/rust/lance-index/src/scalar/inverted/index/doc_set.rs @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors use super::*; +use crate::scalar::inverted::documents::docs_identity_column; #[derive(Debug, Clone, DeepSizeOf, Copy)] pub enum DocInfo { @@ -240,6 +241,10 @@ pub struct DocSet { // Memoized answer to `row_ids_strictly_ascending`. Filled on first query use; // build-time appends happen before any query touches it. row_ids_ascending: Arc>, + /// The column this set's identities were read from, carried so a builder + /// derived from it rewrites them under the same name. A set built from + /// scratch keeps the legacy default until the build is told otherwise. + pub(super) identity_column: &'static str, } impl DeepSizeOf for DocSet { @@ -448,12 +453,19 @@ impl DocSet { block_max_scores } - pub fn to_batch(&self) -> Result { + /// `identity_column` names the column the documents' identities are + /// written under: [`ROW_ADDR`](lance_core::ROW_ADDR) from + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`](crate::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION) + /// onward, [`ROW_ID`](lance_core::ROW_ID) for a segment written to be read + /// as a legacy one. + /// The name has to match the version the segment will be labelled with -- + /// see `docs_identity_column`. + pub fn to_batch(&self, identity_column: &str) -> Result { let row_id_col = UInt64Array::from_iter_values(self.row_ids.iter().cloned()); let num_tokens_col = UInt32Array::from_iter_values(self.num_tokens.iter().cloned()); let mut fields = vec![ - arrow_schema::Field::new(ROW_ID, DataType::UInt64, false), + arrow_schema::Field::new(identity_column, DataType::UInt64, false), arrow_schema::Field::new(NUM_TOKEN_COL, DataType::UInt32, false), ]; let mut columns = vec![ @@ -482,7 +494,8 @@ impl DocSet { frag_reuse_index: Option>, ) -> Result { let batch = reader.read_range(0..reader.num_rows(), None).await?; - let row_id_col = batch[ROW_ID].as_primitive::(); + let identity = docs_identity_column(batch.schema_ref())?; + let row_id_col = batch[identity].as_primitive::(); let num_tokens_col = batch[NUM_TOKEN_COL].as_primitive::(); let mut doc_indices = Vec::new(); for rank in 0.. { @@ -492,13 +505,15 @@ impl DocSet { }; doc_indices.push(column.as_primitive::()); } - Self::from_columns_with_doc_indices( + let mut docs = Self::from_columns_with_doc_indices( row_id_col, num_tokens_col, &doc_indices, is_legacy, frag_reuse_index, - ) + )?; + docs.identity_column = identity; + Ok(docs) } /// Additive sibling of [`Self::load`] for mappings that require @@ -510,9 +525,10 @@ impl DocSet { ) -> Result { lance_index_core::remapping::check_batch_remapping_entry()?; let batch = reader.read_range(0..reader.num_rows(), None).await?; + let identity = docs_identity_column(batch.schema_ref())?; let (batch, frag_reuse_index) = match remapping { Some(remapping) => { - let row_id_idx = batch.schema().index_of(ROW_ID)?; + let row_id_idx = batch.schema().index_of(identity)?; let (batch, remapper) = remap_row_ids_preserving_layout_async(remapping.as_ref(), batch, row_id_idx) .await?; @@ -520,7 +536,7 @@ impl DocSet { } None => (batch, None), }; - let row_id_col = batch[ROW_ID].as_primitive::(); + let row_id_col = batch[identity].as_primitive::(); let num_tokens_col = batch[NUM_TOKEN_COL].as_primitive::(); let mut doc_indices = Vec::new(); for rank in 0.. { @@ -565,6 +581,7 @@ impl DocSet { scoring_quantized: false, norms: Arc::new(std::sync::OnceLock::new()), row_ids_ascending: Arc::new(std::sync::OnceLock::new()), + identity_column: ROW_ID, } } @@ -630,6 +647,7 @@ impl DocSet { scoring_quantized: false, norms: Arc::new(std::sync::OnceLock::new()), row_ids_ascending: Arc::new(std::sync::OnceLock::new()), + identity_column: ROW_ID, }); } @@ -675,6 +693,7 @@ impl DocSet { scoring_quantized: false, norms: Arc::new(std::sync::OnceLock::new()), row_ids_ascending: Arc::new(std::sync::OnceLock::new()), + identity_column: ROW_ID, }); } @@ -698,6 +717,7 @@ impl DocSet { scoring_quantized: false, norms: Arc::new(std::sync::OnceLock::new()), row_ids_ascending: Arc::new(std::sync::OnceLock::new()), + identity_column: ROW_ID, }) } diff --git a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs index d8b4c7996d4..5bad41aed94 100644 --- a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs +++ b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs @@ -5,6 +5,7 @@ use super::*; use crate::scalar::RowAddrTranslatorRef; use crate::scalar::inverted::documents::DocumentRemapping; use lance_core::utils::row_addr_remap::RowAddrRemap; +use lance_core::{ROW_ADDR, ROW_ID}; use lance_index_core::remapping::RowAddrTranslator; #[derive(Debug, Default)] @@ -84,6 +85,19 @@ impl InvertedIndex { } } + /// The column this index's documents' identities are stored under, which + /// tracks [`Self::index_version`] exactly: both switch on + /// `results_are_row_addresses`. A segment rewritten from this one -- a + /// merge or a remap -- keeps this index's version, so it has to keep this + /// name too. + pub(super) fn identity_column(&self) -> &'static str { + if self.results_are_row_addresses { + ROW_ADDR + } else { + ROW_ID + } + } + fn posting_tail_codec(&self) -> PostingTailCodec { self.partitions .first() @@ -99,7 +113,16 @@ impl InvertedIndex { self.to_builder_with_offset(None) } + /// Every builder derived from an opened index inherits that index's + /// identity column (see [`Self::identity_column`]): a rewrite keeps the + /// source's `index_version`, so it must keep the matching column name, and + /// setting it here means no rewrite path can omit it. fn to_builder_with_offset(&self, fragment_mask: Option) -> InvertedIndexBuilder { + self.to_builder_with_offset_inner(fragment_mask) + .with_identity_column(self.identity_column()) + } + + fn to_builder_with_offset_inner(&self, fragment_mask: Option) -> InvertedIndexBuilder { if self.is_legacy() { // for legacy format, we re-create the index in the new format InvertedIndexBuilder::from_existing_index( @@ -254,6 +277,7 @@ impl InvertedIndex { .with_progress(progress) .with_token_set_format(first.token_set_format) .with_format_version(first.format_version()) + .with_identity_column(first.identity_column()) .update_from_segments(new_data, dest_store, segments, old_data_filters) .await? }; diff --git a/rust/lance-index/src/scalar/inverted/index/partition.rs b/rust/lance-index/src/scalar/inverted/index/partition.rs index 41684595dd8..e8eb2e730f2 100644 --- a/rust/lance-index/src/scalar/inverted/index/partition.rs +++ b/rust/lance-index/src/scalar/inverted/index/partition.rs @@ -1665,6 +1665,10 @@ impl InvertedPartition { ); builder.tokens = TokenDictionary::try_from_token_set(Arc::unwrap_or_clone(self.tokens))?; builder.docs = self.docs.load_build_docset().await?; + // Rewrites keep the source segment's `index_version`, so they must keep + // the identity column it was read under. + let identity_column = builder.docs.identity_column; + builder = builder.with_identity_column(identity_column); builder .posting_lists diff --git a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs index 6c99b7c3e84..ee59cef45a3 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs @@ -144,7 +144,7 @@ async fn write_test_partition_with_optional_impacts_and_positions( token_writer.write_record_batch(token_batch).await.unwrap(); token_writer.finish().await.unwrap(); - let doc_batch = docs.to_batch().unwrap(); + let doc_batch = docs.to_batch(lance_core::ROW_ID).unwrap(); let mut doc_writer = store .new_index_file(&doc_file_path(partition_id), doc_batch.schema()) .await diff --git a/rust/lance-index/src/scalar/registry.rs b/rust/lance-index/src/scalar/registry.rs index d622c690bcf..15090b53017 100644 --- a/rust/lance-index/src/scalar/registry.rs +++ b/rust/lance-index/src/scalar/registry.rs @@ -38,6 +38,19 @@ pub const VALUE_COLUMN_NAME: &str = "value"; pub trait TrainingRequest: std::any::Any + Send + Sync { fn as_any(&self) -> &dyn std::any::Any; fn criteria(&self) -> &TrainingCriteria; + + /// Tell the request whether the dataset it will train over uses stable + /// row ids. + /// + /// Every builtin type now trains on physical row addresses regardless, so + /// most plugins ignore this. It matters only where the *stored layout* + /// differs between the two cases -- an FTS segment names its document + /// identity column `_rowaddr` when it keeps its row-address-domain + /// version, and `_rowid` when it will be relabelled to a legacy version + /// for older readers, which only happens without stable row ids. + /// + /// Called before training; the default does nothing. + fn set_stable_row_ids(&mut self, _stable_row_ids: bool) {} } /// A default training request impl for indexes that don't need any parameters diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index 34bc653ad59..4a14e4e4f47 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -3153,3 +3153,147 @@ async fn test_fts_large_tie_pagination_across_query_shapes( } assert_eq!(pages, vec![0, 1, 2]); } + +/// The identity column in `docs.lance` has to be named for the domain the +/// segment is committed with: `_rowaddr` when it keeps +/// `INVERTED_ROW_ADDR_DOMAIN_VERSION`, `_rowid` when `build_scalar_index` +/// relabels it down for older readers. The reader resolves whichever name is +/// present, so only an assertion on the written file catches a build path that +/// was never told which to write. +#[rstest] +#[case::stable_row_ids(true, "_rowaddr")] +#[case::without_stable_row_ids(false, "_rowid")] +#[tokio::test] +async fn test_fts_docs_identity_column_matches_index_version( + #[case] stable_row_ids: bool, + #[case] expected_column: &str, +) { + use crate::dataset::index::LanceIndexStoreExt; + use lance_index::scalar::IndexStore; + use lance_index::scalar::lance_format::LanceIndexStore; + + let dir = TempStrDir::default(); + let mut ds = write_fts_dataset( + &dir, + combined_fields_batch(vec![0, 1, 2, 3], vec!["alpha"; 4], vec!["beta"; 4]), + Some(WriteParams { + enable_stable_row_ids: stable_row_ids, + max_rows_per_file: 2, + ..Default::default() + }), + ) + .await; + create_inverted_indices(&mut ds, &["title"], &combined_fields_test_params()).await; + + let meta = ds.load_index_by_name("title_idx").await.unwrap().unwrap(); + // With stable row ids the segment keeps the row-address-domain version; + // without them `build_scalar_index` relabels it down to whichever legacy + // version its posting format implies. + assert_eq!( + meta.results_are_row_addrs(), + stable_row_ids, + "index_version {} does not match the expected domain", + meta.index_version + ); + + // Read the committed docs file's schema straight off disk. + let store = LanceIndexStore::from_dataset_for_existing(&ds, &meta) + .await + .unwrap(); + let mut docs = None; + let mut tried = Vec::new(); + for id in 0..4u64 { + for candidate in [format!("part_{id}_docs.lance"), "docs.lance".to_string()] { + match store.open_index_file(&candidate).await { + Ok(reader) => { + docs = Some(reader); + break; + } + Err(err) => tried.push(format!("{candidate}: {err}")), + } + } + if docs.is_some() { + break; + } + } + let docs = docs.unwrap_or_else(|| panic!("no docs file; tried:\n{}", tried.join("\n"))); + let columns = docs + .schema() + .fields + .iter() + .map(|field| field.name.clone()) + .collect::>(); + assert!( + columns.iter().any(|name| name == expected_column), + "docs.lance for index_version {} must name its identity column \ + {expected_column}, got {columns:?}", + meta.index_version + ); + let unexpected = if expected_column == "_rowaddr" { + "_rowid" + } else { + "_rowaddr" + }; + assert!( + !columns.iter().any(|name| name == unexpected), + "docs.lance must not also carry {unexpected}: {columns:?}" + ); + + // Optimizing rewrites the segment but keeps its version, so the column has + // to survive a merge too. + ds.append( + RecordBatchIterator::new( + vec![Ok(combined_fields_batch( + vec![4, 5], + vec!["alpha"; 2], + vec!["beta"; 2], + ))], + combined_fields_batch(vec![4], vec!["alpha"], vec!["beta"]).schema(), + ), + None, + ) + .await + .unwrap(); + ds.optimize_indices(&OptimizeOptions::default()) + .await + .unwrap(); + let merged = ds.load_index_by_name("title_idx").await.unwrap().unwrap(); + let merged_store = LanceIndexStore::from_dataset_for_existing(&ds, &merged) + .await + .unwrap(); + let mut merged_docs = None; + for id in 0..6u64 { + if let Ok(reader) = merged_store + .open_index_file(&format!("part_{id}_docs.lance")) + .await + { + merged_docs = Some(reader); + break; + } + } + let merged_columns = merged_docs + .expect("merged index must have a docs file") + .schema() + .fields + .iter() + .map(|field| field.name.clone()) + .collect::>(); + assert!( + merged_columns.iter().any(|name| name == expected_column) + && !merged_columns.iter().any(|name| name == unexpected), + "a merge must keep the identity column name, got {merged_columns:?} \ + (merged index_version {}, addr-domain {})", + merged.index_version, + merged.results_are_row_addrs() + ); + + // And the index still answers, read back through the resolved name. + let ids = fts_result_ids( + &ds, + MatchQuery::new("alpha".into()) + .with_column(Some("title".into())) + .into(), + ) + .await; + assert_eq!(unique_ids(ids), HashSet::from([0, 1, 2, 3, 4, 5])); +} diff --git a/rust/lance/src/index/scalar.rs b/rust/lance/src/index/scalar.rs index a8ed9b33c24..d21984ea334 100644 --- a/rust/lance/src/index/scalar.rs +++ b/rust/lance/src/index/scalar.rs @@ -572,8 +572,13 @@ pub(super) async fn build_scalar_index( format!("The '{}' index type does not support basic training, please refer to the index's documentation for more details on how to create this index.", params.index_type).into(), ) })?; - let training_request = + let mut training_request = trainer.new_training_request(params.params.as_deref().unwrap_or("{}"), &field)?; + // Only the plugin knows whether its stored layout depends on this, and the + // default is a no-op. FTS uses it to name its document identity column for + // the `index_version` the segment will actually be committed with -- see + // the relabeling below. + training_request.set_stable_row_ids(dataset.manifest.uses_stable_row_ids()); // A zone map trained from the table reuses the write seeds its fragments // already carry and scans only the fragments without one. A caller that From e2eee96f380706ab71d18f2a3c1018b039c3223c Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Tue, 24 Nov 2026 09:07:57 -0800 Subject: [PATCH 10/15] docs(format): route posting IDs through the FTS identity column by name The posting-list description still resolved document IDs through `docs.lance._rowid`, which names only the pre-version-4 column after the rename. Refer to the identity column instead of one of its two names. Co-Authored-By: Claude Opus 5 --- docs/src/format/index/scalar/fts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/src/format/index/scalar/fts.md b/docs/src/format/index/scalar/fts.md index 068daf550a6..e4b29545f8a 100644 --- a/docs/src/format/index/scalar/fts.md +++ b/docs/src/format/index/scalar/fts.md @@ -49,7 +49,7 @@ loaded, is file corruption. | Column | Type | Nullable | Description | |------------------------|-------------------------|----------|------------------------------------------------------------------| -| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance._rowid`. | +| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance`'s identity column (`_rowaddr` or `_rowid`, see above). | | `_max_score` | Float32 | false | Maximum score for the token (for query optimization) | | `_length` | UInt32 | false | Number of documents containing the token | | `_compressed_position` | List> | true | Optional compressed position lists for phrase queries | From 5bbac58368a3f94d621818266331bc921c03a23f Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Tue, 24 Nov 2026 10:18:14 -0800 Subject: [PATCH 11/15] revert(docs): restore the FTS spec unchanged Spec changes require the format vote, and this PR does not need one: main's `fts.md` already specifies format version 4's document identity column as `_rowaddr` (the Document File Schema table lists `_rowid` for version <= 3 and `_rowaddr` for version >= 4). The code now writes that column, so the implementation matches the published spec rather than amending it. This drops every `fts.md` edit on the branch, including the original commit's -- which had rewritten the table into a single `_rowid` column and so contradicted what was already voted. Two inaccuracies are left standing in the restored text, neither introduced here and neither a format change: - The prose says the address lives in `docs.lance._rowid` while the table below it says `_rowaddr` for version 4. The table is what the code implements. This contradiction is pre-existing on main. - "format version 4 is specified here but is not yet implemented" is false once this PR lands. Both want a follow-up docs PR that can take the vote on its own. Co-Authored-By: Claude Opus 5 --- docs/src/format/index/scalar/fts.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/src/format/index/scalar/fts.md b/docs/src/format/index/scalar/fts.md index e4b29545f8a..4a36f4c851e 100644 --- a/docs/src/format/index/scalar/fts.md +++ b/docs/src/format/index/scalar/fts.md @@ -20,7 +20,7 @@ The FTS index consists of multiple files storing the token dictionary, document An FTS index may contain multiple partitions. Each partition has its own set of token, document, and posting list files, prefixed with the partition ID (e.g. `part_0_tokens.lance`, `part_0_docs.lance`, `part_0_invert.lance`). The `metadata.lance` file lists all partition IDs in the index. At query time, every partition must be searched and the results combined to produce the final ranked output. Fewer partitions generally means better query performance, since each partition requires its own token dictionary lookup and posting list scan. The number of partitions is controlled by the training configuration -- specifically `LANCE_FTS_TARGET_SIZE` determines how large each merged partition can grow (see [Training Process](#training-process) for details). -From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, each document's identity is stored in `docs.lance._rowaddr` and holds the document's physical row address (`fragment_id << 32 | offset`). In versions 1 through 3 it is stored in `docs.lance._rowid` and holds the dataset's row id. The column name therefore tracks `index_version`: a reader must select the column for the segment's version, and a reader that looks for the wrong one finds no such column rather than silently reading one domain's values as the other's. Writers may label a segment with version 1 through 3 only on a dataset without stable row ids, where row ids and row addresses are equal, and must then name the column `_rowid` so that a reader supporting only those versions can still read it. A reader that supports version 4 must also support every capability of version 3. The posting-list format is recorded separately and must not be inferred from `index_version`. +From format version 4 onward, a segment stores a physical row address (`fragment_id << 32 | offset`) in `docs.lance._rowid` instead of the dataset's logical row id. A segment persisted before version 4 stores a row id there instead. The current implementation supports format versions 1 through 3; format version 4 is specified here but is not yet implemented. ### Token Dictionary File Schema @@ -33,7 +33,8 @@ From format version 4 (`INVERTED_ROW_ADDR_DOMAIN_VERSION`) onward, each document | Column | Type | Nullable | Description | |---------------|--------|----------|----------------------------------| -| `_rowid` / `_rowaddr` | UInt64 | false | Document row ID, named `_rowid` (format version <= 3), or row address, named `_rowaddr` (format version >= 4); see above | +| `_rowid` | UInt64 | false | Document row ID (only if format version <= 3) | +| `_rowaddr` | UInt64 | false | Physical row address (`fragment_id << 32 \| offset`) of the document (only if format version >= 4) | | `_num_tokens` | UInt32 | false | Number of tokens in the document | Partitioned `docs.lance` files may include the optional schema metadata key @@ -49,7 +50,7 @@ loaded, is file corruption. | Column | Type | Nullable | Description | |------------------------|-------------------------|----------|------------------------------------------------------------------| -| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance`'s identity column (`_rowaddr` or `_rowid`, see above). | +| `_posting` | List | false | Compressed posting lists (delta-encoded document IDs and frequencies). A document ID is a dense, partition-local `u32` assigned when the document is appended, not a row id or row address; it is resolved to the document's row through `docs.lance._rowid` or `docs.lance._rowaddr`. | | `_max_score` | Float32 | false | Maximum score for the token (for query optimization) | | `_length` | UInt32 | false | Number of documents containing the token | | `_compressed_position` | List> | true | Optional compressed position lists for phrase queries | From 6ea4841a8ef96bead792de844feb35f0e5f2725e Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Tue, 24 Nov 2026 10:40:17 -0800 Subject: [PATCH 12/15] fix(fts): correct three regressions from the review round All three were introduced by this PR's own earlier commits; each test below was confirmed to fail with its fix reverted. - A whole-fragment (`Full`) allow or block mask failed FTS queries on a dataset *without* stable row ids. `fts_segments_are_address_domain` reports address domain there because the two domains coincide, which sent valid masks through `translate_treemap_to_row_addr_domain` -- added last round to report a `Full` entry as a mislabelled mask. Where a row id and a row address are the same number there is nothing to translate and nothing to mislabel, so the mask is now returned untouched. The report still stands on stable-row-id datasets, where the domains can actually differ. - `HybridCompoundQueryExec` truncated to the widened tie-rerank bound rather than the limit the caller asked for, so a mixed indexed/residual plan with no outer scanner limit returned up to the whole margin past `k` (a `k = 1` query returned 6 rows). - `DocSet::load_with_remapping` resolved the identity column but dropped it on the returned set, so a batch-remapped merge wrote `_rowid` while still committing `index_version` 4. Only the reader's name resolution hid it; a reader selecting the specified v4 `_rowaddr` column could not read the rewritten file. It now records the detected name as `load` does. Reported by @Xuanwo (items 1-3) and the gatekeeper (item 3). Co-Authored-By: Claude Opus 5 --- .../src/scalar/inverted/index/doc_set.rs | 8 +- .../tests/dataset_fts_combined_fields.rs | 233 ++++++++++++++++++ rust/lance/src/io/exec/fts/compound.rs | 6 +- rust/lance/src/io/exec/utils.rs | 7 + 4 files changed, 251 insertions(+), 3 deletions(-) diff --git a/rust/lance-index/src/scalar/inverted/index/doc_set.rs b/rust/lance-index/src/scalar/inverted/index/doc_set.rs index 53a4ea48c41..fd2e3fc8fbc 100644 --- a/rust/lance-index/src/scalar/inverted/index/doc_set.rs +++ b/rust/lance-index/src/scalar/inverted/index/doc_set.rs @@ -546,13 +546,17 @@ impl DocSet { }; doc_indices.push(column.as_primitive::()); } - Self::from_columns_with_doc_indices( + let mut docs = Self::from_columns_with_doc_indices( row_id_col, num_tokens_col, &doc_indices, is_legacy, frag_reuse_index, - ) + )?; + // Same as `load`: a rewrite derived from this set keeps the source's + // `index_version`, so it has to keep the column that version names. + docs.identity_column = identity; + Ok(docs) } /// Build a `DocSet` carrying only the per-doc `num_tokens` array; diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index 4a14e4e4f47..dfae8f0192b 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -3297,3 +3297,236 @@ async fn test_fts_docs_identity_column_matches_index_version( .await; assert_eq!(unique_ids(ids), HashSet::from([0, 1, 2, 3, 4, 5])); } + +/// Without stable row ids a logical row id *is* a physical row address, so a +/// whole-fragment (`Full`) allow or block mask is a legitimate shape rather +/// than the mislabelled one `translate_treemap_to_row_addr_domain` reports. +/// Forcing it through translation regressed these queries, which pass on the +/// base commit. +#[rstest] +#[case::allow_list(true)] +#[case::block_list(false)] +#[tokio::test] +async fn test_fts_whole_fragment_mask_without_stable_row_ids(#[case] allow: bool) { + let dir = TempStrDir::default(); + let mut ds = write_fts_dataset( + &dir, + combined_fields_batch(vec![0, 1, 2, 3], vec!["alpha"; 4], vec!["beta"; 4]), + Some(WriteParams { + enable_stable_row_ids: false, + max_rows_per_file: 2, + ..Default::default() + }), + ) + .await; + create_inverted_indices(&mut ds, &["title"], &combined_fields_test_params()).await; + + // A mask naming whole fragments, not individual rows. + let mut fragments = RowAddrTreeMap::new(); + fragments.insert_fragment(0); + let mask = if allow { + RowAddrMask::from_allowed(fragments) + } else { + RowAddrMask::from_block(fragments) + }; + + let mut scan = ds.scan(); + scan.project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query( + MatchQuery::new("alpha".into()) + .with_column(Some("title".into())) + .into(), + )) + .unwrap() + .with_row_id_prefilter(mask); + let batch = scan + .try_into_batch() + .await + .expect("a whole-fragment mask must not fail the query"); + let ids = batch["id"] + .as_primitive::() + .values() + .iter() + .copied() + .collect::>(); + // Fragment 0 holds ids 0 and 1 (two rows per file). + let expected: HashSet = if allow { + HashSet::from([0, 1]) + } else { + HashSet::from([2, 3]) + }; + assert_eq!(ids, expected); +} + +/// `HybridCompoundQueryExec` widens its limit for tie re-ranking, so its final +/// truncation has to use the limit the caller asked for. With a mixed +/// indexed/residual plan and no outer scanner limit, truncating to the widened +/// bound returned up to the whole tie margin past `k`. +#[tokio::test] +async fn test_fts_hybrid_compound_respects_requested_limit() { + use lance_index::scalar::inverted::query::{BooleanQuery, Occur}; + + let dir = TempStrDir::default(); + let mut ds = write_fts_dataset( + &dir, + combined_fields_batch((0..40).collect(), vec!["alpha"; 40], vec!["beta"; 40]), + Some(WriteParams { + enable_stable_row_ids: true, + max_rows_per_file: 20, + ..Default::default() + }), + ) + .await; + create_inverted_indices(&mut ds, &["title", "body"], &combined_fields_test_params()).await; + // Unindexed rows force the residual side, making this the hybrid plan. + let ds = append_fts_dataset( + &dir, + combined_fields_batch((40..45).collect(), vec!["alpha"; 5], vec!["beta"; 5]), + None, + ) + .await; + + let query: FtsQuery = BooleanQuery::new([( + Occur::Must, + MatchQuery::new("alpha".into()) + .with_column(Some("title".into())) + .into(), + )]) + .into(); + // No outer scanner limit: the FTS node's own `k` is the only bound. + let batch = ds + .scan() + .project(&["id"]) + .unwrap() + .full_text_search(FullTextSearchQuery::new_query(query).limit(Some(1))) + .unwrap() + .try_into_batch() + .await + .unwrap(); + assert_eq!( + batch.num_rows(), + 1, + "a k=1 hybrid query must return one row, got {}", + batch.num_rows() + ); +} + +/// A rewrite keeps its source's `index_version`, so it has to keep the column +/// that version names. `DocSet::load_with_remapping` detected the column but +/// dropped it on the returned set, so a batch-remapped merge wrote `_rowid` +/// while still committing version 4 -- readable only because the reader +/// resolves either name, and unreadable to a strict v4 reader. +#[tokio::test] +async fn test_fts_identity_column_survives_a_batch_remapped_merge() { + use crate::dataset::index::LanceIndexStoreExt; + use datafusion::physical_plan::stream::RecordBatchStreamAdapter; + use lance_core::cache::LanceCache; + use lance_index::progress::noop_progress; + use lance_index::scalar::BatchRowIdRemapper; + use lance_index::scalar::IndexStore; + use lance_index::scalar::inverted::{InvertedIndex, InvertedIndexPlugin}; + use lance_index::scalar::lance_format::LanceIndexStore; + use lance_index::scalar::registry::ScalarIndexPlugin; + + #[derive(Debug)] + struct IdentityRemapper; + #[async_trait::async_trait] + impl BatchRowIdRemapper for IdentityRemapper { + async fn remap_row_ids(&self, ids: &[u64]) -> lance_core::Result>> { + Ok(ids.iter().copied().map(Some).collect()) + } + } + + /// Every `docs.lance` file an index committed, by name. + async fn docs_columns(ds: &Dataset, meta: &lance_table::format::IndexMetadata) -> Vec { + let store = LanceIndexStore::from_dataset_for_existing(ds, meta) + .await + .unwrap(); + let mut columns = Vec::new(); + for file in meta + .files + .as_ref() + .expect("committed index records its files") + .iter() + .filter(|file| file.path.ends_with("docs.lance")) + { + let reader = store.open_index_file(&file.path).await.unwrap(); + columns.extend(reader.schema().fields.iter().map(|f| f.name.clone())); + } + columns + } + + let dir = TempStrDir::default(); + let mut ds = write_fts_dataset( + &dir, + combined_fields_batch(vec![0, 1, 2, 3], vec!["alpha"; 4], vec!["beta"; 4]), + Some(WriteParams { + enable_stable_row_ids: true, + max_rows_per_file: 2, + ..Default::default() + }), + ) + .await; + create_inverted_indices(&mut ds, &["title"], &combined_fields_test_params()).await; + let meta = ds.load_index_by_name("title_idx").await.unwrap().unwrap(); + assert!( + docs_columns(&ds, &meta) + .await + .iter() + .any(|c| c == "_rowaddr"), + "the source index should already be _rowaddr" + ); + + // Open through the batch-remapping loader, then rewrite via a merge. + let store = LanceIndexStore::from_dataset_for_existing(&ds, &meta) + .await + .unwrap(); + let opened = InvertedIndexPlugin + .load_index_with_remapping( + Arc::new(store), + meta.index_details.as_ref().unwrap().as_ref(), + meta.index_version as u32, + Some(Arc::new(IdentityRemapper)), + &LanceCache::no_cache(), + ) + .await + .unwrap(); + let source = Arc::new( + opened + .as_any() + .downcast_ref::() + .unwrap() + .clone(), + ); + + let uuid = uuid::Uuid::new_v4(); + let dest = LanceIndexStore::from_dataset_for_new(&ds, &uuid).unwrap(); + let empty = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, false), + ArrowField::new("_rowaddr", DataType::UInt64, false), + ])); + let stream = Box::pin(RecordBatchStreamAdapter::new( + empty, + futures::stream::empty(), + )); + let created = InvertedIndex::merge_segments(&[source], stream, &dest, &[None], noop_progress()) + .await + .unwrap(); + assert_eq!( + created.index_version, 4, + "the rewrite keeps the source's version" + ); + + let rewritten = lance_table::format::IndexMetadata { + uuid, + index_details: Some(Arc::new(created.index_details)), + files: Some(lance_index::scalar::index_files_to_table(created.files)), + ..meta + }; + let columns = docs_columns(&ds, &rewritten).await; + assert!( + columns.iter().any(|c| c == "_rowaddr") && !columns.iter().any(|c| c == "_rowid"), + "a version-4 rewrite must write _rowaddr, got {columns:?}" + ); +} diff --git a/rust/lance/src/io/exec/fts/compound.rs b/rust/lance/src/io/exec/fts/compound.rs index 8665cb04762..c3a624b454f 100644 --- a/rust/lance/src/io/exec/fts/compound.rs +++ b/rust/lance/src/io/exec/fts/compound.rs @@ -912,7 +912,11 @@ impl ExecutionPlan for HybridCompoundQueryExec { .total_cmp(&left.score.0) .then_with(|| left.row_id.cmp(&right.row_id)) }); - documents.truncate(limit); + // `limit` is the widened search bound (see `widen_limit_for_tie_rerank`); + // what the caller asked for is `requested_limit`. Truncating to the + // widened one would return up to the whole tie margin past `k` on a + // mixed indexed/residual plan with no outer scanner limit. + documents.truncate(requested_limit.unwrap_or(limit)); metrics.baseline_metrics.record_output(documents.len()); scored_documents_batch(schema, documents, None, None).map_err(DataFusionError::from) }); diff --git a/rust/lance/src/io/exec/utils.rs b/rust/lance/src/io/exec/utils.rs index 2230fb9b2bb..c8a56abda87 100644 --- a/rust/lance/src/io/exec/utils.rs +++ b/rust/lance/src/io/exec/utils.rs @@ -560,6 +560,13 @@ async fn row_id_mask_to_row_addr_domain( dataset: &Dataset, mask: Arc, ) -> Result> { + if !dataset.manifest.uses_stable_row_ids() { + // A row id and a row address are the same number here, so the mask is + // already in the domain the caller wants. Returning it untouched also + // keeps a legitimate whole-fragment entry intact -- those are only a + // sign of a mislabelled mask where the two domains can actually differ. + return Ok(mask); + } let translated = match mask.as_ref() { RowAddrMask::AllowList(allow) => { RowAddrMask::AllowList(translate_treemap_to_row_addr_domain(dataset, allow).await?) From e894754b6c5830b99d18b273beb7b53895a27cda Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 30 Nov 2026 04:16:56 -0800 Subject: [PATCH 13/15] refactor(fts): load an FTS segment in the row-address domain by default Review: the new `results_are_row_addresses` parameter on `InvertedIndex::load` forced `, true` onto ~85 call sites that only wanted the behaviour a fresh index already has, which both bloated the diff and left a bare bool to interpret at each site. `load`/`load_with_remapping` now return `InvertedIndexLoad`, awaited directly (via `IntoFuture`), so those call sites go back to their pre-migration three-argument form. The domain is named only where it is not the default: - `.in_legacy_row_id_domain()` for a segment persisted before `INVERTED_ROW_ADDR_DOMAIN_VERSION`, whose identity column holds row ids. - `.in_domain_of_version(index_version)` for the two plugin entry points, which resolve the domain from the manifest's declared version. Note the method is named for the row-*id* domain rather than the row-address one suggested in review: the default already is row addresses, so the opt-out is the legacy side. No behaviour change -- every former `true` is the new default and every former `false` is the explicit legacy call. Co-Authored-By: Claude Opus 5 --- rust/lance-index/benches/inverted.rs | 9 +- .../benches/inverted_request_cache.rs | 2 +- rust/lance-index/src/scalar/inverted.rs | 22 +--- .../src/scalar/inverted/builder.rs | 65 +++++----- .../src/scalar/inverted/combined/testing.rs | 2 +- .../scalar/inverted/index/inverted_index.rs | 114 +++++++++++++++++- .../src/scalar/inverted/index/tests.rs | 13 +- .../inverted/index/tests/flat_search.rs | 6 +- .../index/tests/format_and_builder.rs | 2 +- .../scalar/inverted/index/tests/grouping.rs | 2 +- .../scalar/inverted/index/tests/lifecycle.rs | 38 ++++-- .../inverted/index/tests/position_cache.rs | 6 +- .../inverted/index/tests/prewarm_cache.rs | 20 ++- .../src/scalar/inverted/index/tests/query.rs | 54 ++++----- .../scalar/inverted/index/tests/scoring.rs | 16 +-- .../src/scalar/inverted/index/tests/stats.rs | 8 +- rust/lance-index/src/scalar/registry.rs | 4 +- 17 files changed, 237 insertions(+), 146 deletions(-) diff --git a/rust/lance-index/benches/inverted.rs b/rust/lance-index/benches/inverted.rs index c5575bc1056..2fd19ee0024 100644 --- a/rust/lance-index/benches/inverted.rs +++ b/rust/lance-index/benches/inverted.rs @@ -142,12 +142,9 @@ fn bench_inverted(c: &mut Criterion) { .unwrap(); }); let invert_index = rt - .block_on(InvertedIndex::load( - phrase_search_store, - None, - &LanceCache::no_cache(), - true, - )) + .block_on(async { + InvertedIndex::load(phrase_search_store, None, &LanceCache::no_cache()).await + }) .unwrap(); let params = FtsSearchParams::new().with_limit(Some(10)); diff --git a/rust/lance-index/benches/inverted_request_cache.rs b/rust/lance-index/benches/inverted_request_cache.rs index 9edae74aa39..ef406072038 100644 --- a/rust/lance-index/benches/inverted_request_cache.rs +++ b/rust/lance-index/benches/inverted_request_cache.rs @@ -125,7 +125,7 @@ impl Fixture { .await .unwrap(); file_sizes.insert(file.path, file.size_bytes); - let index = InvertedIndex::load(store.clone(), None, &index_cache, true) + let index = InvertedIndex::load(store.clone(), None, &index_cache) .await .unwrap(); index.prewarm().await.unwrap(); diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index d587fafdc06..18f6ca7ceb6 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -761,14 +761,9 @@ impl ScalarIndexPlugin for InvertedIndexPlugin { frag_reuse_index: Option>, cache: &LanceCache, ) -> Result> { - let results_are_row_addresses = index_version >= INVERTED_ROW_ADDR_DOMAIN_VERSION; - let index = InvertedIndex::load( - index_store, - frag_reuse_index, - cache, - results_are_row_addresses, - ) - .await?; + let index = InvertedIndex::load(index_store, frag_reuse_index, cache) + .in_domain_of_version(index_version) + .await?; let details = decode_inverted_details(index_details)?; let expected_granularity = DocumentGranularity::try_from(details.document_granularity)?; let physical_granularity = index.params().get_document_granularity(); @@ -792,14 +787,9 @@ impl ScalarIndexPlugin for InvertedIndexPlugin { frag_reuse_index: Option>, cache: &LanceCache, ) -> Result> { - let results_are_row_addresses = index_version >= INVERTED_ROW_ADDR_DOMAIN_VERSION; - let index = InvertedIndex::load_with_remapping( - index_store, - frag_reuse_index, - cache, - results_are_row_addresses, - ) - .await?; + let index = InvertedIndex::load_with_remapping(index_store, frag_reuse_index, cache) + .in_domain_of_version(index_version) + .await?; let details = decode_inverted_details(index_details)?; let expected_granularity = DocumentGranularity::try_from(details.document_granularity)?; let physical_granularity = index.params().get_document_granularity(); diff --git a/rust/lance-index/src/scalar/inverted/builder.rs b/rust/lance-index/src/scalar/inverted/builder.rs index d012db18d61..7ba2a38f786 100644 --- a/rust/lance-index/src/scalar/inverted/builder.rs +++ b/rust/lance-index/src/scalar/inverted/builder.rs @@ -4821,7 +4821,7 @@ mod tests { ) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; assert_eq!(index.partition_count(), 1); Ok(()) @@ -5011,7 +5011,7 @@ mod tests { .write_metadata(src_store.as_ref(), &[0]) .await?; - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()).await?; let derived_params = index.derive_index_params()?; let derived_params: InvertedIndexParams = serde_json::from_str(derived_params.params.as_deref().unwrap())?; @@ -5033,7 +5033,7 @@ mod tests { .await?; let updated = - InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache(), true).await?; + InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache()).await?; assert_eq!(updated.partitions.len(), 1); for partition in &updated.partitions { assert_eq!( @@ -5133,7 +5133,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(params); builder.update(stream, store.as_ref(), None).await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; assert_eq!(index.partitions.len(), 1); let partition = &index.partitions[0]; let token_id = partition.tokens.get("hello").unwrap(); @@ -5194,7 +5194,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; let (total_tokens, num_docs, token_docs) = index .bm25_stats_for_terms(&["hello".to_string()], None) .await?; @@ -5244,7 +5244,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; assert!(index.partitions.is_empty()); let statistics = index.statistics()?; assert_eq!(statistics["num_tokens"], 0); @@ -5294,7 +5294,7 @@ mod tests { .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; let statistics = index.statistics()?; assert_eq!(statistics["num_tokens"], 0); assert_eq!(statistics["num_docs"], 5); @@ -6359,10 +6359,8 @@ mod tests { builder .write(pipeline_store.as_ref(), files, FinalizeOptions::default()) .await?; - let reference = - InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; - let actual = - InvertedIndex::load(pipeline_store, None, &LanceCache::no_cache(), true).await?; + let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; + let actual = InvertedIndex::load(pipeline_store, None, &LanceCache::no_cache()).await?; if all_null || docs_per_fragment == 0 { assert_eq!(actual.partition_count(), 0); } else { @@ -6558,7 +6556,7 @@ mod tests { builder .update(Box::pin(stream), store.as_ref(), None) .await?; - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()).await?; // The caller keeps the TempDir alive for as long as it queries the // loaded index. Ok((index_dir, index)) @@ -6944,7 +6942,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(InvertedIndexParams::default()); builder.update(stream, store.as_ref(), None).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); assert!( @@ -6989,7 +6987,7 @@ mod tests { .unwrap(); // Load it back and confirm the invalidated fragments are set - let index = InvertedIndex::load(src_store.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(src_store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert_eq!(index.deleted_fragments(), &initial_deleted); @@ -7003,10 +7001,9 @@ mod tests { .unwrap(); // Reload from dest and verify deleted fragments are preserved - let remapped_index = - InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache(), true) - .await - .unwrap(); + let remapped_index = InvertedIndex::load(dest_store.clone(), None, &LanceCache::no_cache()) + .await + .unwrap(); assert_eq!( remapped_index.deleted_fragments(), &initial_deleted, @@ -7032,7 +7029,7 @@ mod tests { builder.update(stream, store.as_ref(), None).await.unwrap(); // Load the index and update it with an old_data_filter that invalidates fragments - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert!(index.deleted_fragments().is_empty()); @@ -7062,7 +7059,7 @@ mod tests { .unwrap(); let updated_index = - InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache(), true) + InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert_eq!( @@ -7090,7 +7087,7 @@ mod tests { builder.update(stream, store1.as_ref(), None).await.unwrap(); // First update: delete fragments 3 and 7 - let index = InvertedIndex::load(store1.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store1.clone(), None, &LanceCache::no_cache()) .await .unwrap(); @@ -7120,7 +7117,7 @@ mod tests { .unwrap(); // Second update: invalidate additional fragments 12 and 15 - let index2 = InvertedIndex::load(store2.clone(), None, &LanceCache::no_cache(), true) + let index2 = InvertedIndex::load(store2.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert_eq!( @@ -7152,7 +7149,7 @@ mod tests { .await .unwrap(); - let index3 = InvertedIndex::load(store3.clone(), None, &LanceCache::no_cache(), true) + let index3 = InvertedIndex::load(store3.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert_eq!( @@ -7178,7 +7175,7 @@ mod tests { let mut builder = InvertedIndexBuilder::new(InvertedIndexParams::default()); builder.update(stream, store.as_ref(), None).await.unwrap(); - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); @@ -7206,7 +7203,7 @@ mod tests { .unwrap(); let updated_index = - InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache(), true) + InvertedIndex::load(update_store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); assert!( @@ -7677,8 +7674,7 @@ mod tests { .update(input, store.as_ref(), None) .await? }; - let index = - InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()).await?; if let Some(source) = &previous_store { assert_eq!( source.copy_count.load(Ordering::SeqCst), @@ -7720,8 +7716,7 @@ mod tests { InvertedIndexBuilder::new(params) .update(input, reference_store.as_ref(), None) .await?; - let reference = - InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; + let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; assert_eq!( consolidation_search(previous.as_ref().unwrap(), &["common"], Operator::Or, false) .await, @@ -7770,8 +7765,7 @@ mod tests { assert!(sizes[0].stored_bytes >= ceiling); assert!(sizes[1].stored_bytes < ceiling); - let index = - InvertedIndex::load(source.clone(), None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(source.clone(), None, &LanceCache::no_cache()).await?; let batch = make_doc_batch("common text", RowAddress::new_from_parts(2, 0).into()); let input = Box::pin(RecordBatchStreamAdapter::new( batch.schema(), @@ -7790,8 +7784,7 @@ mod tests { .with_format_version(builder.format_version) .update(input, dest.as_ref(), None) .await?; - let updated = - InvertedIndex::load(dest.clone(), None, &LanceCache::no_cache(), true).await?; + let updated = InvertedIndex::load(dest.clone(), None, &LanceCache::no_cache()).await?; assert_eq!( updated.partition_count(), 2, @@ -7877,8 +7870,7 @@ mod tests { .await?; (staged_store, files) }; - let index = - InvertedIndex::load(output.clone(), None, &LanceCache::no_cache(), true).await?; + let index = InvertedIndex::load(output.clone(), None, &LanceCache::no_cache()).await?; assert_eq!( index.partition_count(), 1, @@ -7949,8 +7941,7 @@ mod tests { reference_builder .update(Box::pin(stream), reference_store.as_ref(), None) .await?; - let reference = - InvertedIndex::load(reference_store, None, &LanceCache::no_cache(), true).await?; + let reference = InvertedIndex::load(reference_store, None, &LanceCache::no_cache()).await?; for (tokens, operator, phrase) in [ (vec!["common"], Operator::Or, false), diff --git a/rust/lance-index/src/scalar/inverted/combined/testing.rs b/rust/lance-index/src/scalar/inverted/combined/testing.rs index f4cf2196685..b1ad17b2950 100644 --- a/rust/lance-index/src/scalar/inverted/combined/testing.rs +++ b/rust/lance-index/src/scalar/inverted/combined/testing.rs @@ -387,7 +387,7 @@ pub(super) async fn element_document_index( .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); (index, tmpdir) diff --git a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs index 5bad41aed94..2180a85cf62 100644 --- a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs +++ b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs @@ -46,6 +46,80 @@ pub struct InvertedIndex { pub(super) results_are_row_addresses: bool, } +enum InvertedLoadRemapping { + RowId(Option>), + Batch(Option>), +} + +/// A pending [`InvertedIndex::load`]. Awaited directly in the common case; the +/// builder exists only so the rare legacy load can name its domain. +/// +/// The domain carried here is the one the *manifest* declares through +/// `index_version`, which the segment's own `docs.lance` identity column is +/// then checked against. Defaulting it to row addresses -- what every build +/// from [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] onward writes -- leaves only the +/// legacy segments spelling their domain out. +#[must_use = "a load does nothing until it is awaited"] +pub struct InvertedIndexLoad<'a> { + store: Arc, + remapping: InvertedLoadRemapping, + index_cache: &'a LanceCache, + results_are_row_addresses: bool, +} + +impl InvertedIndexLoad<'_> { + /// Read `docs.lance`'s identity column as row ids rather than row + /// addresses, for a segment persisted before + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]. + pub fn in_legacy_row_id_domain(mut self) -> Self { + self.results_are_row_addresses = false; + self + } + + /// Resolve the domain from the segment's `index_version` instead of + /// naming it: the row-id domain below [`INVERTED_ROW_ADDR_DOMAIN_VERSION`], + /// row addresses from it onward. + pub fn in_domain_of_version(self, index_version: u32) -> Self { + if index_version < INVERTED_ROW_ADDR_DOMAIN_VERSION { + self.in_legacy_row_id_domain() + } else { + self + } + } +} + +impl<'a> std::future::IntoFuture for InvertedIndexLoad<'a> { + type Output = Result>; + type IntoFuture = futures::future::BoxFuture<'a, Self::Output>; + + fn into_future(self) -> Self::IntoFuture { + let Self { + store, + remapping, + index_cache, + results_are_row_addresses, + } = self; + match remapping { + InvertedLoadRemapping::RowId(frag_reuse_index) => { + Box::pin(InvertedIndex::load_in_domain( + store, + frag_reuse_index, + index_cache, + results_are_row_addresses, + )) + } + InvertedLoadRemapping::Batch(remapping) => { + Box::pin(InvertedIndex::load_with_remapping_in_domain( + store, + remapping, + index_cache, + results_are_row_addresses, + )) + } + } + } +} + impl Debug for InvertedIndex { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("InvertedIndex") @@ -616,7 +690,27 @@ impl InvertedIndex { } } - pub async fn load( + /// Load a segment whose `docs.lance` identity column holds physical row + /// addresses -- what every build from [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] + /// onward writes. + /// + /// For a segment persisted before that version, whose identity column holds + /// row ids instead, chain [`InvertedIndexLoad::in_legacy_row_id_domain`] + /// before awaiting. + pub fn load( + store: Arc, + frag_reuse_index: Option>, + index_cache: &LanceCache, + ) -> InvertedIndexLoad<'_> { + InvertedIndexLoad { + store, + remapping: InvertedLoadRemapping::RowId(frag_reuse_index), + index_cache, + results_are_row_addresses: true, + } + } + + async fn load_in_domain( store: Arc, frag_reuse_index: Option>, index_cache: &LanceCache, @@ -732,8 +826,22 @@ impl InvertedIndex { } /// Additive sibling of [`Self::load`] for mappings that require - /// asynchronous batch row-ID translation. - pub(crate) async fn load_with_remapping( + /// asynchronous batch row-ID translation. Carries the same domain default + /// and the same [`InvertedIndexLoad::in_legacy_row_id_domain`] opt-out. + pub(crate) fn load_with_remapping( + store: Arc, + remapping: Option>, + index_cache: &LanceCache, + ) -> InvertedIndexLoad<'_> { + InvertedIndexLoad { + store, + remapping: InvertedLoadRemapping::Batch(remapping), + index_cache, + results_are_row_addresses: true, + } + } + + async fn load_with_remapping_in_domain( store: Arc, remapping: Option>, index_cache: &LanceCache, diff --git a/rust/lance-index/src/scalar/inverted/index/tests.rs b/rust/lance-index/src/scalar/inverted/index/tests.rs index 8733764c2e1..729cf25ccc8 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests.rs @@ -96,12 +96,13 @@ async fn write_single_partition_index( .await?; writer.finish_with_metadata(metadata).await?; - InvertedIndex::load( - store, - None, - &LanceCache::no_cache(), - results_are_row_addresses, - ) + let cache = LanceCache::no_cache(); + let load = InvertedIndex::load(store, None, &cache); + if results_are_row_addresses { + load + } else { + load.in_legacy_row_id_domain() + } .await } diff --git a/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs b/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs index b05a62ccc28..fef1d84f75b 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/flat_search.rs @@ -213,7 +213,7 @@ async fn test_ngram_phrase_preserves_positions_indexed_and_flat( ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); let tokens = try_collect_query_tokens("abcd", &mut params.build().unwrap()).unwrap(); @@ -348,7 +348,7 @@ async fn test_ngram_match_requires_all_terms_indexed_and_flat( ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); for (operator, expected) in [(Operator::And, expected_and), (Operator::Or, expected_or)] { @@ -548,7 +548,7 @@ async fn test_document_lengths_indexed_and_flat( ) .await .unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); let (tokens, num_docs, _) = index.bm25_stats_for_terms(&[], None).await.unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs b/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs index e2b2b8f936e..13eb61c101b 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/format_and_builder.rs @@ -979,7 +979,7 @@ async fn test_build_search_uses_configured_posting_block_size() { write_test_metadata(&store, vec![0], params).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); assert_eq!(index.partitions[0].inverted_list.block_size(), block_size); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs b/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs index 6b959a46258..4c900f4c66a 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/grouping.rs @@ -564,7 +564,7 @@ async fn test_grouped_bm25_search_correct_and_cache_stable() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs index 889b13905fa..ed7da1b7305 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs @@ -91,7 +91,7 @@ async fn build_multi_partition_index( // Keep the cache alive and return it: the partition readers hold only a // WeakLanceCache, so the prewarmed entries vanish if this Arc is dropped. let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); (index, cache) @@ -211,7 +211,9 @@ async fn test_update_preserves_v2_format_version() -> Result<()> { .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), false).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(index.format_version(), format_version); assert_eq!(index.index_version(), INVERTED_INDEX_VERSION_V2); @@ -229,7 +231,9 @@ async fn test_update_preserves_v2_format_version() -> Result<()> { assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V2); - let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; + let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(updated.format_version(), format_version); assert_eq!(updated.index_version(), INVERTED_INDEX_VERSION_V2); // Consolidating the two tiny partitions must preserve their V2 format. @@ -283,7 +287,9 @@ async fn test_block_size_256_writes_v3_metadata_and_index_version() -> Result<() write_test_metadata(&src_store, vec![0], params).await; - let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache(), false).await?; + let index = InvertedIndex::load(src_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(index.format_version(), InvertedListFormatVersion::V3); assert_eq!(index.index_version(), INVERTED_INDEX_VERSION_V3); @@ -292,7 +298,9 @@ async fn test_block_size_256_writes_v3_metadata_and_index_version() -> Result<() .await?; assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V3); - let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; + let updated = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(updated.format_version(), InvertedListFormatVersion::V3); assert_eq!(updated.index_version(), INVERTED_INDEX_VERSION_V3); @@ -334,7 +342,9 @@ async fn test_merge_segments_preserves_arrow_token_set_format() -> Result<()> { .await?; assert_eq!(created.index_version, 0); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(merged.index_version(), 0); assert_eq!(merged.token_set_format, TokenSetFormat::Arrow); @@ -391,7 +401,9 @@ async fn test_merge_segments_preserves_format_version( .await?; assert_eq!(created.index_version, format_version.index_version()); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(merged.format_version(), format_version); assert_eq!(merged.index_version(), format_version.index_version()); @@ -424,7 +436,9 @@ async fn test_merge_v1_segments_with_empty_segment(#[case] is_empty_first: bool) let params = InvertedIndexParams::default().format_version(InvertedListFormatVersion::V1); write_test_metadata(&empty_store, Vec::new(), params.clone()).await; - let empty = InvertedIndex::load(empty_store, None, &LanceCache::no_cache(), false).await?; + let empty = InvertedIndex::load(empty_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(empty.partition_count(), 0); assert_eq!(empty.format_version(), InvertedListFormatVersion::V1); @@ -453,7 +467,9 @@ async fn test_merge_v1_segments_with_empty_segment(#[case] is_empty_first: bool) .await?; assert_eq!(created.index_version, INVERTED_INDEX_VERSION_V1); - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), false).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()) + .in_legacy_row_id_domain() + .await?; assert_eq!(merged.format_version(), InvertedListFormatVersion::V1); assert_eq!(merged.index_version(), INVERTED_INDEX_VERSION_V1); @@ -521,7 +537,7 @@ async fn test_merge_segments_uses_memory_limit_for_old_partitions() -> Result<() ) .await?; - let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache(), true).await?; + let merged = InvertedIndex::load(dest_store, None, &LanceCache::no_cache()).await?; assert_eq!(merged.partitions.len(), 2); let mut partition_ids = merged .partitions @@ -575,7 +591,7 @@ async fn test_modern_index_without_deleted_col_has_empty_bitmap() { .unwrap(); writer.finish_with_metadata(metadata).await.unwrap(); - let index = InvertedIndex::load(store, None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store, None, &LanceCache::no_cache()) .await .unwrap(); assert!( diff --git a/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs b/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs index 64fa7e1cb37..c4929b35408 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/position_cache.rs @@ -136,7 +136,7 @@ async fn test_prewarm_with_positions_populates_separate_position_cache() { let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(4096), ))); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -257,7 +257,7 @@ async fn test_best_effort_prewarm_reports_missing_requested_positions() { let cache = Arc::new(LanceCache::with_backend(Arc::new( RejectPositionsCacheBackend::new(1 << 20), ))); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); @@ -342,7 +342,7 @@ async fn test_prewarm_with_v2_positions_preserves_shared_stream_codec() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); index diff --git a/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs b/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs index 4775f3247f5..c16877be24c 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/prewarm_cache.rs @@ -323,10 +323,8 @@ async fn cached_fts_versions_release_posting_readers( None, &version_cache, Box::pin(async move { - Ok( - InvertedIndex::load(load_store, None, &load_cache, true).await? - as Arc, - ) + Ok(InvertedIndex::load(load_store, None, &load_cache).await? + as Arc) }), ) .await @@ -512,7 +510,7 @@ async fn test_posting_cache_conflict_across_partitions() { // Load the inverted index let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -633,7 +631,7 @@ async fn test_modern_prewarm_packs_group_with_shared_posting_buffer() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -934,7 +932,7 @@ async fn test_prewarm_streams_in_chunks_preserves_content( writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(1 << 20)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -1083,7 +1081,7 @@ async fn test_prewarm_streams_in_chunks_with_positions( let cache = Arc::new(LanceCache::with_backend(Arc::new( CacheWithoutResidentProbe(QuickCacheBackend::with_capacity(1 << 20)), ))); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); let inverted_list = &index.partitions[0].inverted_list; @@ -1180,7 +1178,7 @@ async fn test_prewarm_streams_in_chunks_with_positions( let probe_cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(1 << 20), ))); - let probe_index = InvertedIndex::load(store, None, probe_cache.as_ref(), true) + let probe_index = InvertedIndex::load(store, None, probe_cache.as_ref()) .await .unwrap(); let probe_inverted_list = &probe_index.partitions[0].inverted_list; @@ -1261,7 +1259,7 @@ async fn test_prewarm_restores_metadata_after_persistent_posting_pressure( ..Default::default() }); let cache = Arc::new(LanceCache::with_backend(backend.clone())); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); let options = FtsPrewarmOptions { @@ -1336,7 +1334,7 @@ async fn test_strict_modern_prewarm_fails_when_index_cache_cannot_hold_all_parti let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(8 * 1024), ))); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/query.rs b/rust/lance-index/src/scalar/inverted/index/tests/query.rs index f62c26144ce..99228fa43a1 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/query.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/query.rs @@ -93,7 +93,7 @@ async fn test_prefilter_skips_excluded_partition_postings( let remapper = translated.then(|| Arc::new(OffsetBatchRemapper::default()) as Arc); let reference = - InvertedIndex::load_with_remapping(store, remapper.clone(), &LanceCache::no_cache(), true) + InvertedIndex::load_with_remapping(store, remapper.clone(), &LanceCache::no_cache()) .await .unwrap(); let tokens = Tokens::new(vec!["alpha".to_owned(), "beta".to_owned()], DocType::Text); @@ -145,7 +145,7 @@ async fn test_prefilter_skips_excluded_partition_postings( posting_file: posting_file_path(1), counter: counter.clone(), }); - let index = InvertedIndex::load_with_remapping(store, remapper, &LanceCache::no_cache(), true) + let index = InvertedIndex::load_with_remapping(store, remapper, &LanceCache::no_cache()) .await .unwrap(); // Statistics still cover both partitions. Only candidate posting reads may be skipped. @@ -227,7 +227,7 @@ async fn test_single_partition_merge_preserves_remapping_and_filtering( let remapper = translated.then(|| Arc::new(OffsetBatchRemapper::default()) as Arc); let index = - InvertedIndex::load_with_remapping(source, remapper, &LanceCache::no_cache(), true).await?; + InvertedIndex::load_with_remapping(source, remapper, &LanceCache::no_cache()).await?; let old_row = if translated { 1100 } else { 100 }; let filter = keep_old.map(|keep| { crate::scalar::OldIndexDataFilter::RowIds(if keep { @@ -251,7 +251,7 @@ async fn test_single_partition_merge_preserves_remapping_and_filtering( .await?; // Reload without any translator: maintenance must have persisted the // current old address, while leaving the newly appended address alone. - let updated = InvertedIndex::load(dest, None, &LanceCache::no_cache(), true).await?; + let updated = InvertedIndex::load(dest, None, &LanceCache::no_cache()).await?; let (mut row_ids, _) = updated .bm25_search( Arc::new(Tokens::new(vec!["hit".to_owned()], DocType::Text)), @@ -296,7 +296,7 @@ async fn translated_fts_snapshot_rebinds_current_store_and_releases_request_reso let remapper = Arc::new(OffsetBatchRemapper::default()); let remapper_weak = Arc::downgrade(&remapper); let cache = LanceCache::with_capacity(1 << 20); - let index = InvertedIndex::load_with_remapping(store, Some(remapper.clone()), &cache, true) + let index = InvertedIndex::load_with_remapping(store, Some(remapper.clone()), &cache) .await .unwrap(); index.prewarm().await.unwrap(); @@ -412,10 +412,8 @@ async fn test_request_wrappers_preserve_prewarmed_index_state() { None, &cache, async move { - Ok( - InvertedIndex::load(load_store, None, &load_cache, true).await? - as Arc, - ) + Ok(InvertedIndex::load(load_store, None, &load_cache).await? + as Arc) } .boxed(), ) @@ -456,9 +454,7 @@ async fn test_request_wrappers_preserve_prewarmed_index_state() { Some((4, 2, vec![2, 1])) ); } - let independently_loaded = InvertedIndex::load(store, None, &cache, true) - .await - .unwrap(); + let independently_loaded = InvertedIndex::load(store, None, &cache).await.unwrap(); assert!( !first .unwrap() @@ -589,7 +585,7 @@ async fn test_write_many_posting_list_batches_preserves_all_batches() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -648,7 +644,7 @@ async fn test_and_query_skips_partition_missing_required_term() { write_test_metadata(&store, vec![0, 1], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -702,7 +698,7 @@ async fn test_fuzzy_and_groups_expansions_by_original_position() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); let params = Arc::new( @@ -797,7 +793,7 @@ async fn test_fuzzy_expansion_cap_applies_to_whole_query( write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); let partition = index.partitions[0].clone(); @@ -912,7 +908,7 @@ async fn load_test_index( partition_ids: Vec, ) -> Arc { write_test_metadata(&store, partition_ids, InvertedIndexParams::default()).await; - InvertedIndex::load(store, None, &LanceCache::with_capacity(4096), true) + InvertedIndex::load(store, None, &LanceCache::with_capacity(4096)) .await .unwrap() } @@ -966,7 +962,7 @@ async fn test_sync_df_requires_all_segments_and_preserves_scorer_bits() { .await; write_test_metadata(&first_store, vec![0], InvertedIndexParams::default()).await; let first_cache = Arc::new(LanceCache::with_capacity(4096)); - let first = InvertedIndex::load(first_store, None, first_cache.as_ref(), true) + let first = InvertedIndex::load(first_store, None, first_cache.as_ref()) .await .unwrap(); @@ -979,7 +975,7 @@ async fn test_sync_df_requires_all_segments_and_preserves_scorer_bits() { write_pair_partition(&second_store, 0, &[("alpha", "beta", 200)]).await; write_test_metadata(&second_store, vec![0], InvertedIndexParams::default()).await; let second_cache = Arc::new(LanceCache::with_capacity(4096)); - let second = InvertedIndex::load(second_store, None, second_cache.as_ref(), true) + let second = InvertedIndex::load(second_store, None, second_cache.as_ref()) .await .unwrap(); @@ -1141,9 +1137,7 @@ async fn load_prewarmed_index( ) -> (Arc, LanceCache) { write_test_metadata(&store, partition_ids, params).await; let cache = LanceCache::with_capacity(1 << 20); - let index = InvertedIndex::load(store, None, &cache, true) - .await - .unwrap(); + let index = InvertedIndex::load(store, None, &cache).await.unwrap(); index .prewarm_with_options(&FtsPrewarmOptions::default()) .await @@ -1696,7 +1690,7 @@ async fn test_fuzzy_expansion_cap_is_global_across_partitions() { write_variant_partition(&store, 1, &["alphc", "alphd"], &[102, 103]).await; write_test_metadata(&store, vec![0, 1], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -1819,9 +1813,7 @@ async fn test_fuzzy_results_independent_of_partition_shape() { let mut results = Vec::new(); for store in [single_store, split_store] { let cache = LanceCache::with_capacity(4096); - let index = InvertedIndex::load(store, None, &cache, true) - .await - .unwrap(); + let index = InvertedIndex::load(store, None, &cache).await.unwrap(); let tokens = Arc::new(Tokens::new(vec!["alphx".to_owned()], DocType::Text)); let (row_ids, scores) = index .bm25_search( @@ -1887,7 +1879,7 @@ async fn test_fuzzy_and_scores_grouped_expansions_by_matched_token() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -1946,7 +1938,7 @@ async fn test_grouped_scoring_keeps_exact_winner_outside_proxy_window(#[case] op write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -2007,7 +1999,7 @@ async fn test_fuzzy_and_grouped_rescore_keeps_wand_limit_bounded() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -2103,7 +2095,7 @@ async fn test_phrase_query_reads_legacy_per_doc_positions() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -2156,7 +2148,7 @@ async fn test_exact_single_term_phrase_uses_frequencies_without_positions( partition.write(store.as_ref()).await.unwrap(); write_test_metadata(&store, vec![0], params).await; - let index = InvertedIndex::load(store, None, &LanceCache::with_capacity(1 << 20), true) + let index = InvertedIndex::load(store, None, &LanceCache::with_capacity(1 << 20)) .await .unwrap(); let tokens = Arc::new(Tokens::with_positions( diff --git a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs index ee59cef45a3..a62bc10d61f 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs @@ -56,7 +56,7 @@ async fn test_bm25_search_uses_global_idf() { writer.finish_with_metadata(metadata).await.unwrap(); let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -183,7 +183,7 @@ async fn load_test_index( } write_test_metadata(&store, partition_ids, InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); (tmpdir, cache, index) @@ -246,7 +246,7 @@ async fn load_global_scoring_test_index( let cache = Arc::new(LanceCache::with_backend(Arc::new( QuickCacheBackend::with_capacity(64 * 1024), ))); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); (tmpdir, cache, index) @@ -543,7 +543,7 @@ async fn test_chunked_modern_search_preserves_cold_and_prewarmed_results() { ) .await; let cache = Arc::new(LanceCache::with_capacity(64 * 1024 * 1024)); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); let tokens = Arc::new(Tokens::new(vec!["pipeline".to_owned()], DocType::Text)); @@ -879,7 +879,7 @@ async fn load_no_impact_bulk_conjunction_test_index( let params = InvertedIndexParams::default().with_position(with_positions); write_test_metadata(&store, vec![0, 1], params).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); (tmpdir, cache, index) @@ -1192,7 +1192,7 @@ async fn test_and_query_returns_empty_when_exact_term_missing() { write_test_metadata(&store, vec![0], InvertedIndexParams::default()).await; let cache = Arc::new(LanceCache::with_capacity(4096)); - let index = InvertedIndex::load(store.clone(), None, cache.as_ref(), true) + let index = InvertedIndex::load(store.clone(), None, cache.as_ref()) .await .unwrap(); @@ -1261,7 +1261,7 @@ async fn test_and_query_accepts_same_position_alternatives() { builder.write(store.as_ref()).await.unwrap(); write_test_metadata(&store, vec![0], InvertedIndexParams::code()).await; - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); @@ -1332,7 +1332,7 @@ async fn test_phrase_query_accepts_same_position_alternatives() { InvertedIndexParams::code().with_position(true), ) .await; - let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache(), true) + let index = InvertedIndex::load(store.clone(), None, &LanceCache::no_cache()) .await .unwrap(); diff --git a/rust/lance-index/src/scalar/inverted/index/tests/stats.rs b/rust/lance-index/src/scalar/inverted/index/tests/stats.rs index d85acb3baea..262e813bb8d 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/stats.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/stats.rs @@ -281,7 +281,7 @@ async fn load_counted_v2_index_with_counter( posting_file: posting_file_path(0), counter: counter.clone(), }); - let index = InvertedIndex::load(counting_store, None, &cache, true) + let index = InvertedIndex::load(counting_store, None, &cache) .await .unwrap(); (index, counter, tmpdir) @@ -382,9 +382,7 @@ async fn load_counted_v3_index( posting_file: posting_file_path(partitions[0]), counter: counter.clone(), }); - let index = InvertedIndex::load(store, None, &cache, true) - .await - .unwrap(); + let index = InvertedIndex::load(store, None, &cache).await.unwrap(); assert_eq!(index.format_version(), InvertedListFormatVersion::V3); (index, counter, tmpdir) } @@ -1416,7 +1414,7 @@ async fn load_v2_index_with_grouped_postings( // The inverted list keeps only a `WeakLanceCache`, so the caller must // hold this `Arc` alive for the cache to stay usable. let cache = Arc::new(LanceCache::with_capacity(1 << 30)); - let index = InvertedIndex::load(store, None, cache.as_ref(), true) + let index = InvertedIndex::load(store, None, cache.as_ref()) .await .unwrap(); (index, cache) diff --git a/rust/lance-index/src/scalar/registry.rs b/rust/lance-index/src/scalar/registry.rs index 15090b53017..c6d5e643a3c 100644 --- a/rust/lance-index/src/scalar/registry.rs +++ b/rust/lance-index/src/scalar/registry.rs @@ -1044,10 +1044,10 @@ mod tests { .await .unwrap(); let index_cache = LanceCache::no_cache(); - let index_a = InvertedIndex::load(store_a.clone(), None, &index_cache, true) + let index_a = InvertedIndex::load(store_a.clone(), None, &index_cache) .await .unwrap(); - let index_b = InvertedIndex::load(store_b.clone(), None, &index_cache, true) + let index_b = InvertedIndex::load(store_b.clone(), None, &index_cache) .await .unwrap(); [(store_a, index_a), (store_b, index_b)] From e23ab57fefb45af9ba2e4d5c38c29d67f54592e5 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 30 Nov 2026 15:53:24 -0800 Subject: [PATCH 14/15] refactor(fts): derive a segment's identity column from the version it trains at Review (Will): `train_inverted_index` always stamped `INVERTED_ROW_ADDR_DOMAIN_VERSION` while taking the document identity column as a separate argument that still defaulted to `_rowid`, so the public entry point could write a v4 segment with a legacy column -- a layout the format does not allow, and the same shape as the batch-remap bug found earlier: column and version decided in two places. The version is now the single input. `train_inverted_index_at_version` takes it, derives the column through `identity_column_for_version`, refuses a version this build does not write for the given params, and stamps what it was given; `train_inverted_index` is that at the row-address domain. The training request carries the version rather than the column, so `set_stable_row_ids` settles it before training instead of `build_scalar_index` relabelling afterwards -- `relabel_as_row_id_domain` and its branch there are gone. `InnerBuilder::merge_from` now rejects a column mismatch instead of adopting whichever side looked non-default, and both builders default to the row-address domain like every other default in this PR. Two callers were writing segments nothing could read back: - remap.rs's legacy FTS reindex asked for neither a row id nor a row address, so the rebuilt segment had no identity column at all. It now scans row addresses and picks its version the way `build_scalar_index` does. - mem-WAL flush computed the legacy version with its own copy of the rule and wrote the column from an unrelated default. Both now come from `flushed_index_version`. Also from the same review: - `InvertedIndex::load` rejects a segment whose `docs.lance` column contradicts the domain the manifest declares, instead of reading the wrong numbering system; the doc that claimed this check existed is now true. Fixtures that faked a legacy segment by relabelling alone get real legacy files via `as_legacy_row_id_fts_segment`. - `normalize_inverted_details` errors on a v4 segment with no `posting_format_version` rather than guessing V3: from v4 the two axes are independent, V1 and V2 pair with it, and every writer records the field. - The FTS `stale_rows` translation no longer runs without stable row ids, where the domains coincide and translating would reject a legitimate whole-fragment entry. - Documented why `open_fts_segments` reads the domain from the segment rather than from the check that precedes it. Co-Authored-By: Claude Opus 5 --- rust/lance-index/src/scalar/inverted.rs | 143 ++++++++++-------- .../src/scalar/inverted/builder.rs | 60 ++++---- .../src/scalar/inverted/builder/pipeline.rs | 2 +- .../src/scalar/inverted/documents.rs | 28 +++- .../src/scalar/inverted/index/doc_set.rs | 7 + .../scalar/inverted/index/inverted_index.rs | 71 ++++++--- .../src/scalar/inverted/index/tests.rs | 13 ++ .../scalar/inverted/index/tests/lifecycle.rs | 138 ++++++++++++++++- .../scalar/inverted/index/tests/scoring.rs | 4 +- rust/lance/src/dataset/mem_wal/index/fts.rs | 28 +++- rust/lance/src/dataset/mem_wal/index/tests.rs | 46 +++++- .../tests/dataset_fts_combined_fields.rs | 19 ++- rust/lance/src/index/append.rs | 27 +++- rust/lance/src/index/remap.rs | 20 ++- rust/lance/src/index/scalar.rs | 23 +-- rust/lance/src/index/scalar/inverted.rs | 33 ++-- rust/lance/src/index/tests/optimize.rs | 8 +- rust/lance/src/io/exec/fts/combined_fields.rs | 26 ++-- rust/lance/src/io/exec/fts/segments.rs | 9 ++ rust/lance/src/utils/test.rs | 113 ++++++++++++++ 20 files changed, 638 insertions(+), 180 deletions(-) diff --git a/rust/lance-index/src/scalar/inverted.rs b/rust/lance-index/src/scalar/inverted.rs index 18f6ca7ceb6..d010066e838 100644 --- a/rust/lance-index/src/scalar/inverted.rs +++ b/rust/lance-index/src/scalar/inverted.rs @@ -493,10 +493,15 @@ use super::IndexStore; pub struct InvertedIndexPlugin; impl InvertedIndexPlugin { - /// Train a segment that writes its document identities under the legacy - /// [`ROW_ID`] column. Callers that know the segment will keep - /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] should use - /// [`Self::train_inverted_index_in_domain`] with [`ROW_ADDR`] instead. + /// Train a segment in the row-address domain, at + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]. + /// + /// The training data must carry [`ROW_ADDR`], which is also the column the + /// segment stores its document identities under. A caller on a dataset + /// without stable row ids -- where a row id and a row address are the same + /// value, so an older reader can still be served -- passes + /// [`Self::legacy_index_version`] to + /// [`Self::train_inverted_index_at_version`] instead. pub async fn train_inverted_index( data: SendableRecordBatchStream, index_store: &dyn IndexStore, @@ -504,29 +509,34 @@ impl InvertedIndexPlugin { fragment_ids: Option>, progress: Arc, ) -> Result { - Self::train_inverted_index_in_domain( + Self::train_inverted_index_at_version( data, index_store, params, fragment_ids, progress, - ROW_ID, + INVERTED_ROW_ADDR_DOMAIN_VERSION, ) .await } - /// Like [`Self::train_inverted_index`], naming the document identity - /// column explicitly. The name must match the `index_version` the - /// finished segment is committed with: [`ROW_ADDR`] for - /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`], [`ROW_ID`] for a segment - /// relabelled to a legacy version. - pub async fn train_inverted_index_in_domain( + /// Like [`Self::train_inverted_index`], committing the finished segment at + /// `index_version`. + /// + /// The version is the single input that decides the stored layout: the + /// document identity column follows from it through + /// [`Self::identity_column_for_version`], so a segment can never be + /// labelled one way and written the other. `index_version` must be one + /// this build writes for `params` -- either + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] or the pre-migration + /// [`Self::legacy_index_version`] for them. + pub async fn train_inverted_index_at_version( data: SendableRecordBatchStream, index_store: &dyn IndexStore, params: InvertedIndexParams, fragment_ids: Option>, progress: Arc, - identity_column: &'static str, + index_version: u32, ) -> Result { let fragment_mask = fragment_ids.as_ref().and_then(|frag_ids| { if !frag_ids.is_empty() { @@ -540,58 +550,59 @@ impl InvertedIndexPlugin { }); params.validate_format_version()?; + let legacy_version = Self::legacy_index_version(¶ms); + if index_version != INVERTED_ROW_ADDR_DOMAIN_VERSION && index_version != legacy_version { + return Err(Error::invalid_input(format!( + "cannot train an FTS segment at index_version {index_version}: this build \ + writes {INVERTED_ROW_ADDR_DOMAIN_VERSION} (the row-address domain) or \ + {legacy_version} (the pre-migration version for these parameters)" + ))); + } let details = pbold::InvertedIndexDetails::try_from(¶ms)?; let mut inverted_index = InvertedIndexBuilder::new_with_fragment_mask(params, fragment_mask) .with_progress(progress) - .with_identity_column(identity_column); + .at_index_version(index_version); let files = inverted_index.update(data, index_store, None).await?; Ok(CreatedIndex { index_details: prost_types::Any::from_msg(&details).unwrap(), - // Training always scans row addresses now (see - // `InvertedIndexTrainingRequest`); `build_scalar_index` relabels - // this back to the legacy row-id-domain version (via - // `relabel_as_row_id_domain`) on a dataset without stable row - // ids, where a row id and a row address are the same value. - index_version: INVERTED_ROW_ADDR_DOMAIN_VERSION, + index_version, files, }) } - /// The format-and-granularity-appropriate version for a freshly trained - /// segment on a dataset without stable row ids, where a row id and a row - /// address are the same value. + /// The column a segment committed at `index_version` stores its document + /// identities under. /// - /// List-element-granularity documents require the V3 reader capability - /// (element-document coordinates) regardless of the configured posting - /// format; every other segment keeps the version implied by its posting - /// format. - fn legacy_index_version(is_element_document: bool, posting_format_version: u32) -> u32 { - if is_element_document { - INVERTED_INDEX_VERSION_V3 + /// The two are one decision, never two: from + /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] a segment holds physical row + /// addresses and names the column [`ROW_ADDR`]; below it the column holds + /// row ids under [`ROW_ID`], the name an older reader looks for. Deriving + /// the name here is what keeps a v4 segment from being written with a + /// `_rowid` column, which the format does not allow. + pub fn identity_column_for_version(index_version: u32) -> &'static str { + if index_version >= INVERTED_ROW_ADDR_DOMAIN_VERSION { + ROW_ADDR } else { - posting_format_version + ROW_ID } } - /// Relabel a freshly trained Inverted segment in the pre-migration - /// row-id-domain format. + /// The version a freshly trained segment takes on a dataset without stable + /// row ids, where a row id and a row address are the same value so the + /// trained data is identical in either domain. /// - /// Only valid on a dataset without stable row ids, where a row address and - /// a row id are the same value, so the segment's trained data is - /// identical in either domain. Mirrors the plain BTree/Bitmap/LabelList - /// relabeling in `build_scalar_index`, and keeps the segment readable by - /// builds that predate [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]. - pub fn relabel_as_row_id_domain(created: &mut CreatedIndex) -> Result<()> { - let details = pbold::InvertedIndexDetails::decode(created.index_details.value.as_slice())?; - let is_element_document = - DocumentGranularity::try_from(details.document_granularity)?.is_list_element(); - let posting_format_version = details - .posting_format_version - .unwrap_or_else(|| default_fts_format_version().index_version()); - created.index_version = - Self::legacy_index_version(is_element_document, posting_format_version); - Ok(()) + /// Writing that version instead of [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] + /// keeps the segment readable by builds predating the migration. It is the + /// version implied by the posting format, except that + /// list-element-granularity documents require the V3 reader capability + /// (element-document coordinates) whatever the posting format. + pub fn legacy_index_version(params: &InvertedIndexParams) -> u32 { + if params.get_document_granularity().is_list_element() { + INVERTED_INDEX_VERSION_V3 + } else { + params.resolved_format_version().index_version() + } } /// Return true if the query can be used to speed up contains_tokens queries @@ -606,19 +617,20 @@ impl InvertedIndexPlugin { struct InvertedIndexTrainingRequest { parameters: InvertedIndexParams, criteria: TrainingCriteria, - /// The column the trained segment writes document identities under. The - /// caller sets [`ROW_ADDR`] when the segment will keep - /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`]; it stays [`ROW_ID`] when the - /// segment will be relabelled to a legacy version, where an old reader - /// expects that name and the two domains coincide anyway. - identity_column: &'static str, + /// The `index_version` the trained segment will be committed with, which + /// also decides the column it writes document identities under (see + /// [`InvertedIndexPlugin::identity_column_for_version`]). Defaults to the + /// row-address domain the training data is always scanned in; + /// [`TrainingRequest::set_stable_row_ids`] lowers it where an older reader + /// can still be served. + index_version: u32, } impl InvertedIndexTrainingRequest { pub fn new(parameters: InvertedIndexParams) -> Self { Self { parameters, - identity_column: ROW_ID, + index_version: INVERTED_ROW_ADDR_DOMAIN_VERSION, criteria: TrainingCriteria::new(TrainingOrdering::None).with_row_addr(), } } @@ -626,13 +638,16 @@ impl InvertedIndexTrainingRequest { impl TrainingRequest for InvertedIndexTrainingRequest { fn set_stable_row_ids(&mut self, stable_row_ids: bool) { - // Without stable row ids `build_scalar_index` relabels the finished - // segment to a pre-`INVERTED_ROW_ADDR_DOMAIN_VERSION` version so an - // older reader still understands it -- and that reader looks for - // `ROW_ID`. The two domains coincide there, so the legacy name is - // truthful. With stable row ids the segment keeps version 4 and names - // the column for what it actually holds. - self.identity_column = if stable_row_ids { ROW_ADDR } else { ROW_ID }; + // Training always scans row addresses. Without stable row ids a row id + // is that same value, so the segment can be committed in the + // pre-migration format an older reader still understands -- and + // naming the version here, before training, is what makes it write + // that format's `ROW_ID` column too. + self.index_version = if stable_row_ids { + INVERTED_ROW_ADDR_DOMAIN_VERSION + } else { + InvertedIndexPlugin::legacy_index_version(&self.parameters) + }; } fn as_any(&self) -> &dyn std::any::Any { @@ -695,13 +710,13 @@ impl BasicTrainer for InvertedIndexPlugin { "must provide training request created by new_training_request".into(), ) })?; - Self::train_inverted_index_in_domain( + Self::train_inverted_index_at_version( data, index_store, request.parameters.clone(), fragment_ids, progress, - request.identity_column, + request.index_version, ) .await } diff --git a/rust/lance-index/src/scalar/inverted/builder.rs b/rust/lance-index/src/scalar/inverted/builder.rs index 7ba2a38f786..65117081cdf 100644 --- a/rust/lance-index/src/scalar/inverted/builder.rs +++ b/rust/lance-index/src/scalar/inverted/builder.rs @@ -225,10 +225,11 @@ pub struct InvertedIndexBuilder { src_store: Option>, progress: Arc, deleted_fragments: RoaringBitmap, - /// The column documents' identities are written under. Defaults to the - /// legacy `ROW_ID`; a build committed as - /// `INVERTED_ROW_ADDR_DOMAIN_VERSION` sets `ROW_ADDR` via - /// [`Self::with_identity_column`]. + /// The column documents' identities are written under, derived from the + /// `index_version` the build will be committed at (see + /// [`Self::at_index_version`]). Defaults to the row-address domain every + /// fresh build is committed in, so only a build that will be labelled a + /// pre-migration version has to say so. identity_column: &'static str, } @@ -275,16 +276,21 @@ impl InvertedIndexBuilder { posting_tail_codec: format_version.posting_tail_codec(), progress: noop_progress(), deleted_fragments, - identity_column: ROW_ID, + identity_column: ROW_ADDR, } } - /// Write documents' identities under `identity_column`. Must agree with - /// the `index_version` the finished segment is committed with: from - /// `INVERTED_ROW_ADDR_DOMAIN_VERSION` that is [`ROW_ADDR`], and a build - /// relabelled down to a legacy version keeps [`ROW_ID`]. - pub fn with_identity_column(mut self, identity_column: &'static str) -> Self { - self.identity_column = identity_column; + /// Build a segment that will be committed at `index_version`, which decides + /// the column documents' identities are written under. + /// + /// Taking the version rather than the column is what keeps the two from + /// being chosen in different places and disagreeing -- see + /// [`InvertedIndexPlugin::identity_column_for_version`](crate::scalar::inverted::InvertedIndexPlugin::identity_column_for_version). + pub fn at_index_version(mut self, index_version: u32) -> Self { + self.identity_column = + crate::scalar::inverted::InvertedIndexPlugin::identity_column_for_version( + index_version, + ); self } @@ -1189,10 +1195,11 @@ pub struct InnerBuilder { pub(super) tokens: TokenDictionary, pub(crate) posting_lists: Vec, pub(crate) docs: DocSet, - /// The column the documents' identities are written under. Defaults to - /// the legacy [`ROW_ID`]; a build that will be labelled - /// [`INVERTED_ROW_ADDR_DOMAIN_VERSION`](super::INVERTED_ROW_ADDR_DOMAIN_VERSION) - /// sets [`ROW_ADDR`] through [`Self::with_identity_column`]. + /// The column the documents' identities are written under, which follows + /// the `index_version` the build will be committed at. Defaults to + /// [`ROW_ADDR`] like [`InvertedIndexBuilder`]; the build sets it through + /// [`Self::with_identity_column`], and a partition reloaded for a rewrite + /// keeps the name its own file carries. identity_column: &'static str, } @@ -1257,7 +1264,7 @@ impl InnerBuilder { tokens: TokenDictionary::default(), posting_lists: Vec::new(), docs: DocSet::default(), - identity_column: ROW_ID, + identity_column: ROW_ADDR, } } @@ -1420,15 +1427,16 @@ impl InnerBuilder { identity_column, } = other; - // A merged partition writes one schema, so the name is taken from - // whichever side actually came from a persisted segment: a freshly - // built partition still carries the default until the build is told - // which to use, and consolidation merges those into partitions loaded - // from files. `write_docs` uses the accumulating builder's name, so - // adopting a non-default incoming one keeps a rewrite on the name its - // source was read under. - if identity_column != ROW_ID { - self.identity_column = identity_column; + // A merged partition writes one schema, and every partition in one + // operation is built at a single `index_version`, so the two names + // always agree. Checking rather than adopting one side is what stops a + // mismatch from being silently resolved into a segment whose column + // contradicts its version. + if self.identity_column != identity_column { + return Err(Error::index(format!( + "cannot merge partitions with mismatched document identity columns: {} vs {}", + self.identity_column, identity_column + ))); } if self.with_position != with_position { @@ -2586,7 +2594,7 @@ pub(crate) fn posting_file_path(partition_id: u64) -> String { format!("part_{}_{}", partition_id, INVERT_LIST_FILE) } -pub(crate) fn doc_file_path(partition_id: u64) -> String { +pub fn doc_file_path(partition_id: u64) -> String { format!("part_{}_{}", partition_id, DOCS_FILE) } diff --git a/rust/lance-index/src/scalar/inverted/builder/pipeline.rs b/rust/lance-index/src/scalar/inverted/builder/pipeline.rs index b0d69595bb8..d0ebd0435ca 100644 --- a/rust/lance-index/src/scalar/inverted/builder/pipeline.rs +++ b/rust/lance-index/src/scalar/inverted/builder/pipeline.rs @@ -949,7 +949,7 @@ mod tests { .await?; assert_eq!(docs.num_rows(), 384); let batch = docs.read_range(0..384, None).await?; - let mut rows = batch[lance_core::ROW_ID] + let mut rows = batch[lance_core::ROW_ADDR] .as_primitive::() .values() .to_vec(); diff --git a/rust/lance-index/src/scalar/inverted/documents.rs b/rust/lance-index/src/scalar/inverted/documents.rs index 0327e7635c6..31cfe3066f9 100644 --- a/rust/lance-index/src/scalar/inverted/documents.rs +++ b/rust/lance-index/src/scalar/inverted/documents.rs @@ -1255,6 +1255,11 @@ pub(super) struct PartitionDocuments { coordinate_rank: usize, persisted_total_tokens: Option, quantized_scoring: bool, + /// The column this file names its document identities with, resolved once + /// at load ([`docs_identity_column_of`]) so every read of the file agrees + /// and `InvertedIndex::load` can check it against the domain the manifest + /// declares. + identity_column: &'static str, /// Legacy synchronous remapper (index_version 0). Mutually exclusive with /// `batch_remapper`; both `None` means no translation is needed. remapper: Option>, @@ -1299,6 +1304,16 @@ impl PartitionDocumentStore { } } + /// The column the partition's file names its document identities with, + /// which `InvertedIndex::load` checks against the domain the manifest + /// declared for the segment. + pub(crate) fn identity_column(&self) -> &'static str { + match self { + Self::Legacy(docs) => docs.identity_column(), + Self::Modern(docs) => docs.identity_column(), + } + } + pub(crate) fn legacy(&self) -> Option<&Arc> { match self { Self::Legacy(docs) => Some(docs), @@ -1570,6 +1585,7 @@ impl PartitionDocuments { .transpose()?; let coordinate_rank = document_coordinate_rank(&arrow_schema::Schema::from(reader.schema())); + let identity_column = docs_identity_column_of(reader)?; Ok(Self { store, path, @@ -1579,6 +1595,7 @@ impl PartitionDocuments { coordinate_rank, persisted_total_tokens, quantized_scoring, + identity_column, remapper, batch_remapper: None, lengths: Arc::new(OnceCell::new()), @@ -1636,6 +1653,7 @@ impl PartitionDocuments { coordinate_rank: self.coordinate_rank, persisted_total_tokens: self.persisted_total_tokens, quantized_scoring: self.quantized_scoring, + identity_column: self.identity_column, remapper, batch_remapper, lengths: self.lengths.clone(), @@ -1649,6 +1667,10 @@ impl PartitionDocuments { self.num_docs } + pub(crate) fn identity_column(&self) -> &'static str { + self.identity_column + } + /// Raw partition files are reusable only if maintenance needs neither /// address translation nor removal of any persisted document. pub(crate) async fn can_copy_unchanged( @@ -1728,6 +1750,7 @@ impl PartitionDocuments { let store = self.store.clone(); let path = self.path.clone(); let num_docs = self.num_docs; + let identity = self.identity_column; let cached = index_cache .get_or_insert_with_key( DocRowIdsKey { @@ -1735,7 +1758,6 @@ impl PartitionDocuments { }, || async move { let reader = store.open_index_file(&path).await?; - let identity = docs_identity_column_of(reader.as_ref())?; let batch = reader.read_range(0..num_docs, Some(&[identity])).await?; let row_ids = required_u64_column(&batch, identity, &path)?; if row_ids.null_count() != 0 { @@ -2032,7 +2054,7 @@ impl PartitionDocuments { }) .collect::>(); let reader = self.reader().await?; - let identity = docs_identity_column_of(reader.as_ref())?; + let identity = self.identity_column; let batch = reader .read_ranges(&ranges, Some(&[identity, NUM_TOKEN_COL])) .await?; @@ -2274,7 +2296,7 @@ impl PartitionDocuments { .get_or_try_init(|| async { if self.lengths.get().is_none() && self.projection.get().is_none() { let reader = self.reader().await?; - let identity = docs_identity_column_of(reader.as_ref())?; + let identity = self.identity_column; let batch = reader .read_range(0..self.num_docs, Some(&[identity, NUM_TOKEN_COL])) .await?; diff --git a/rust/lance-index/src/scalar/inverted/index/doc_set.rs b/rust/lance-index/src/scalar/inverted/index/doc_set.rs index fd2e3fc8fbc..439f74e2ade 100644 --- a/rust/lance-index/src/scalar/inverted/index/doc_set.rs +++ b/rust/lance-index/src/scalar/inverted/index/doc_set.rs @@ -247,6 +247,13 @@ pub struct DocSet { pub(super) identity_column: &'static str, } +impl DocSet { + /// The column this set's documents are (or will be) stored under. + pub(crate) fn identity_column(&self) -> &'static str { + self.identity_column + } +} + impl DeepSizeOf for DocSet { fn deep_size_of_children(&self, context: &mut lance_core::deepsize::Context) -> usize { self.row_ids.deep_size_of_children(context) diff --git a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs index 2180a85cf62..fd44ceae12f 100644 --- a/rust/lance-index/src/scalar/inverted/index/inverted_index.rs +++ b/rust/lance-index/src/scalar/inverted/index/inverted_index.rs @@ -55,10 +55,10 @@ enum InvertedLoadRemapping { /// builder exists only so the rare legacy load can name its domain. /// /// The domain carried here is the one the *manifest* declares through -/// `index_version`, which the segment's own `docs.lance` identity column is -/// then checked against. Defaulting it to row addresses -- what every build -/// from [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] onward writes -- leaves only the -/// legacy segments spelling their domain out. +/// `index_version`; the load rejects a segment whose `docs.lance` names the +/// other domain's column, so the two cannot disagree past this point. Defaulting it to row addresses -- what every +/// build from [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] onward writes -- leaves +/// only the legacy segments spelling their domain out. #[must_use = "a load does nothing until it is awaited"] pub struct InvertedIndexLoad<'a> { store: Arc, @@ -139,6 +139,42 @@ impl DeepSizeOf for InvertedIndex { } impl InvertedIndex { + /// Reject a segment whose `docs.lance` names its identity column for one + /// domain while the manifest declares the other. + /// + /// The two are written from a single `index_version` + /// ([`InvertedIndexPlugin::identity_column_for_version`]), so a + /// disagreement means the segment was produced by something other than + /// that path -- and the numbers inside are `u64` either way, so without + /// this check the mismatch would be read as the wrong numbering system + /// rather than reported. + fn check_identity_domain( + partitions: &[Arc], + results_are_row_addresses: bool, + ) -> Result<()> { + let expected = if results_are_row_addresses { + ROW_ADDR + } else { + ROW_ID + }; + for partition in partitions { + let found = partition.docs.identity_column(); + if found != expected { + return Err(Error::index(format!( + "FTS partition {} stores its document identities under `{found}`, but this \ + segment is declared in the {} domain, whose column is `{expected}`", + partition.id(), + if results_are_row_addresses { + "row-address" + } else { + "row-id" + }, + ))); + } + } + Ok(()) + } + pub(super) fn format_version(&self) -> InvertedListFormatVersion { self.format_version } @@ -159,19 +195,6 @@ impl InvertedIndex { } } - /// The column this index's documents' identities are stored under, which - /// tracks [`Self::index_version`] exactly: both switch on - /// `results_are_row_addresses`. A segment rewritten from this one -- a - /// merge or a remap -- keeps this index's version, so it has to keep this - /// name too. - pub(super) fn identity_column(&self) -> &'static str { - if self.results_are_row_addresses { - ROW_ADDR - } else { - ROW_ID - } - } - fn posting_tail_codec(&self) -> PostingTailCodec { self.partitions .first() @@ -188,12 +211,12 @@ impl InvertedIndex { } /// Every builder derived from an opened index inherits that index's - /// identity column (see [`Self::identity_column`]): a rewrite keeps the - /// source's `index_version`, so it must keep the matching column name, and - /// setting it here means no rewrite path can omit it. + /// `index_version`: a rewrite keeps it, so it must keep the matching + /// identity column name, and setting it here means no rewrite path can + /// omit it. fn to_builder_with_offset(&self, fragment_mask: Option) -> InvertedIndexBuilder { self.to_builder_with_offset_inner(fragment_mask) - .with_identity_column(self.identity_column()) + .at_index_version(self.index_version()) } fn to_builder_with_offset_inner(&self, fragment_mask: Option) -> InvertedIndexBuilder { @@ -351,7 +374,7 @@ impl InvertedIndex { .with_progress(progress) .with_token_set_format(first.token_set_format) .with_format_version(first.format_version()) - .with_identity_column(first.identity_column()) + .at_index_version(first.index_version()) .update_from_segments(new_data, dest_store, segments, old_data_filters) .await? }; @@ -802,6 +825,8 @@ impl InvertedIndex { DocumentGranularity::ListElement }; + Self::check_identity_domain(&partitions, results_are_row_addresses)?; + let tokenizer = params.build()?; Ok(Arc::new(Self { params, @@ -931,6 +956,8 @@ impl InvertedIndex { DocumentGranularity::ListElement }; + Self::check_identity_domain(&partitions, results_are_row_addresses)?; + let tokenizer = params.build()?; Ok(Arc::new(Self { params, diff --git a/rust/lance-index/src/scalar/inverted/index/tests.rs b/rust/lance-index/src/scalar/inverted/index/tests.rs index 729cf25ccc8..0d58cace5e3 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests.rs @@ -53,12 +53,25 @@ async fn write_single_partition_index( ) -> Result> { let block_size = params.posting_block_size(); let format_version = params.resolved_format_version(); + // The fixture is loaded below in the domain `results_are_row_addresses` + // names, so its docs file has to carry that domain's column -- a segment + // whose file and declared version disagree is rejected at load, which is + // the point of writing it coherently here. let mut partition = InnerBuilder::new_with_format_version_and_block_size( 0, false, token_set_format, format_version, block_size, + ) + .with_identity_column( + crate::scalar::inverted::InvertedIndexPlugin::identity_column_for_version( + if results_are_row_addresses { + crate::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION + } else { + 0 + }, + ), ); partition.tokens.get_or_add(token); let mut posting_list = PostingListBuilder::new_with_posting_tail_codec_and_block_size( diff --git a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs index ed7da1b7305..77c467ada4e 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/lifecycle.rs @@ -2,6 +2,8 @@ // SPDX-FileCopyrightText: Copyright The Lance Authors use super::*; +use crate::progress::NoopIndexBuildProgress; +use crate::scalar::inverted::InvertedIndexPlugin; use lance_core::ROW_ADDR; use crate::Index; @@ -177,8 +179,11 @@ async fn test_update_preserves_v2_format_version() -> Result<()> { let format_version = InvertedListFormatVersion::V2; let posting_tail_codec = format_version.posting_tail_codec(); + // A genuine pre-migration segment: it is loaded below as a legacy V2 + // index, so its docs file has to carry the legacy identity column too. let mut partition = - InnerBuilder::new_with_format_version(0, false, TokenSetFormat::default(), format_version); + InnerBuilder::new_with_format_version(0, false, TokenSetFormat::default(), format_version) + .with_identity_column(lance_core::ROW_ID); partition.tokens.get_or_add("hello"); let mut posting_list = PostingListBuilder::new_with_posting_tail_codec(false, posting_tail_codec); @@ -267,13 +272,16 @@ async fn test_block_size_256_writes_v3_metadata_and_index_version() -> Result<() let format_version = params.resolved_format_version(); assert_eq!(format_version, InvertedListFormatVersion::V3); + // Loaded below as a legacy V3 segment, so the file carries that domain's + // identity column. let mut partition = InnerBuilder::new_with_format_version_and_block_size( 0, false, TokenSetFormat::default(), format_version, params.posting_block_size(), - ); + ) + .with_identity_column(lance_core::ROW_ID); partition.tokens.get_or_add("hello"); let mut posting_list = PostingListBuilder::new_with_posting_tail_codec_and_block_size( false, @@ -646,3 +654,129 @@ async fn fts_total_hits_resident_evidence_and_overlapping_partitions() -> Result ); Ok(()) } + +/// A segment's document identity column is derived from the `index_version` it +/// is trained at, never chosen beside it, so the public training entry points +/// cannot produce a row-address-domain segment that names its column `_rowid` +/// (the shape of the batch-remap bug, and a layout the format does not allow). +#[rstest::rstest] +#[case::row_address_domain(false)] +#[case::legacy(true)] +#[tokio::test] +async fn train_names_the_identity_column_for_its_version(#[case] legacy: bool) -> Result<()> { + let dir = TempObjDir::default(); + let store = Arc::new(LanceIndexStore::new( + ObjectStore::local().into(), + dir.clone(), + Arc::new(LanceCache::no_cache()), + )); + let params = InvertedIndexParams::default(); + let (expected_version, expected_column) = if legacy { + ( + InvertedIndexPlugin::legacy_index_version(¶ms), + lance_core::ROW_ID, + ) + } else { + (INVERTED_ROW_ADDR_DOMAIN_VERSION, ROW_ADDR) + }; + let at_version = legacy.then_some(expected_version); + let created = match at_version { + None => { + InvertedIndexPlugin::train_inverted_index( + identity_training_stream(), + store.as_ref(), + params, + None, + Arc::new(NoopIndexBuildProgress), + ) + .await? + } + Some(version) => { + InvertedIndexPlugin::train_inverted_index_at_version( + identity_training_stream(), + store.as_ref(), + params, + None, + Arc::new(NoopIndexBuildProgress), + version, + ) + .await? + } + }; + assert_eq!(created.index_version, expected_version); + + let cache = LanceCache::no_cache(); + let load = InvertedIndex::load(store.clone(), None, &cache); + let index = if expected_column == ROW_ADDR { + load.await? + } else { + load.in_legacy_row_id_domain().await? + }; + assert_eq!(index.index_version(), expected_version); + // Read the column off the file rather than the loaded index, whose own + // name is derived from the declared version and so would agree either way. + for partition in &index.partitions { + let reader = store + .open_index_file(&crate::scalar::inverted::builder::doc_file_path( + partition.id(), + )) + .await?; + assert_eq!( + crate::scalar::inverted::documents::docs_identity_column_of(reader.as_ref())?, + expected_column, + "a segment at version {expected_version} must store identities under \ + {expected_column}" + ); + } + Ok(()) +} + +/// Training refuses a version this build does not write, rather than labelling +/// a segment something its contents do not match. +#[tokio::test] +async fn train_rejects_a_version_it_does_not_write() { + let dir = TempObjDir::default(); + let store = Arc::new(LanceIndexStore::new( + ObjectStore::local().into(), + dir.clone(), + Arc::new(LanceCache::no_cache()), + )); + let result = InvertedIndexPlugin::train_inverted_index_at_version( + identity_training_stream(), + store.as_ref(), + InvertedIndexParams::default(), + None, + Arc::new(NoopIndexBuildProgress), + INVERTED_ROW_ADDR_DOMAIN_VERSION + 1, + ) + .await; + let Err(error) = result else { + panic!("a version this build does not write must be refused"); + }; + assert!( + error.to_string().contains("cannot train an FTS segment"), + "unexpected error: {error}" + ); +} + +fn identity_training_stream() -> SendableRecordBatchStream { + let schema = Arc::new(Schema::new(vec![ + Field::new("doc", DataType::Utf8, true), + Field::new(ROW_ADDR, DataType::UInt64, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(StringArray::from(vec![Some("hello world"), Some("hello")])), + Arc::new(UInt64Array::from(vec![ + u64::from(lance_core::utils::address::RowAddress::new_from_parts(1, 0)), + u64::from(lance_core::utils::address::RowAddress::new_from_parts(1, 1)), + ])), + ], + ) + .unwrap(); + Box::pin(RecordBatchStreamAdapter::new( + schema, + stream::iter(vec![Ok(batch)]), + )) +} diff --git a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs index a62bc10d61f..5fc121dbde4 100644 --- a/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs +++ b/rust/lance-index/src/scalar/inverted/index/tests/scoring.rs @@ -144,7 +144,9 @@ async fn write_test_partition_with_optional_impacts_and_positions( token_writer.write_record_batch(token_batch).await.unwrap(); token_writer.finish().await.unwrap(); - let doc_batch = docs.to_batch(lance_core::ROW_ID).unwrap(); + // These fixtures are loaded in the default row-address domain, so their + // docs file has to name the column that domain uses. + let doc_batch = docs.to_batch(ROW_ADDR).unwrap(); let mut doc_writer = store .new_index_file(&doc_file_path(partition_id), doc_batch.schema()) .await diff --git a/rust/lance/src/dataset/mem_wal/index/fts.rs b/rust/lance/src/dataset/mem_wal/index/fts.rs index 29bffe31ea9..58fb78a6b18 100644 --- a/rust/lance/src/dataset/mem_wal/index/fts.rs +++ b/rust/lance/src/dataset/mem_wal/index/fts.rs @@ -73,7 +73,6 @@ use rustc_hash::{FxHashMap, FxHashSet}; use lance_index::IndexType; use lance_index::pbold; -use lance_index::scalar::inverted::INVERTED_INDEX_VERSION_V3; use lance_index::scalar::lance_format::LanceIndexStore; use lance_index::scalar::registry::{TrainingCriteria, TrainingOrdering}; use prost::Message as _; @@ -3004,6 +3003,14 @@ impl FtsMemIndex { /// Stored documents are kept in insert order and retain their positions in /// the forward-written flush data file. `total_rows` is used only to /// validate positions. + /// The `index_version` a flushed segment is committed at, and so also the + /// column it writes document identities under. A flushed mem-WAL segment + /// stays in the pre-migration domain, which + /// [`InvertedIndexPlugin::legacy_index_version`] defines for these params. + pub(crate) fn flushed_index_version(&self) -> u32 { + lance_index::scalar::inverted::InvertedIndexPlugin::legacy_index_version(&self.params) + } + pub fn to_index_builder( &self, partition_id: u64, @@ -3018,6 +3025,13 @@ impl FtsMemIndex { let format_version = self.params.resolved_format_version(); let posting_tail_codec = format_version.posting_tail_codec(); let total_rows_u64 = total_rows as u64; + // The column follows the version this segment will be committed at, so + // the two cannot disagree -- `InvertedIndex::load` rejects a segment + // where they do. + let identity_column = + lance_index::scalar::inverted::InvertedIndexPlugin::identity_column_for_version( + self.flushed_index_version(), + ); // Step 1: collect (document key, num_tokens) for every doc across all // immutable partitions and the visible tail. @@ -3040,7 +3054,8 @@ impl FtsMemIndex { Default::default(), format_version, block_size, - )); + ) + .with_identity_column(identity_column)); } // Step 2: assign doc_ids in ascending insert-position order while @@ -3157,7 +3172,8 @@ impl FtsMemIndex { Default::default(), format_version, block_size, - ); + ) + .with_identity_column(identity_column); builder.set_tokens(tokens); builder.set_docs(docs); builder.set_posting_lists(posting_lists); @@ -5376,11 +5392,7 @@ impl MemIndex for FtsMemIndex { let details = prost_types::Any::from_msg(&pbold::InvertedIndexDetails::try_from(&self.params)?) .map_err(|e| Error::internal(format!("failed to encode index details: {e}")))?; - let index_version = if self.params.get_document_granularity().is_list_element() { - INVERTED_INDEX_VERSION_V3 - } else { - self.params.resolved_format_version().index_version() - }; + let index_version = self.flushed_index_version(); Ok(FlushOutcome::Wrote(Box::new(generation.index_metadata( uuid, vec![self.field_id], diff --git a/rust/lance/src/dataset/mem_wal/index/tests.rs b/rust/lance/src/dataset/mem_wal/index/tests.rs index 072e771435d..fafd97e008d 100644 --- a/rust/lance/src/dataset/mem_wal/index/tests.rs +++ b/rust/lance/src/dataset/mem_wal/index/tests.rs @@ -755,14 +755,13 @@ fn fts_from_metadata_preserves_format_version() { let arrow_schema = create_test_schema(); let schema = LanceSchema::try_from(arrow_schema.as_ref()).unwrap(); + // Below INVERTED_ROW_ADDR_DOMAIN_VERSION the posting format is implied by + // the index version, so metadata without it still resolves. for (index_version, expected_format_version) in [ (0, InvertedListFormatVersion::V1), (1, InvertedListFormatVersion::V1), (2, InvertedListFormatVersion::V2), (3, InvertedListFormatVersion::V3), - // INVERTED_ROW_ADDR_DOMAIN_VERSION: orthogonal to the posting-list - // format, which defaults to V3 for it just as it does for V3 itself. - (4, InvertedListFormatVersion::V3), ] { let config = FtsMemIndexPlugin::resolve_from_metadata( "fts_idx", @@ -777,6 +776,47 @@ fn fts_from_metadata_preserves_format_version() { expected_format_version ); } + + // From INVERTED_ROW_ADDR_DOMAIN_VERSION the two axes are independent, so + // the posting format is read from the details and any of them can pair + // with version 4. + for expected_format_version in [ + InvertedListFormatVersion::V1, + InvertedListFormatVersion::V2, + InvertedListFormatVersion::V3, + ] { + let details = pbold::InvertedIndexDetails { + posting_format_version: Some(expected_format_version.index_version()), + ..Default::default() + }; + let config = FtsMemIndexPlugin::resolve_from_metadata( + "fts_idx", + &schema, + &fts_index_metadata_with_details(4, Some(details)), + ) + .unwrap(); + let config = fts_params(&config); + assert_eq!( + config.params.resolved_format_version(), + expected_format_version + ); + } +} + +/// From INVERTED_ROW_ADDR_DOMAIN_VERSION the posting format is no longer +/// implied by the index version, and every writer of such a segment records +/// it, so metadata missing it is rejected rather than guessed at. +#[test] +fn fts_from_metadata_rejects_a_row_address_segment_without_a_posting_format() { + let arrow_schema = create_test_schema(); + let schema = LanceSchema::try_from(arrow_schema.as_ref()).unwrap(); + let err = FtsMemIndexPlugin::resolve_from_metadata("fts_idx", &schema, &fts_index_metadata(4)) + .unwrap_err(); + assert!( + err.to_string() + .contains("records no posting_format_version"), + "{err}" + ); } #[test] diff --git a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs index dfae8f0192b..4876697ef2d 100644 --- a/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs +++ b/rust/lance/src/dataset/tests/dataset_fts_combined_fields.rs @@ -2780,12 +2780,29 @@ async fn legacy_row_id_segment( .remap(&RowAddrRemap::direct(addr_to_row_id), &store) .await .unwrap(); - lance_table::format::IndexMetadata { + // The remap inherits the source segment's identity column along with its + // version; relabelling to 3 also means naming that version's column, or + // the segment is rejected at load for contradicting itself. + crate::utils::test::rewrite_fts_docs_to_row_id_column(ds, &uuid) + .await + .unwrap(); + let segment = lance_table::format::IndexMetadata { uuid, index_version: 3, index_details: Some(Arc::new(created.index_details)), files: Some(index_files_to_table(created.files)), ..meta + }; + // The rewrite changed the files, so the recorded sizes have to follow. + match crate::index::scalar::inverted::finalize_segment_files_if_needed(ds, &segment) + .await + .unwrap() + { + Some(files) => lance_table::format::IndexMetadata { + files: Some(index_files_to_table(files)), + ..segment + }, + None => segment, } } diff --git a/rust/lance/src/index/append.rs b/rust/lance/src/index/append.rs index 65c4282160f..f75759019a3 100644 --- a/rust/lance/src/index/append.rs +++ b/rust/lance/src/index/append.rs @@ -5346,13 +5346,15 @@ mod tests { ); // Relabel below `INVERTED_ROW_ADDR_DOMAIN_VERSION` so the index reads - // as a pre-migration one. Its postings are still addresses, which is - // fine here: the rebuild this test asserts discards the segment's data - // and rescans, so only the label is ever consulted. - let legacy_segment = IndexMetadata { - index_version: 3, - ..segment - }; + // as a pre-migration one, rewriting its docs files to name that + // domain's identity column: FTS is the one type whose stored layout + // differs between the domains, and a segment whose file and version + // disagree is rejected at load. Its postings are still addresses, + // which is what a dataset that enabled stable row ids after the index + // was built would hold. + let legacy_segment = crate::utils::test::as_legacy_row_id_fts_segment(&dataset, segment) + .await + .unwrap(); dataset .commit_existing_index_segments("body_idx", "body", vec![legacy_segment]) .await @@ -7001,7 +7003,16 @@ mod tests { .execute_uncommitted() .await .unwrap(); - let legacy_segment = crate::utils::test::as_legacy_row_id_segment(segment); + // FTS stores its identities under a column named for its domain, + // so a legacy FTS segment needs its files rewritten, not just its + // version relabelled (see `as_legacy_row_id_fts_segment`). + let legacy_segment = if index_type == IndexType::Inverted { + crate::utils::test::as_legacy_row_id_fts_segment(&dataset, segment) + .await + .unwrap() + } else { + crate::utils::test::as_legacy_row_id_segment(segment) + }; let name = legacy_segment.name.clone(); dataset .commit_existing_index_segments(&name, "cat", vec![legacy_segment]) diff --git a/rust/lance/src/index/remap.rs b/rust/lance/src/index/remap.rs index 412f384e12b..7190bb93119 100644 --- a/rust/lance/src/index/remap.rs +++ b/rust/lance/src/index/remap.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use lance_core::utils::address::RowAddress; use lance_index::scalar::RowAddrTranslator; -use lance_index::scalar::inverted::InvertedIndexPlugin; +use lance_index::scalar::inverted::{INVERTED_ROW_ADDR_DOMAIN_VERSION, InvertedIndexPlugin}; use lance_index::scalar::lance_format::LanceIndexStore; use lance_index::scalar::registry::{TrainingCriteria, TrainingOrdering}; use lance_index::scalar::{CreatedIndex, index_files_to_table, table_files_to_index}; @@ -208,22 +208,36 @@ pub(crate) async fn remap_index( index_id, field_path ); + // An FTS segment trains from row addresses whatever + // domain it is committed in, so the scan has to carry + // them -- without this the rebuilt segment would have + // no identity column at all. The version follows the + // dataset the same way `build_scalar_index` picks it: + // row-address domain under stable row ids, and + // otherwise the pre-migration version, where a row id + // and a row address are the same value. + let index_version = if dataset.manifest.uses_stable_row_ids() { + INVERTED_ROW_ADDR_DOMAIN_VERSION + } else { + InvertedIndexPlugin::legacy_index_version(inverted_index.params()) + }; let training_data = load_training_data( dataset, &field_path, - &TrainingCriteria::new(TrainingOrdering::None), + &TrainingCriteria::new(TrainingOrdering::None).with_row_addr(), None, true, // Legacy reindexing should always train None, TrainingScanOptions::default(), ) .await?; - InvertedIndexPlugin::train_inverted_index( + InvertedIndexPlugin::train_inverted_index_at_version( training_data, &new_store, inverted_index.params().clone(), None, Arc::new(NoopIndexBuildProgress), + index_version, ) .await? } else { diff --git a/rust/lance/src/index/scalar.rs b/rust/lance/src/index/scalar.rs index d21984ea334..7b03d6602d0 100644 --- a/rust/lance/src/index/scalar.rs +++ b/rust/lance/src/index/scalar.rs @@ -575,9 +575,9 @@ pub(super) async fn build_scalar_index( let mut training_request = trainer.new_training_request(params.params.as_deref().unwrap_or("{}"), &field)?; // Only the plugin knows whether its stored layout depends on this, and the - // default is a no-op. FTS uses it to name its document identity column for - // the `index_version` the segment will actually be committed with -- see - // the relabeling below. + // default is a no-op. FTS uses it to choose the `index_version` it trains + // at, which in turn names its document identity column -- the relabeling + // below covers the types whose version is a single fixed constant. training_request.set_stable_row_ids(dataset.manifest.uses_stable_row_ids()); // A zone map trained from the table reuses the write seeds its fragments @@ -700,19 +700,12 @@ pub(super) async fn build_scalar_index( // plugin would, so the same relabeling applies to a wrapped BTree, // Bitmap, or LabelList. lance_index::scalar::json::relabel_as_row_id_domain(&mut created_index)?; - } else if params - .index_type - .eq_ignore_ascii_case(BuiltinIndexType::Inverted.as_str()) - || params.index_type.eq_ignore_ascii_case("fts") - { - // Inverted always trains on physical row addresses too, but its - // pre-migration version varies with the chosen posting format - // (and document granularity), unlike the single fixed constant - // `row_id_domain_version` returns for the other types above. - lance_index::scalar::inverted::InvertedIndexPlugin::relabel_as_row_id_domain( - &mut created_index, - )?; } + // Inverted needs nothing here: its pre-migration version varies with + // the chosen posting format and document granularity, so it is settled + // before training instead (`set_stable_row_ids` on its training + // request) -- which is also what makes it write that version's + // identity column. } Ok(created_index) diff --git a/rust/lance/src/index/scalar/inverted.rs b/rust/lance/src/index/scalar/inverted.rs index b6726a23b13..a1a7eafee38 100644 --- a/rust/lance/src/index/scalar/inverted.rs +++ b/rust/lance/src/index/scalar/inverted.rs @@ -24,7 +24,8 @@ use lance_index::progress::IndexBuildProgress; use lance_index::scalar::inverted::builder::{FinalizeOptions, finalize_staged_index_to}; use lance_index::scalar::inverted::is_inverted_details_type; use lance_index::scalar::inverted::{ - DocumentGranularity, InvertedIndex, InvertedIndexParams, doc_index_storage_column, + DocumentGranularity, INVERTED_ROW_ADDR_DOMAIN_VERSION, InvertedIndex, InvertedIndexParams, + doc_index_storage_column, }; use lance_index::scalar::lance_format::LanceIndexStore; use lance_index::scalar::registry::VALUE_COLUMN_NAME; @@ -876,14 +877,17 @@ pub(crate) fn transform_fts_document_stream( /// Fill legacy posting-format metadata while leaving protobuf-default row /// document granularity untouched. /// -/// `index_version` 4 ([`lance_index::scalar::inverted::INVERTED_ROW_ADDR_DOMAIN_VERSION`]) -/// marks row-address-domain segments; it is independent of the posting-list -/// format, which every such segment already carries explicitly in -/// `details.posting_format_version` (see `InvertedIndexPlugin::train_inverted_index`). -/// The fallback below still maps version 4 to posting format V3, the newest -/// format and the only one a version-4 segment is ever written with, so that a -/// segment reaching here without the field -- which a correct writer never -/// produces -- is read rather than rejected. +/// Below [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] the two were one axis: a segment +/// that predates `details.posting_format_version` has its posting format +/// implied by its `index_version`, so that is what the fallback recovers. +/// +/// From [`INVERTED_ROW_ADDR_DOMAIN_VERSION`] they are independent -- the +/// version records the identity domain and the posting format is whatever the +/// parameters asked for, V1 included -- so there is nothing to infer. Every +/// writer of such a segment records the field, so one arriving without it is +/// rejected rather than guessed at: guessing would mean readers carrying a +/// lenient fallback for the life of the format, and silently misreading any +/// segment the guess got wrong. pub(crate) fn normalize_inverted_details( index: &IndexMetadata, mut details: InvertedIndexDetails, @@ -898,8 +902,15 @@ pub(crate) fn normalize_inverted_details( let posting_format_version = match index.index_version { 0 | 1 => 1, 2 => 2, - 3 | 4 => 3, - _ => unreachable!("index version was validated above"), + 3 => 3, + _ => { + return Err(Error::invalid_input(format!( + "FTS index '{}' is at index_version {} but records no \ + posting_format_version; from version {} the two are independent and \ + every writer records it", + index.name, index.index_version, INVERTED_ROW_ADDR_DOMAIN_VERSION + ))); + } }; details.posting_format_version = Some(posting_format_version); } diff --git a/rust/lance/src/index/tests/optimize.rs b/rust/lance/src/index/tests/optimize.rs index a390bca2818..d7ea9c0af4b 100644 --- a/rust/lance/src/index/tests/optimize.rs +++ b/rust/lance/src/index/tests/optimize.rs @@ -1497,7 +1497,13 @@ async fn test_optimize_skips_an_index_with_an_unavailable_tokenizer( let details = if has_manifest_tokenizer { InvertedIndexDetails::try_from(¶ms).unwrap() } else { - InvertedIndexDetails::default() + // Model details that carry no tokenizer configuration -- the case + // under test -- while still recording the posting format, which every + // writer of this segment's index_version does. + InvertedIndexDetails { + posting_format_version: Some(params.resolved_format_version().index_version()), + ..Default::default() + } }; segment.index_details = Some(Arc::new(prost_types::Any::from_msg(&details).unwrap())); dataset diff --git a/rust/lance/src/io/exec/fts/combined_fields.rs b/rust/lance/src/io/exec/fts/combined_fields.rs index 17de13d16de..dc586a466ec 100644 --- a/rust/lance/src/io/exec/fts/combined_fields.rs +++ b/rust/lance/src/io/exec/fts/combined_fields.rs @@ -450,18 +450,22 @@ pub(super) async fn open_combined_fields_scan( // `bm25_row_stats_for_terms` compares it to the index's stored // identifiers, physical addresses for the address-domain index every // fresh build now produces (see `INVERTED_ROW_ADDR_DOMAIN_VERSION`). + // + // Translate only where the two domains can actually differ, matching + // `row_id_mask_to_row_addr_domain`: without stable row ids a row id is + // already that address, and translating anyway would reject a + // legitimate whole-fragment entry as a mislabelled mask. The domain is + // this column's own, which is what its stats are compared against; a + // query whose columns disagree is rejected below, where their segments + // are resolved together. + let column_is_address_domain = dataset.manifest.uses_stable_row_ids() + && indices + .first() + .is_some_and(|index| index.results_are_row_addresses()); let column_stale_rows = match stale_rows.get(slot).filter(|rows| !rows.is_empty()) { - Some(rows) - if !dataset.manifest.uses_stable_row_ids() - || indices - .first() - .is_some_and(|index| index.results_are_row_addresses()) => - { - Some(Arc::new( - crate::io::exec::utils::translate_treemap_to_row_addr_domain(dataset, rows) - .await?, - )) - } + Some(rows) if column_is_address_domain => Some(Arc::new( + crate::io::exec::utils::translate_treemap_to_row_addr_domain(dataset, rows).await?, + )), other => other.cloned(), }; columns.push(CombinedFieldColumn { diff --git a/rust/lance/src/io/exec/fts/segments.rs b/rust/lance/src/io/exec/fts/segments.rs index a7260c9761e..c8cad711ab0 100644 --- a/rust/lance/src/io/exec/fts/segments.rs +++ b/rust/lance/src/io/exec/fts/segments.rs @@ -178,6 +178,15 @@ pub(super) async fn open_fts_segments( // disagree fails loudly rather than answering from two numbering systems // at once. fts_segments_are_address_domain(dataset, segments)?; + // Deliberately the segment's own declared domain rather than the `true` + // the check just returned: that answer is about whether the *results* + // need translating, and it is `true` for every segment once stable row + // ids are off. This asks the different question of how to read the + // identifiers a segment stores, which is what its `index_version` says. + // The two agree wherever it matters -- under stable row ids the check + // above has already rejected any disagreement, and without them a row id + // and a row address are the same value, so coverage resolves identically + // either way. let row_domain = match segments.first() { Some(first) if first.results_are_row_addrs() => SegmentRowDomain::RowAddress, _ => SegmentRowDomain::RowId, diff --git a/rust/lance/src/utils/test.rs b/rust/lance/src/utils/test.rs index 68a74de55d4..2e6229770c0 100644 --- a/rust/lance/src/utils/test.rs +++ b/rust/lance/src/utils/test.rs @@ -1369,3 +1369,116 @@ pub fn as_legacy_row_id_segment( ..segment } } + +/// Rewrite every `docs.lance` in `store` to name its identity column +/// [`lance_core::ROW_ID`], as a pre-`INVERTED_ROW_ADDR_DOMAIN_VERSION` writer +/// did. The values are untouched: on a dataset that turned stable row ids on +/// after the index was built, they are exactly the addresses such a writer +/// would have stored. +#[cfg(test)] +pub async fn rewrite_fts_docs_to_row_id_column( + dataset: &Dataset, + uuid: &uuid::Uuid, +) -> crate::Result<()> { + use arrow_schema::{Field, Schema}; + use lance_core::cache::LanceCache; + use lance_index::scalar::IndexStore; + use lance_index::scalar::inverted::METADATA_FILE; + use lance_index::scalar::inverted::builder::doc_file_path; + use lance_index::scalar::lance_format::LanceIndexStore; + + // Deliberately cache-free: a store that already read these files would + // serve their old schema back from cache after the rewrite. + let store = LanceIndexStore::new( + dataset.table_state.object_store.clone(), + dataset.indices_dir().join(uuid.to_string()), + Arc::new(LanceCache::no_cache()), + ); + let store = &store; + let metadata = store.open_index_file(METADATA_FILE).await?; + let partitions: Vec = serde_json::from_str( + metadata + .schema() + .metadata + .get("partitions") + .expect("an FTS segment records its partitions"), + )?; + for partition in partitions { + let path = doc_file_path(partition); + let reader = store.open_index_file(&path).await?; + let batch = reader.read_range(0..reader.num_rows(), None).await?; + let fields = batch + .schema() + .fields() + .iter() + .map(|field| { + if field.name() == lance_core::ROW_ADDR { + Arc::new(Field::new( + lance_core::ROW_ID, + field.data_type().clone(), + field.is_nullable(), + )) + } else { + field.clone() + } + }) + .collect::>(); + let schema = Arc::new(Schema::new(fields)); + let renamed = arrow_array::RecordBatch::try_new(schema.clone(), batch.columns().to_vec())?; + let mut writer = store.new_index_file(&path, schema).await?; + writer.write_record_batch(renamed).await?; + writer + .finish_with_metadata(reader.schema().metadata.clone()) + .await?; + } + Ok(()) +} + +/// Relabel a freshly built Inverted segment as a pre-migration row-id-domain +/// one *and rewrite its document files to match*, so the result is a segment a +/// pre-migration writer could actually have produced. +/// +/// Unlike [`as_legacy_row_id_segment`], this is safe to open and query: FTS is +/// the one migrated type whose stored layout differs between the domains (the +/// `docs.lance` identity column is named for the domain it holds, and +/// `InvertedIndex::load` rejects a segment where the two disagree), so a bare +/// relabel would produce a file no writer makes. The stored identifiers are +/// still row addresses, which is what a dataset that enabled stable row ids +/// after the index was built would have. +#[cfg(test)] +pub async fn as_legacy_row_id_fts_segment( + dataset: &Dataset, + segment: lance_table::format::IndexMetadata, +) -> crate::Result { + use crate::dataset::index::LanceIndexStoreExt; + use lance_index::scalar::IndexStore; + use lance_index::scalar::index_files_to_table; + use lance_index::scalar::inverted::{InvertedIndexParams, InvertedIndexPlugin, METADATA_FILE}; + use lance_index::scalar::lance_format::LanceIndexStore; + + rewrite_fts_docs_to_row_id_column(dataset, &segment.uuid).await?; + let store = LanceIndexStore::from_dataset_for_new(dataset, &segment.uuid)?; + + // The version a pre-migration writer would have stamped for these + // parameters, so the relabelled segment is one such a writer could produce. + let params = store + .open_index_file(METADATA_FILE) + .await? + .schema() + .metadata + .get("params") + .map(|params| serde_json::from_str::(params)) + .transpose()? + .unwrap_or_default(); + let mut segment = lance_table::format::IndexMetadata { + index_version: InvertedIndexPlugin::legacy_index_version(¶ms) as i32, + ..segment + }; + // The rewrite changed the files on disk, so any recorded sizes are stale. + if let Some(files) = + crate::index::scalar::inverted::finalize_segment_files_if_needed(dataset, &segment).await? + { + segment.files = Some(index_files_to_table(files)); + } + Ok(segment) +} From 4c18d9834356c32c2b0f3efe4c43aea39bcaecf5 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Mon, 30 Nov 2026 16:44:05 -0800 Subject: [PATCH 15/15] fix(fts): translate a legacy FTS rebuild's scan onto the rewrite's addresses Gatekeeper found that giving remap.rs's legacy reindex its missing identity column let the path complete without making its output valid: the rebuild rescans the dataset as it stands *before* the rewrite commits, so its postings hold addresses the commit is about to retire, while the commit replaces the index's coverage with the destination fragments. Eager compaction then succeeded and the same query went from matches to none, with no error -- worse than the panic the missing column used to cause. The scan now runs through the same old-to-new address map the in-place remap path applies (materializing a batch translator the way `remap_streaming` does), dropping the rows it deletes, so the rebuilt segment lands in the committed snapshot's address space. Covered by `test_legacy_fts_index_survives_eager_compaction`, which is the gatekeeper's reproducer over the checked-in 0.27.0 fixture: it reports 0 rows before this change and 2 after. Co-Authored-By: Claude Opus 5 --- rust/lance/src/index/remap.rs | 74 ++++++++++++++++++++++++++++- rust/lance/src/index/remap/tests.rs | 51 ++++++++++++++++++++ 2 files changed, 124 insertions(+), 1 deletion(-) diff --git a/rust/lance/src/index/remap.rs b/rust/lance/src/index/remap.rs index 7190bb93119..c862e2b2b6c 100644 --- a/rust/lance/src/index/remap.rs +++ b/rust/lance/src/index/remap.rs @@ -10,12 +10,18 @@ use super::field_dependencies::input_field_ids; use std::sync::Arc; +use arrow_array::RecordBatch; +use datafusion::error::DataFusionError; +use datafusion_physical_plan::SendableRecordBatchStream; +use datafusion_physical_plan::stream::RecordBatchStreamAdapter; +use lance_core::ROW_ADDR; use lance_core::utils::address::RowAddress; -use lance_index::scalar::RowAddrTranslator; +use lance_core::utils::row_addr_remap::RowAddrRemap; use lance_index::scalar::inverted::{INVERTED_ROW_ADDR_DOMAIN_VERSION, InvertedIndexPlugin}; use lance_index::scalar::lance_format::LanceIndexStore; use lance_index::scalar::registry::{TrainingCriteria, TrainingOrdering}; use lance_index::scalar::{CreatedIndex, index_files_to_table, table_files_to_index}; +use lance_index::scalar::{RowAddrTranslator, materialize_remap}; use lance_index::{IndexType, metrics::NoOpMetricsCollector, progress::NoopIndexBuildProgress}; use roaring::RoaringBitmap; use uuid::Uuid; @@ -32,6 +38,51 @@ use crate::index::vector::details::vector_index_details_default; use crate::index::vector::remap_vector_index; use crate::{Dataset, Error, Result}; +/// Rewrite a training scan's `_rowaddr` column through `mapping`, dropping the +/// rows it deletes. +/// +/// A rebuild during a rewrite scans the dataset as it stands *before* the +/// commit, so its addresses are the ones the rewrite is about to retire. +/// Training on them directly would publish an index whose postings point at +/// fragments the commit removes -- queries would find nothing and report no +/// error. `mapping` is the same old-to-new address map the in-place remap +/// path applies, so running the scan through it puts the rebuilt segment in +/// the committed snapshot's address space. +fn remap_training_stream( + stream: SendableRecordBatchStream, + mapping: Arc, +) -> SendableRecordBatchStream { + use arrow_array::cast::AsArray; + use arrow_array::types::UInt64Type; + use arrow_array::{BooleanArray, UInt64Array}; + use futures::StreamExt; + + let schema = stream.schema(); + let mapped = stream.map(move |batch| { + let batch = batch?; + let Some(column) = batch.column_by_name(ROW_ADDR) else { + return Err(DataFusionError::Execution(format!( + "a rebuild during a rewrite needs `{ROW_ADDR}` to translate its scan, but the \ + training data does not carry it" + ))); + }; + let mut addrs = column + .as_primitive_opt::() + .ok_or_else(|| DataFusionError::Execution(format!("`{ROW_ADDR}` is not a u64 column")))? + .iter() + .collect::>(); + mapping.remap_in_place(&mut addrs); + let keep = BooleanArray::from_iter(addrs.iter().map(|addr| Some(addr.is_some()))); + let translated: UInt64Array = addrs.into_iter().flatten().collect(); + let batch = arrow::compute::filter_record_batch(&batch, &keep)?; + let index = batch.schema().index_of(ROW_ADDR)?; + let mut columns = batch.columns().to_vec(); + columns[index] = Arc::new(translated); + Ok(RecordBatch::try_new(batch.schema(), columns)?) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, mapped)) +} + /// Addresses checked per translation while deciding whether a remap deletes /// every indexed row; the check stops at the first surviving row. const REMAP_DELETE_CHECK_BATCH: u32 = 64 * 1024; @@ -231,6 +282,27 @@ pub(crate) async fn remap_index( TrainingScanOptions::default(), ) .await?; + // The scan above reads the dataset this rewrite is + // about to replace, so its addresses have to be moved + // into the committed snapshot's space before they are + // indexed (see `remap_training_stream`). + let mapping = match row_id_map { + RowAddrTranslator::Sync(mapping) => mapping.clone(), + RowAddrTranslator::Batch(remapper) => Arc::new( + materialize_remap( + remapper.as_ref(), + scalar_index.stored_fragments().as_ref(), + ) + .await?, + ), + other => { + return Err(Error::index(format!( + "rebuilding a legacy full-text index during a rewrite does \ + not support the {other:?} translator; rebuild the index" + ))); + } + }; + let training_data = remap_training_stream(training_data, mapping); InvertedIndexPlugin::train_inverted_index_at_version( training_data, &new_store, diff --git a/rust/lance/src/index/remap/tests.rs b/rust/lance/src/index/remap/tests.rs index b228734ec8e..eecddd38388 100644 --- a/rust/lance/src/index/remap/tests.rs +++ b/rust/lance/src/index/remap/tests.rs @@ -326,3 +326,54 @@ async fn test_remap_index_drops_a_covered_index(#[case] keys_only: bool) { .unwrap(); assert_eq!(result, RemapResult::Drop); } + +/// A legacy-format FTS index cannot be remapped in place, so a rewrite +/// rebuilds it by rescanning -- and that scan sees the addresses the rewrite +/// is about to retire. Without translating them the rebuilt index points at +/// fragments the commit removes, and the same query silently returns nothing +/// rather than failing. +#[tokio::test] +async fn test_legacy_fts_index_survives_eager_compaction() { + use crate::dataset::optimize::{CompactionOptions, compact_files}; + use lance_index::scalar::FullTextSearchQuery; + let dir = copy_test_data_to_tmp("0.27.0/legacy_fts_index").unwrap(); + let mut dataset = Dataset::open(&dir.path_str()).await.unwrap(); + dataset.delete("contains(text, 'happy')").await.unwrap(); + let before = dataset + .scan() + .full_text_search(FullTextSearchQuery::new("puppy".into())) + .unwrap() + .try_into_batch() + .await + .unwrap(); + assert_eq!(before.num_rows(), 2); + let metrics = compact_files( + &mut dataset, + CompactionOptions { + defer_index_remap: false, + materialize_deletions: true, + materialize_deletions_threshold: 0.1, + ..Default::default() + }, + None, + ) + .await + .unwrap(); + assert!( + metrics.fragments_removed > 0, + "compaction must rewrite the indexed fragment" + ); + assert_eq!(dataset.count_rows(None).await.unwrap(), 2); + let after = dataset + .scan() + .full_text_search(FullTextSearchQuery::new("puppy".into())) + .unwrap() + .try_into_batch() + .await + .unwrap(); + assert_eq!( + after.num_rows(), + before.num_rows(), + "legacy indexed rows must survive eager compaction" + ); +}